import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout';
import { Head, Link, useForm, router } from '@inertiajs/react';
import { formatCurrency, formatDate, formatMonth } from '@/utils';

export default function Create({ leases, defaultRate }) {
    const { data, setData, post, processing, errors } = useForm({
        lease_id: '',
        month: new Date().toISOString().slice(0, 7),
        previous_reading: '',
        current_reading: '',
        rate_per_unit: defaultRate || '',
    });

    const units = (parseFloat(data.current_reading) || 0) - (parseFloat(data.previous_reading) || 0);
    const amount = units > 0 ? units * (parseFloat(data.rate_per_unit) || 0) : 0;

    const handleSubmit = (e) => {
        e.preventDefault();
        post(route('meter-readings.store'));
    };

    return (
        <AuthenticatedLayout header={<h2 className="text-xl font-semibold leading-tight text-gray-800">Add Meter Reading</h2>}>
            <Head title="Add Meter Reading" />

            <div className="py-12">
                <div className="mx-auto max-w-2xl sm:px-6 lg:px-8">
                    <div className="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                        <div className="p-6 text-gray-900">
                            <div className="flex items-center justify-between mb-6">
                                <h3 className="text-lg font-medium">New Meter Reading</h3>
                                <Link href={route('meter-readings.index')} className="inline-flex items-center rounded-md bg-gray-200 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-300">Back</Link>
                            </div>

                            <form onSubmit={handleSubmit} className="space-y-6">
                                {/* Lease */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Shop / Tenant <span className="text-red-500">*</span></label>
                                    <select
                                        value={data.lease_id}
                                        onChange={(e) => setData('lease_id', e.target.value)}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                    >
                                        <option value="">Select shop / tenant...</option>
                                        {leases.map((lease) => (
                                            <option key={lease.id} value={lease.id}>
                                                Shop {lease.shop?.shop_number} - {lease.tenant?.name}
                                            </option>
                                        ))}
                                    </select>
                                    {errors.lease_id && <p className="mt-1 text-sm text-red-600">{errors.lease_id}</p>}
                                </div>

                                {/* Month */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Month <span className="text-red-500">*</span></label>
                                    <input
                                        type="month"
                                        value={data.month}
                                        onChange={(e) => setData('month', e.target.value)}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                    />
                                    {errors.month && <p className="mt-1 text-sm text-red-600">{errors.month}</p>}
                                </div>

                                {/* Previous Reading */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Previous Reading <span className="text-red-500">*</span></label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        value={data.previous_reading}
                                        onChange={(e) => setData('previous_reading', e.target.value)}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                        placeholder="Enter previous reading"
                                    />
                                    {errors.previous_reading && <p className="mt-1 text-sm text-red-600">{errors.previous_reading}</p>}
                                </div>

                                {/* Current Reading */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Current Reading <span className="text-red-500">*</span></label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        value={data.current_reading}
                                        onChange={(e) => setData('current_reading', e.target.value)}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                        placeholder="Enter current reading"
                                    />
                                    {errors.current_reading && <p className="mt-1 text-sm text-red-600">{errors.current_reading}</p>}
                                </div>

                                {/* Rate Per Unit */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Rate Per Unit (PKR) <span className="text-red-500">*</span></label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        min="0"
                                        value={data.rate_per_unit}
                                        onChange={(e) => setData('rate_per_unit', e.target.value)}
                                        className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500"
                                    />
                                    {errors.rate_per_unit && <p className="mt-1 text-sm text-red-600">{errors.rate_per_unit}</p>}
                                </div>

                                {/* Live Calculation */}
                                {data.previous_reading !== '' && data.current_reading !== '' && (
                                    <div className="rounded-lg border border-blue-200 bg-blue-50 p-4">
                                        <div className="grid grid-cols-2 gap-4 text-sm">
                                            <div>
                                                <span className="text-gray-500">Units Consumed</span>
                                                <p className="font-semibold text-gray-900">{units > 0 ? units.toFixed(2) : '0.00'}</p>
                                            </div>
                                            <div>
                                                <span className="text-gray-500">Total Amount</span>
                                                <p className="font-bold text-blue-800">{formatCurrency(amount)}</p>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* Submit */}
                                <div className="flex items-center justify-end gap-4">
                                    <Link href={route('meter-readings.index')} className="text-sm text-gray-600 hover:text-gray-900">Cancel</Link>
                                    <button
                                        type="submit"
                                        disabled={processing}
                                        className="inline-flex items-center rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50"
                                    >
                                        {processing ? 'Saving...' : 'Save Reading'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
