import { Head, router, useForm } from '@inertiajs/react';
import { CalendarPlus, Download, HeartHandshake, Plus, RotateCcw, Wallet } from 'lucide-react';
import ChandaController from '@/actions/App/Http/Controllers/ChandaController';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useI18n } from '@/hooks/use-i18n';

type DonorRow = {
    id: number;
    donor_code: string;
    name_bn: string;
    name_en: string | null;
    phone: string | null;
    member_type: string;
};

type FundRow = {
    id: number;
    name_bn: string;
    name_en: string | null;
    code: string;
    current_balance: number;
};

type ChargeRow = {
    id: number;
    period_start: string;
    amount: string | number;
    due_amount: string | number;
    membership?: { donor?: { name_bn: string; name_en: string | null } | null } | null;
};

type ContributionRow = {
    id: number;
    receipt_number: string;
    contribution_type: string;
    payment_date: string;
    total_amount: string | number;
    status: string;
    donor?: { name_bn: string; name_en: string | null } | null;
    payment_method?: { name_bn: string; name_en: string | null } | null;
};

type PaymentMethodItem = { id: number; name_bn: string; name_en: string | null };

export default function ChandaIndex({
    donors,
    funds,
    charges,
    contributions,
    paymentMethods,
}: {
    donors: DonorRow[];
    funds: FundRow[];
    charges: ChargeRow[];
    contributions: ContributionRow[];
    paymentMethods: PaymentMethodItem[];
}) {
    const { locale, t, localized } = useI18n();
    const now = new Date();

    const donorForm = useForm({
        name_bn: '',
        name_en: '',
        phone: '',
        member_type: 'chanda_member',
        chanda_amount: '500',
        chanda_frequency: 'monthly',
    });

    const fundForm = useForm({
        name_bn: '',
        name_en: '',
        code: '',
        opening_balance: '0',
    });

    const contribForm = useForm({
        donor_id: donors[0]?.id ? String(donors[0].id) : '',
        contribution_type: 'membership_chanda',
        payment_date: now.toISOString().slice(0, 10),
        total_amount: '',
        payment_method_id: paymentMethods[0]?.id ? String(paymentMethods[0].id) : '',
        donation_fund_id: '',
        transaction_reference: '',
        send_whatsapp: true,
    });

    const genForm = useForm({
        year: now.getFullYear(),
        month: now.getMonth() + 1,
    });

    return (
        <>
            <Head title={t('nav.chanda_donations', 'Chanda & Donations')} />

            <div className="flex flex-col gap-6 p-4 md:p-6">
                <div className="flex flex-wrap items-center justify-between gap-4">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight">
                            {t('nav.chanda_donations', 'Chanda & Donations')}
                        </h1>
                        <p className="text-sm text-muted-foreground">
                            {locale === 'bn'
                                ? 'মাসিক/বাৎসরিক নির্ধারিত চাঁদা এবং সাধারণ বা ফান্ডভিত্তিক দান পরিচালনা করুন।'
                                : 'Manage expected membership chanda and manual general or fund donations.'}
                        </p>
                    </div>

                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            genForm.submit(ChandaController.generateCharges());
                        }}
                        className="flex items-center gap-2"
                    >
                        <Input
                            type="number"
                            value={genForm.data.month}
                            onChange={(e) => genForm.setData('month', Number(e.target.value))}
                            className="w-20"
                            min={1}
                            max={12}
                        />
                        <Input
                            type="number"
                            value={genForm.data.year}
                            onChange={(e) => genForm.setData('year', Number(e.target.value))}
                            className="w-24"
                        />
                        <Button type="submit" disabled={genForm.processing}>
                            <CalendarPlus className="mr-1.5 h-4 w-4" />
                            {locale === 'bn' ? 'মাসিক চাঁদা চার্জ তৈরি' : 'Generate Chanda'}
                        </Button>
                    </form>
                </div>

                {/* Fund Balances */}
                <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
                    {funds.map((fund) => (
                        <div key={fund.id} className="minimal-card p-5">
                            <p className="text-xs font-medium uppercase text-muted-foreground">{fund.code}</p>
                            <p className="mt-1 font-semibold">{localized(fund, 'name')}</p>
                            <p className="mt-2 text-2xl font-bold text-primary">৳{fund.current_balance.toLocaleString()}</p>
                        </div>
                    ))}
                </div>

                <div className="grid gap-6 lg:grid-cols-3">
                    {/* Record Contribution */}
                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <Wallet className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">
                                {locale === 'bn' ? 'চাঁদা / দান সংগ্রহ' : 'Collect Chanda / Donation'}
                            </h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                contribForm.submit(ChandaController.storeContribution(), {
                                    onSuccess: () => contribForm.reset('total_amount', 'transaction_reference'),
                                });
                            }}
                            className="space-y-3"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'দাতা / সদস্য' : 'Donor / Member'}</Label>
                                <select
                                    value={contribForm.data.donor_id}
                                    onChange={(e) => contribForm.setData('donor_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    required
                                >
                                    <option value="">{locale === 'bn' ? 'নির্বাচন করুন' : 'Select donor'}</option>
                                    {donors.map((d) => (
                                        <option key={d.id} value={d.id}>
                                            {localized(d, 'name')} ({d.donor_code})
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ধরন' : 'Type'}</Label>
                                <select
                                    value={contribForm.data.contribution_type}
                                    onChange={(e) => contribForm.setData('contribution_type', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                >
                                    <option value="membership_chanda">
                                        {locale === 'bn' ? 'সদস্য চাঁদা (Expected)' : 'Membership Chanda'}
                                    </option>
                                    <option value="manual_donation">
                                        {locale === 'bn' ? 'সাধারণ / ফান্ড দান' : 'Manual Donation'}
                                    </option>
                                </select>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'পরিমাণ (৳)' : 'Amount'}</Label>
                                    <Input
                                        type="number"
                                        step="0.01"
                                        min="0.01"
                                        value={contribForm.data.total_amount}
                                        onChange={(e) => contribForm.setData('total_amount', e.target.value)}
                                        required
                                    />
                                </div>
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'মাধ্যম' : 'Method'}</Label>
                                    <select
                                        value={contribForm.data.payment_method_id}
                                        onChange={(e) => contribForm.setData('payment_method_id', e.target.value)}
                                        className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    >
                                        {paymentMethods.map((pm) => (
                                            <option key={pm.id} value={pm.id}>
                                                {localized(pm, 'name')}
                                            </option>
                                        ))}
                                    </select>
                                </div>
                            </div>
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ফান্ড (ঐচ্ছিক)' : 'Donation Fund (Optional)'}</Label>
                                <select
                                    value={contribForm.data.donation_fund_id}
                                    onChange={(e) => contribForm.setData('donation_fund_id', e.target.value)}
                                    className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                >
                                    <option value="">{locale === 'bn' ? 'সাধারণ তহবিল' : 'General Pool'}</option>
                                    {funds.map((f) => (
                                        <option key={f.id} value={f.id}>
                                            {localized(f, 'name')}
                                        </option>
                                    ))}
                                </select>
                            </div>
                            <label className="flex items-center gap-2 text-sm">
                                <input
                                    type="checkbox"
                                    checked={contribForm.data.send_whatsapp}
                                    onChange={(e) => contribForm.setData('send_whatsapp', e.target.checked)}
                                    className="h-4 w-4 accent-primary"
                                />
                                <span>{locale === 'bn' ? 'হোয়াটসঅ্যাপ রসিদ পাঠান' : 'Send WhatsApp confirmation'}</span>
                            </label>
                            <Button type="submit" disabled={contribForm.processing} className="w-full">
                                <Plus className="mr-1.5 h-4 w-4" />
                                {locale === 'bn' ? 'জমা নিন' : 'Record Contribution'}
                            </Button>
                        </form>
                    </div>

                    {/* Add Donor / Member */}
                    <div className="minimal-card p-6">
                        <div className="mb-4 flex items-center gap-2">
                            <HeartHandshake className="h-5 w-5 text-primary" />
                            <h2 className="font-semibold">{locale === 'bn' ? 'নতুন দাতা / সদস্য' : 'Add Donor / Member'}</h2>
                        </div>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                donorForm.submit(ChandaController.storeDonor(), {
                                    onSuccess: () => donorForm.reset('name_bn', 'name_en', 'phone'),
                                });
                            }}
                            className="space-y-3"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'নাম (বাংলা)' : 'Name (Bangla)'}</Label>
                                <Input
                                    value={donorForm.data.name_bn}
                                    onChange={(e) => donorForm.setData('name_bn', e.target.value)}
                                    required
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'ফোন' : 'Phone'}</Label>
                                    <Input
                                        value={donorForm.data.phone}
                                        onChange={(e) => donorForm.setData('phone', e.target.value)}
                                    />
                                </div>
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'ধরন' : 'Member Type'}</Label>
                                    <select
                                        value={donorForm.data.member_type}
                                        onChange={(e) => donorForm.setData('member_type', e.target.value)}
                                        className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    >
                                        <option value="chanda_member">Chanda Member</option>
                                        <option value="general_donor">General Donor</option>
                                        <option value="both">Both</option>
                                    </select>
                                </div>
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'নির্ধারিত চাঁদা (৳)' : 'Expected Chanda'}</Label>
                                    <Input
                                        type="number"
                                        value={donorForm.data.chanda_amount}
                                        onChange={(e) => donorForm.setData('chanda_amount', e.target.value)}
                                    />
                                </div>
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'সময়কাল' : 'Frequency'}</Label>
                                    <select
                                        value={donorForm.data.chanda_frequency}
                                        onChange={(e) => donorForm.setData('chanda_frequency', e.target.value)}
                                        className="h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm"
                                    >
                                        <option value="monthly">Monthly</option>
                                        <option value="annual">Annual</option>
                                    </select>
                                </div>
                            </div>
                            <Button type="submit" disabled={donorForm.processing} className="w-full">
                                {locale === 'bn' ? 'দাতা যোগ করুন' : 'Save Donor'}
                            </Button>
                        </form>
                    </div>

                    {/* Add Fund */}
                    <div className="minimal-card p-6">
                        <h2 className="mb-4 font-semibold">{locale === 'bn' ? 'নতুন ফান্ড তৈরি' : 'Create Donation Fund'}</h2>
                        <form
                            onSubmit={(e) => {
                                e.preventDefault();
                                fundForm.submit(ChandaController.storeFund(), {
                                    onSuccess: () => fundForm.reset('name_bn', 'name_en', 'code'),
                                });
                            }}
                            className="space-y-3"
                        >
                            <div className="space-y-1">
                                <Label>{locale === 'bn' ? 'ফান্ডের নাম (বাংলা)' : 'Fund Name (Bangla)'}</Label>
                                <Input
                                    value={fundForm.data.name_bn}
                                    onChange={(e) => fundForm.setData('name_bn', e.target.value)}
                                    placeholder="এতিমখানা ফান্ড"
                                    required
                                />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'কোড' : 'Code'}</Label>
                                    <Input
                                        value={fundForm.data.code}
                                        onChange={(e) => fundForm.setData('code', e.target.value)}
                                        placeholder="ORPHAN"
                                        required
                                    />
                                </div>
                                <div className="space-y-1">
                                    <Label>{locale === 'bn' ? 'প্রারম্ভিক ব্যালেন্স' : 'Opening'}</Label>
                                    <Input
                                        type="number"
                                        value={fundForm.data.opening_balance}
                                        onChange={(e) => fundForm.setData('opening_balance', e.target.value)}
                                    />
                                </div>
                            </div>
                            <Button type="submit" disabled={fundForm.processing} className="w-full">
                                {locale === 'bn' ? 'ফান্ড যোগ করুন' : 'Add Fund'}
                            </Button>
                        </form>
                    </div>
                </div>

                {/* Recent Contributions & Unpaid Chanda */}
                <div className="grid gap-6 lg:grid-cols-2">
                    <div className="minimal-card p-6">
                        <h3 className="mb-3 font-semibold">{locale === 'bn' ? 'বকেয়া সদস্য চাঁদা' : 'Unpaid Chanda Charges'}</h3>
                        <div className="space-y-2">
                            {charges.length === 0 ? (
                                <p className="text-sm text-muted-foreground">{locale === 'bn' ? 'কোনো বকেয়া চাঁদা নেই।' : 'No unpaid chanda.'}</p>
                            ) : (
                                charges.map((ch) => (
                                    <div key={ch.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                                        <div>
                                            <p className="font-medium">{localized(ch.membership?.donor, 'name')}</p>
                                            <p className="text-xs text-muted-foreground">{ch.period_start}</p>
                                        </div>
                                        <span className="font-semibold text-rose-600">৳{Number(ch.due_amount).toLocaleString()}</span>
                                    </div>
                                ))
                            )}
                        </div>
                    </div>

                    <div className="minimal-card p-6">
                        <h3 className="mb-3 font-semibold">{locale === 'bn' ? 'সাম্প্রতিক রসিদ' : 'Recent Contributions'}</h3>
                        <div className="space-y-2">
                            {contributions.map((c) => (
                                <div key={c.id} className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm">
                                    <div>
                                        <p className="font-medium">
                                            {c.receipt_number} · {localized(c.donor, 'name')}
                                        </p>
                                        <p className="text-xs text-muted-foreground">
                                            {c.payment_date} · {c.contribution_type}
                                        </p>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className="font-semibold text-emerald-600">
                                            ৳{Number(c.total_amount).toLocaleString()}
                                        </span>
                                        <Button size="sm" variant="ghost" asChild title="Download Receipt PDF">
                                            <a href={ChandaController.downloadReceipt(c.id).url} target="_blank" rel="noreferrer">
                                                <Download className="h-3.5 w-3.5" />
                                            </a>
                                        </Button>
                                        {c.status !== 'reversed' && (
                                            <Button
                                                size="sm"
                                                variant="ghost"
                                                onClick={() => router.post(ChandaController.reverseContribution(c.id).url)}
                                            >
                                                <RotateCcw className="h-3.5 w-3.5 text-rose-500" />
                                            </Button>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
}
