import { useForm, router } from '@inertiajs/react';
import AppLayout from '@/layouts/AppLayout';
import { useState } from 'react';
import { makeCurrencyFormatter } from '@/lib/currency';
import { useTranslator } from '@/lib/i18n';
import { ExportMenu } from '@/components/export-menu';

interface Category {
    id: string;
    name: string;
    icon?: string;
    allocated_amount: number;
    spent_amount: number;
    notes?: string;
}

interface Props {
    wedding: any;
    vision?: { total_budget: number; notes?: string };
    categories: Category[];
    summary: {
        totalBudget: number;
        totalAllocated: number;
        totalSpent: number;
        budgetRemaining: number;
    };
}

export default function Budget({ wedding, vision, categories, summary }: Props) {
    const t = useTranslator();
    const [tab, setTab] = useState<'overview' | 'categories'>('overview');
    const fmt = makeCurrencyFormatter(wedding?.currency || 'USD');
    const tabLabels: Record<'overview' | 'categories', string> = {
        overview: t('budget.overview'),
        categories: t('budget.categories'),
    };

    // Vision uses a string-backed input so users can fully clear the field —
    // type="number" with a 0 default blocks backspacing past the leading zero.
    const visionForm = useForm({
        total_budget: vision?.total_budget != null ? String(vision.total_budget) : '',
        notes: vision?.notes ?? '',
    });

    function saveVision(e: React.FormEvent) {
        e.preventDefault();
        visionForm.put(`/weddings/${wedding.id}/budget/vision`, { preserveScroll: true });
    }

    return (
        <AppLayout wedding={wedding}>
            <div className="max-w-5xl mx-auto px-6 py-8">
                <div className="flex items-center justify-between mb-6">
                    <h1 className="font-serif text-3xl">{t('budget.title')}</h1>
                    <ExportMenu
                        filename="budget"
                        title={t('budget.title')}
                        rows={categories}
                        columns={[
                            { header: t('budget.category_name'), value: (c: Category) => c.name },
                            { header: t('budget.allocated'), value: (c: Category) => Number(c.allocated_amount ?? 0) },
                            { header: t('budget.spent'), value: (c: Category) => Number(c.spent_amount ?? 0) },
                            { header: t('budget.remaining'), value: (c: Category) => Number(c.allocated_amount ?? 0) - Number(c.spent_amount ?? 0) },
                            { header: t('common.notes'), value: (c: Category) => c.notes },
                        ]}
                    />
                </div>

                {/* Summary Cards — simplified per reviewer feedback */}
                <div className="grid grid-cols-2 gap-4 mb-8">
                    <SCard label={t('budget.total_budget')} value={fmt(summary.totalBudget)} />
                    <SCard label={t('budget.spent')} value={fmt(summary.totalSpent)} color={summary.totalSpent <= summary.totalBudget ? 'text-foreground' : 'text-red-600'} />
                </div>

                {/* Budget Vision */}
                <div className="bg-card border border-border rounded-xl p-6 mb-6">
                    <h2 className="font-semibold mb-4">{t('budget.budget_vision')}</h2>
                    <form onSubmit={saveVision} className="flex gap-4 items-end">
                        <div className="flex-1">
                            <label className="block text-sm font-medium mb-1">{t('budget.total_budget')}</label>
                            <input
                                type="text"
                                inputMode="decimal"
                                pattern="[0-9]*\.?[0-9]*"
                                placeholder="0"
                                value={visionForm.data.total_budget}
                                onChange={e => visionForm.setData('total_budget', e.target.value.replace(/[^0-9.]/g, ''))}
                                className="w-full border border-border rounded-lg px-3 py-2 text-sm"
                            />
                        </div>
                        <button type="submit" disabled={visionForm.processing} className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm">
                            {t('common.save')}
                        </button>
                    </form>
                </div>

                {/* Tabs */}
                <div className="flex gap-1 mb-6 border-b border-border">
                    {(['overview', 'categories'] as const).map(t => (
                        <button
                            key={t}
                            onClick={() => setTab(t)}
                            className={`px-4 py-2 text-sm capitalize font-medium border-b-2 transition-colors ${tab === t ? 'border-primary text-primary' : 'border-transparent text-muted-foreground hover:text-foreground'}`}
                        >
                            {tabLabels[t]}
                        </button>
                    ))}
                </div>

                {tab === 'overview' && (
                    <div className="space-y-2">
                        {categories.length === 0 && (
                            <p className="text-center text-muted-foreground py-10 text-sm">
                                No categories yet. Add them in the Categories tab.
                            </p>
                        )}
                        {categories.map(cat => {
                            const allocated = Number(cat.allocated_amount);
                            const spent = Number(cat.spent_amount);
                            // Progress against this category's own allocation; falls back to
                            // spend-vs-total-budget when nothing is allocated yet.
                            const denom = allocated > 0 ? allocated : summary.totalBudget;
                            const pct = denom > 0 ? (spent / denom) * 100 : 0;
                            const over = allocated > 0 && spent > allocated;
                            return (
                                <div key={cat.id} className="bg-card border border-border rounded-lg p-4">
                                    <div className="flex items-center justify-between mb-2">
                                        <span className="font-medium text-sm">{cat.icon} {cat.name}</span>
                                        <div className="flex gap-4 text-sm">
                                            <span className="text-muted-foreground" title={t('budget.budgeted_help')}>{t('budget.budgeted')}: {fmt(allocated)}</span>
                                            <span className={over ? 'text-red-600' : ''} title={t('budget.spent_help')}>{t('budget.spent')}: {fmt(spent)}</span>
                                        </div>
                                    </div>
                                    <div className="bg-muted rounded-full h-1.5">
                                        <div className={`h-1.5 rounded-full ${over ? 'bg-red-500' : 'bg-primary'}`} style={{ width: `${Math.min(pct, 100)}%` }} />
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                )}

                {tab === 'categories' && <CategoriesTab wedding={wedding} categories={categories} totalBudget={summary.totalBudget} />}
            </div>
        </AppLayout>
    );
}

function CategoriesTab({ wedding, categories, totalBudget }: { wedding: any; categories: Category[]; totalBudget: number }) {
    const t = useTranslator();
    const fmt = makeCurrencyFormatter(wedding?.currency || 'USD');
    const [editId, setEditId] = useState<string | null>(null);
    const [showAdd, setShowAdd] = useState(false);
    const form = useForm<any>({ name: '', icon: '', allocated_amount: '', spent_amount: '', notes: '' });
    const addForm = useForm({ name: '', icon: '', allocated_amount: '' as string, spent_amount: '' as string });

    function handleAdd(e: React.FormEvent) {
        e.preventDefault();
        addForm.post(`/weddings/${wedding.id}/budget/categories`, {
            onSuccess: () => { addForm.reset(); setShowAdd(false); },
            preserveScroll: true,
        });
    }

    function handleDelete(cat: Category) {
        if (!confirm(`Delete the "${cat.name}" category? This can't be undone.`)) return;
        router.delete(`/weddings/${wedding.id}/budget/categories/${cat.id}`, { preserveScroll: true });
    }

    function startEdit(cat: Category) {
        form.setData({
            name: cat.name ?? '',
            icon: cat.icon ?? '',
            allocated_amount: cat.allocated_amount ?? '',
            spent_amount: cat.spent_amount ?? '',
            notes: cat.notes ?? '',
        } as any);
        setEditId(cat.id);
    }

    function saveEdit(e: React.FormEvent, catId: string) {
        e.preventDefault();
        form.put(`/weddings/${wedding.id}/budget/categories/${catId}`, {
            onSuccess: () => setEditId(null),
            preserveScroll: true,
        });
    }

    const num = (v: string) => v.replace(/[^0-9.]/g, '');

    return (
        <div className="space-y-2">
            <div className="flex items-center justify-between">
                <p className="text-[12.5px] text-muted-foreground">
                    {t('budget.line_item_help')}
                </p>
                <button onClick={() => setShowAdd(!showAdd)} className="bg-primary text-primary-foreground px-4 py-2 rounded-lg text-sm shrink-0">
                    + {t('budget.add_category')}
                </button>
            </div>
            {showAdd && (
                <form onSubmit={handleAdd} className="bg-card border border-border rounded-lg p-4 grid grid-cols-12 gap-3">
                    <input
                        type="text" placeholder={t('budget.icon')} maxLength={2}
                        value={addForm.data.icon}
                        onChange={e => addForm.setData('icon', e.target.value)}
                        className="col-span-2 border border-border rounded-lg px-3 py-2 text-sm"
                    />
                    <input
                        type="text" placeholder={t('budget.category_name') + ' *'} required
                        value={addForm.data.name}
                        onChange={e => addForm.setData('name', e.target.value)}
                        className="col-span-4 border border-border rounded-lg px-3 py-2 text-sm"
                    />
                    <input
                        type="text" inputMode="decimal" placeholder={t('budget.budgeted')}
                        value={addForm.data.allocated_amount}
                        onChange={e => addForm.setData('allocated_amount', num(e.target.value))}
                        className="col-span-2 border border-border rounded-lg px-3 py-2 text-sm"
                    />
                    <input
                        type="text" inputMode="decimal" placeholder={t('budget.spent')}
                        value={addForm.data.spent_amount}
                        onChange={e => addForm.setData('spent_amount', num(e.target.value))}
                        className="col-span-2 border border-border rounded-lg px-3 py-2 text-sm"
                    />
                    <button type="submit" disabled={addForm.processing} className="col-span-2 bg-primary text-primary-foreground rounded-lg py-2 text-sm disabled:opacity-50">{t('common.add')}</button>
                </form>
            )}
            {categories.map(cat => (
                <div key={cat.id} className="bg-card border border-border rounded-lg p-4">
                    {editId === cat.id ? (
                        <form onSubmit={(e) => saveEdit(e, cat.id)} className="space-y-3">
                            <div className="flex gap-3 items-center flex-wrap">
                                <input
                                    type="text" maxLength={2} placeholder={t('budget.icon')}
                                    value={form.data.icon}
                                    onChange={e => form.setData('icon', e.target.value)}
                                    className="w-14 border border-border rounded px-2 py-1 text-sm"
                                />
                                <input
                                    type="text" placeholder="Name" required
                                    value={form.data.name}
                                    onChange={e => form.setData('name', e.target.value)}
                                    className="flex-1 min-w-[8rem] border border-border rounded px-2 py-1 text-sm"
                                />
                                <label className="text-xs text-muted-foreground">{t('budget.budgeted')}
                                    <input
                                        type="text" inputMode="decimal"
                                        value={form.data.allocated_amount}
                                        onChange={e => form.setData('allocated_amount', num(e.target.value))}
                                        className="ml-1 w-24 border border-border rounded px-2 py-1 text-sm"
                                    />
                                </label>
                                <label className="text-xs text-muted-foreground">{t('budget.spent')}
                                    <input
                                        type="text" inputMode="decimal"
                                        value={form.data.spent_amount}
                                        onChange={e => form.setData('spent_amount', num(e.target.value))}
                                        className="ml-1 w-24 border border-border rounded px-2 py-1 text-sm"
                                    />
                                </label>
                            </div>
                            <input
                                type="text" placeholder={t('budget.notes_optional')}
                                value={form.data.notes}
                                onChange={e => form.setData('notes', e.target.value)}
                                className="w-full border border-border rounded px-2 py-1 text-sm"
                            />
                            <div className="flex gap-3">
                                <button type="submit" className="text-primary text-sm">{t('common.save')}</button>
                                <button type="button" onClick={() => setEditId(null)} className="text-muted-foreground text-sm">{t('common.cancel')}</button>
                            </div>
                        </form>
                    ) : (
                        <div className="flex items-center justify-between gap-4">
                            <div className="min-w-0">
                                <span className="font-medium">{cat.icon} {cat.name}</span>
                                {cat.notes && <p className="text-[12px] text-muted-foreground mt-0.5 truncate">{cat.notes}</p>}
                            </div>
                            <div className="flex gap-4 items-center shrink-0">
                                <span className="text-sm">
                                    <span className="text-muted-foreground">{t('budget.budgeted')}</span> {fmt(Number(cat.allocated_amount))}
                                    <span className="text-muted-foreground ml-3">{t('budget.spent')}</span>{' '}
                                    <span className={Number(cat.spent_amount) > Number(cat.allocated_amount) && Number(cat.allocated_amount) > 0 ? 'text-red-600 font-medium' : 'font-medium'}>
                                        {fmt(Number(cat.spent_amount))}
                                    </span>
                                </span>
                                <button onClick={() => startEdit(cat)} className="text-xs text-primary">{t('common.edit')}</button>
                                <button onClick={() => handleDelete(cat)} className="text-xs text-destructive" title="Delete this category">{t('common.delete')}</button>
                            </div>
                        </div>
                    )}
                </div>
            ))}
            {categories.length === 0 && (
                <p className="text-center text-muted-foreground py-8 text-sm">{t('budget.no_categories')}</p>
            )}
        </div>
    );
}

function SCard({ label, value, color }: { label: string; value: string; color?: string }) {
    return (
        <div className="bg-card border border-border rounded-xl p-4">
            <p className="text-xs text-muted-foreground uppercase tracking-wide mb-1">{label}</p>
            <p className={`text-xl font-semibold ${color ?? 'text-foreground'}`}>{value}</p>
        </div>
    );
}
