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

export default function Edit({ expense, categories }) {
    const { data, setData, post, processing, errors } = useForm({
        _method: 'PUT',
        type: expense.type || 'cash_out',
        category_id: expense.category_id || '',
        amount: expense.amount || '',
        description: expense.description || '',
        date: expense.date ? expense.date.split('T')[0] : '',
        reference_no: expense.reference_no || '',
        proof_file: null,
    });

    const filteredCategories = useMemo(() => {
        if (!data.type) return categories;
        return categories.filter((cat) => cat.type === data.type);
    }, [data.type, categories]);

    const handleTypeChange = (type) => {
        setData((prev) => ({
            ...prev,
            type,
            category_id: '',
        }));
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        post(route('expenses.update', expense.id), { forceFormData: true });
    };

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

            <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">Edit Cash Book Entry</h3>
                                <Link href={route('expenses.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">
                                {/* Type */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700 mb-2">Type <span className="text-red-500">*</span></label>
                                    <div className="flex gap-4">
                                        <label className={`flex items-center gap-2 cursor-pointer rounded-lg border px-4 py-3 ${data.type === 'cash_in' ? 'border-green-500 bg-green-50' : 'border-gray-200'}`}>
                                            <input
                                                type="radio"
                                                name="type"
                                                value="cash_in"
                                                checked={data.type === 'cash_in'}
                                                onChange={(e) => handleTypeChange(e.target.value)}
                                                className="text-green-600 focus:ring-green-500"
                                            />
                                            <span className="text-sm font-medium text-gray-900">Cash In</span>
                                        </label>
                                        <label className={`flex items-center gap-2 cursor-pointer rounded-lg border px-4 py-3 ${data.type === 'cash_out' ? 'border-red-500 bg-red-50' : 'border-gray-200'}`}>
                                            <input
                                                type="radio"
                                                name="type"
                                                value="cash_out"
                                                checked={data.type === 'cash_out'}
                                                onChange={(e) => handleTypeChange(e.target.value)}
                                                className="text-red-600 focus:ring-red-500"
                                            />
                                            <span className="text-sm font-medium text-gray-900">Cash Out</span>
                                        </label>
                                    </div>
                                    {errors.type && <p className="mt-1 text-sm text-red-600">{errors.type}</p>}
                                </div>

                                {/* Category */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Category <span className="text-red-500">*</span></label>
                                    <select
                                        value={data.category_id}
                                        onChange={(e) => setData('category_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 category...</option>
                                        {filteredCategories.map((cat) => (
                                            <option key={cat.id} value={cat.id}>{cat.name}</option>
                                        ))}
                                    </select>
                                    {errors.category_id && <p className="mt-1 text-sm text-red-600">{errors.category_id}</p>}
                                </div>

                                {/* Amount */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Amount (PKR) <span className="text-red-500">*</span></label>
                                    <input
                                        type="number"
                                        step="0.01"
                                        min="1"
                                        value={data.amount}
                                        onChange={(e) => setData('amount', 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.amount && <p className="mt-1 text-sm text-red-600">{errors.amount}</p>}
                                </div>

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

                                {/* Date */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Date <span className="text-red-500">*</span></label>
                                    <input
                                        type="date"
                                        value={data.date}
                                        onChange={(e) => setData('date', 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.date && <p className="mt-1 text-sm text-red-600">{errors.date}</p>}
                                </div>

                                {/* Reference No */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Reference No</label>
                                    <input
                                        type="text"
                                        value={data.reference_no}
                                        onChange={(e) => setData('reference_no', 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="Optional"
                                    />
                                    {errors.reference_no && <p className="mt-1 text-sm text-red-600">{errors.reference_no}</p>}
                                </div>

                                {/* Proof File */}
                                <div>
                                    <label className="block text-sm font-medium text-gray-700">Proof / Receipt</label>
                                    {expense.proof_file && (
                                        <p className="mb-1 text-xs text-gray-500">
                                            Current file: <a href={`/storage/${expense.proof_file}`} target="_blank" rel="noopener noreferrer" className="text-blue-600 hover:text-blue-900">View</a>
                                        </p>
                                    )}
                                    <input
                                        type="file"
                                        onChange={(e) => setData('proof_file', e.target.files[0])}
                                        className="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:rounded-md file:border-0 file:bg-blue-50 file:px-4 file:py-2 file:text-sm file:font-medium file:text-blue-700 hover:file:bg-blue-100"
                                    />
                                    {errors.proof_file && <p className="mt-1 text-sm text-red-600">{errors.proof_file}</p>}
                                </div>

                                {/* Submit */}
                                <div className="flex items-center justify-end gap-4">
                                    <Link href={route('expenses.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 ? 'Updating...' : 'Update Entry'}
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </AuthenticatedLayout>
    );
}
