import { useState, useEffect } from 'react';
import { useForm } from '@inertiajs/react';
import FormModal from '@/Components/FormModal';
import { formatCurrency, formatMonth } from '@/utils';

export default function PaymentModal({ show, onClose, lease }) {
    const unpaidInvoices = (lease?.invoices || []).filter(
        (inv) => inv.status === 'pending' || inv.status === 'partial' || inv.status === 'overdue'
    );

    const { data, setData, post, processing, errors, reset } = useForm({
        invoice_id: '',
        amount_paid: '',
        payment_date: new Date().toISOString().slice(0, 10),
        payment_method: 'cash',
        received_by: '',
        remarks: '',
        proof_file: null,
    });

    const [selectedInvoice, setSelectedInvoice] = useState(null);

    // Reset form when modal opens/closes
    useEffect(() => {
        if (show) {
            reset();
            setSelectedInvoice(null);
        }
    }, [show]);

    // Update selected invoice details when invoice_id changes
    useEffect(() => {
        if (data.invoice_id) {
            const inv = unpaidInvoices.find((i) => i.id === parseInt(data.invoice_id));
            if (inv) {
                setSelectedInvoice(inv);
                const paid = parseFloat(inv.payments_sum_amount_paid || 0);
                const remaining = parseFloat(inv.total_amount) - paid;
                setData('amount_paid', remaining.toFixed(2));
            }
        } else {
            setSelectedInvoice(null);
        }
    }, [data.invoice_id]);

    const handleSubmit = (e) => {
        e.preventDefault();
        post(route('payments.store'), {
            onSuccess: () => {
                reset();
                setSelectedInvoice(null);
                onClose();
            },
            forceFormData: true,
        });
    };

    const remaining = selectedInvoice
        ? parseFloat(selectedInvoice.total_amount) - parseFloat(selectedInvoice.payments_sum_amount_paid || 0)
        : 0;

    return (
        <FormModal show={show} onClose={onClose} title="Record Payment" maxWidth="lg">
            {/* Lease Info Header */}
            <div className="mb-5 rounded-xl bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-100 p-4">
                <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-600 text-white">
                        <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" strokeWidth="1.5" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M2.25 21h19.5M3.75 3v18m16.5-18v18M5.25 3h13.5M5.25 21V6.75a.75.75 0 0 1 .75-.75h3a.75.75 0 0 1 .75.75V21m7.5-14.25v14.25m-7.5-14.25h7.5" />
                        </svg>
                    </div>
                    <div>
                        <p className="text-sm font-semibold text-gray-900">
                            Shop #{lease?.shop?.shop_number} — {lease?.tenant?.name}
                        </p>
                        <p className="text-xs text-gray-500">
                            Agreed Rent: {formatCurrency(lease?.agreed_rent)} • Owner: {lease?.shop?.owner?.name}
                        </p>
                    </div>
                </div>
            </div>

            {unpaidInvoices.length === 0 ? (
                <div className="rounded-xl border-2 border-dashed border-green-200 bg-green-50 p-8 text-center">
                    <div className="mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-full bg-green-100">
                        <svg className="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                        </svg>
                    </div>
                    <p className="text-sm font-medium text-green-800">All invoices are paid!</p>
                    <p className="text-xs text-green-600 mt-1">No pending payments for this lease.</p>
                </div>
            ) : (
                <form onSubmit={handleSubmit} className="space-y-4">
                    {/* Invoice Selection */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            Select Invoice <span className="text-red-500">*</span>
                        </label>
                        <select
                            value={data.invoice_id}
                            onChange={(e) => setData('invoice_id', e.target.value)}
                            className="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
                        >
                            <option value="">— Choose an invoice —</option>
                            {unpaidInvoices.map((inv) => {
                                const paid = parseFloat(inv.payments_sum_amount_paid || 0);
                                const rem = parseFloat(inv.total_amount) - paid;
                                return (
                                    <option key={inv.id} value={inv.id}>
                                        {inv.invoice_number} • {formatMonth(inv.month)} • Due: {formatCurrency(inv.total_amount)} • Remaining: {formatCurrency(rem)}
                                    </option>
                                );
                            })}
                        </select>
                        {errors.invoice_id && <p className="mt-1 text-xs text-red-600">{errors.invoice_id}</p>}
                    </div>

                    {/* Invoice Detail Card */}
                    {selectedInvoice && (
                        <div className="rounded-lg border border-amber-200 bg-amber-50 p-3">
                            <div className="grid grid-cols-3 gap-3 text-center">
                                <div>
                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Total</p>
                                    <p className="text-sm font-bold text-gray-900">{formatCurrency(selectedInvoice.total_amount)}</p>
                                </div>
                                <div>
                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Paid</p>
                                    <p className="text-sm font-bold text-green-600">{formatCurrency(selectedInvoice.payments_sum_amount_paid || 0)}</p>
                                </div>
                                <div>
                                    <p className="text-[10px] font-medium text-gray-500 uppercase">Remaining</p>
                                    <p className="text-sm font-bold text-red-600">{formatCurrency(remaining)}</p>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Amount & Date */}
                    <div className="grid grid-cols-2 gap-4">
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Amount <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="number"
                                step="0.01"
                                min="1"
                                max={remaining || undefined}
                                value={data.amount_paid}
                                onChange={(e) => setData('amount_paid', e.target.value)}
                                className="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
                                placeholder="0.00"
                            />
                            {errors.amount_paid && <p className="mt-1 text-xs text-red-600">{errors.amount_paid}</p>}
                        </div>
                        <div>
                            <label className="block text-sm font-medium text-gray-700 mb-1">
                                Payment Date <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="date"
                                value={data.payment_date}
                                onChange={(e) => setData('payment_date', e.target.value)}
                                className="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
                            />
                            {errors.payment_date && <p className="mt-1 text-xs text-red-600">{errors.payment_date}</p>}
                        </div>
                    </div>

                    {/* Payment Method */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-2">
                            Payment Method <span className="text-red-500">*</span>
                        </label>
                        <div className="grid grid-cols-3 gap-2">
                            {[
                                { value: 'cash', label: 'Cash', icon: '💵' },
                                { value: 'bank_transfer', label: 'Bank Transfer', icon: '🏦' },
                                { value: 'online', label: 'Online', icon: '📱' },
                            ].map((method) => (
                                <button
                                    key={method.value}
                                    type="button"
                                    onClick={() => setData('payment_method', method.value)}
                                    className={`flex items-center justify-center gap-1.5 rounded-lg border-2 px-3 py-2.5 text-sm font-medium transition-all ${
                                        data.payment_method === method.value
                                            ? 'border-blue-500 bg-blue-50 text-blue-700 shadow-sm'
                                            : 'border-gray-200 text-gray-600 hover:border-gray-300 hover:bg-gray-50'
                                    }`}
                                >
                                    <span>{method.icon}</span>
                                    <span>{method.label}</span>
                                </button>
                            ))}
                        </div>
                        {errors.payment_method && <p className="mt-1 text-xs text-red-600">{errors.payment_method}</p>}
                    </div>

                    {/* Cash - Received By */}
                    {data.payment_method === 'cash' && (
                        <div className="rounded-lg border border-amber-200 bg-amber-50 p-3">
                            <label className="block text-sm font-medium text-amber-800 mb-1">
                                💰 Received By (Cash Payment) <span className="text-red-500">*</span>
                            </label>
                            <input
                                type="text"
                                value={data.received_by}
                                onChange={(e) => setData('received_by', e.target.value)}
                                className="w-full rounded-lg border-amber-300 bg-white shadow-sm focus:border-amber-500 focus:ring-amber-500 text-sm"
                                placeholder="Name of person receiving cash..."
                            />
                            {errors.received_by && <p className="mt-1 text-xs text-red-600">{errors.received_by}</p>}
                        </div>
                    )}

                    {/* Proof File */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Proof / Receipt (optional)</label>
                        <input
                            type="file"
                            onChange={(e) => setData('proof_file', e.target.files[0])}
                            className="w-full rounded-lg border border-gray-300 text-sm file:mr-3 file:rounded-l-lg file:border-0 file:bg-gray-100 file:px-4 file:py-2 file:text-sm file:font-medium file:text-gray-700 hover:file:bg-gray-200"
                            accept="image/*,.pdf"
                        />
                        {errors.proof_file && <p className="mt-1 text-xs text-red-600">{errors.proof_file}</p>}
                    </div>

                    {/* Remarks */}
                    <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">Remarks (optional)</label>
                        <textarea
                            value={data.remarks}
                            onChange={(e) => setData('remarks', e.target.value)}
                            rows="2"
                            className="w-full rounded-lg border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 text-sm"
                            placeholder="Any additional notes..."
                        />
                        {errors.remarks && <p className="mt-1 text-xs text-red-600">{errors.remarks}</p>}
                    </div>

                    {/* Submit */}
                    <div className="flex items-center justify-end gap-3 pt-2 border-t border-gray-100">
                        <button
                            type="button"
                            onClick={onClose}
                            className="rounded-lg border border-gray-300 px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                        >
                            Cancel
                        </button>
                        <button
                            type="submit"
                            disabled={processing || !data.invoice_id}
                            className="inline-flex items-center gap-2 rounded-lg bg-blue-600 px-5 py-2 text-sm font-medium text-white hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                            {processing ? (
                                <>
                                    <svg className="h-4 w-4 animate-spin" fill="none" viewBox="0 0 24 24">
                                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
                                    </svg>
                                    Processing...
                                </>
                            ) : (
                                <>
                                    <svg className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth="2" stroke="currentColor">
                                        <path strokeLinecap="round" strokeLinejoin="round" d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" />
                                    </svg>
                                    Record Payment
                                </>
                            )}
                        </button>
                    </div>
                </form>
            )}
        </FormModal>
    );
}
