import { Head, router, usePage } from '@inertiajs/react';
import { useMemo, useState } from 'react';
import { index as expenseReportsIndex } from '@/actions/App/Http/Controllers/ExpenseReportController';
import { ExpenseDayCategoryTable } from '@/components/expenses/expense-day-tables';
import { ExpenseStatusBadge } from '@/components/expenses/expense-status-badge';
import { expensePaymentLabel, expenseStatusLabel, expenseCategoryLabel } from '@/lib/expense-labels';
import { AppDateInput } from '@/components/ui/app-date-input';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useLanguage } from '@/contexts/language-context';
import { formatExpenseDateOrDash } from '@/lib/dates';
import AppLayout from '@/layouts/app-layout';
import { cn } from '@/lib/utils';
import { dashboard } from '@/routes';

function buildQuery(filters) {
    const params = new URLSearchParams();
    Object.entries(filters).forEach(([key, value]) => {
        if (value) params.set(key, String(value));
    });
    return params.toString();
}

export default function ExpenseReportsIndex() {
    const { t } = useLanguage();
    const p = t.expenseReportsPage;
    const { filters = {}, report = {}, categories = [], paymentMethods = [], statuses = [] } = usePage().props;
    const [localFilters, setLocalFilters] = useState(filters);
    const [activeTab, setActiveTab] = useState('category');

    const breadcrumbs = useMemo(
        () => [
            { title: t.dashboard.breadcrumb, href: dashboard() },
            { title: p.breadcrumb, href: expenseReportsIndex() },
        ],
        [t.dashboard.breadcrumb, p.breadcrumb],
    );

    function apply(extra = {}) {
        router.get(expenseReportsIndex.url({ query: { ...localFilters, ...extra } }), {}, { preserveScroll: true });
    }

    const query = buildQuery(localFilters);
    const byCategory = report.by_category ?? [];
    const byPayment = report.by_payment ?? [];
    const tabs = [
        { id: 'category', label: p.tabCategory },
        { id: 'payment', label: p.tabPayment },
        { id: 'period', label: p.tabPeriod },
        { id: 'details', label: p.tabDetails },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={p.headTitle} />
            <div className="flex flex-1 flex-col gap-6 p-4">
                <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <h1 className="text-2xl font-semibold tracking-tight">{p.headTitle}</h1>
                        <p className="text-muted-foreground text-sm">{formatExpenseDateOrDash(filters.date_from)} — {formatExpenseDateOrDash(filters.date_to)}</p>
                    </div>
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="outline">{p.exportLabel}</Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                            <DropdownMenuItem asChild>
                                <a href={`/expense-reports/pdf?${query}&print=1`} target="_blank" rel="noreferrer">{p.exportPrint}</a>
                            </DropdownMenuItem>
                            <DropdownMenuItem asChild>
                                <a href={`/expense-reports/pdf?${query}`} target="_blank" rel="noreferrer">{p.exportPdf}</a>
                            </DropdownMenuItem>
                            <DropdownMenuItem asChild>
                                <a href={`/expense-reports/excel?${query}`}>{p.exportExcel}</a>
                            </DropdownMenuItem>
                        </DropdownMenuContent>
                    </DropdownMenu>
                </div>

                <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-4">
                    {[
                        [p.totalAfn, report.summary?.total_afn],
                        [p.paidAfn, report.summary?.paid_afn],
                        [p.pendingAfn, report.summary?.pending_afn],
                        [p.records, report.summary?.records],
                    ].map(([label, value]) => (
                        <Card key={label}>
                            <CardHeader className="pb-2"><CardTitle className="text-sm text-muted-foreground">{label}</CardTitle></CardHeader>
                            <CardContent className="text-2xl font-semibold tabular-nums">{value} {label === p.records ? '' : t.expensesPage.currencyLabel}</CardContent>
                        </Card>
                    ))}
                </div>

                <Card>
                    <CardHeader>
                        <CardTitle>{p.filters}</CardTitle>
                        <CardDescription>{p.subtitle}</CardDescription>
                    </CardHeader>
                    <CardContent className="grid gap-4 md:grid-cols-2 xl:grid-cols-5">
                        <div className="space-y-2">
                            <Label>{t.expensesPage.dateFrom}</Label>
                            <AppDateInput value={localFilters.date_from ?? ''} onChange={(value) => setLocalFilters((c) => ({ ...c, date_from: value }))} />
                        </div>
                        <div className="space-y-2">
                            <Label>{t.expensesPage.dateTo}</Label>
                            <AppDateInput value={localFilters.date_to ?? ''} onChange={(value) => setLocalFilters((c) => ({ ...c, date_to: value }))} />
                        </div>
                        <div className="space-y-2">
                            <Label>{t.expensesPage.category}</Label>
                            <Select value={localFilters.expense_category_id ? String(localFilters.expense_category_id) : 'all'} onValueChange={(v) => setLocalFilters((c) => ({ ...c, expense_category_id: v === 'all' ? '' : v }))}>
                                <SelectTrigger><SelectValue placeholder={p.allCategories} /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">{p.allCategories}</SelectItem>
                                    {categories.map((c) => (
                                        <SelectItem key={c.id} value={String(c.id)}>
                                            {expenseCategoryLabel(c.slug, c.name, t.expensesPage)}
                                        </SelectItem>
                                    ))}
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label>{t.expensesPage.paymentMethod}</Label>
                            <Select value={localFilters.payment_method || 'all'} onValueChange={(v) => setLocalFilters((c) => ({ ...c, payment_method: v === 'all' ? '' : v }))}>
                                <SelectTrigger><SelectValue placeholder={p.allPaymentMethods} /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">{p.allPaymentMethods}</SelectItem>
                                    {paymentMethods.map((m) => <SelectItem key={m.value} value={m.value}>{expensePaymentLabel(m.value, t.expensesPage)}</SelectItem>)}
                                </SelectContent>
                            </Select>
                        </div>
                        <div className="space-y-2">
                            <Label>{t.expensesPage.status}</Label>
                            <Select value={localFilters.status || 'all'} onValueChange={(v) => setLocalFilters((c) => ({ ...c, status: v === 'all' ? '' : v }))}>
                                <SelectTrigger><SelectValue placeholder={p.allStatuses} /></SelectTrigger>
                                <SelectContent>
                                    <SelectItem value="all">{p.allStatuses}</SelectItem>
                                    {statuses.map((s) => <SelectItem key={s.value} value={s.value}>{expenseStatusLabel(s.value, t.expensesPage)}</SelectItem>)}
                                </SelectContent>
                            </Select>
                        </div>
                    </CardContent>
                    <CardContent className="flex flex-wrap gap-2 border-t pt-4">
                        {['today', 'this_week', 'this_month', 'this_year'].map((range) => (
                            <Button key={range} size="sm" variant="outline" onClick={() => apply({ quick_range: range })}>{t.expensesPage[`quick${range.split('_').map((x) => x[0].toUpperCase() + x.slice(1)).join('')}`]}</Button>
                        ))}
                        <Button onClick={() => apply()}>{t.expensesPage.applyFilters}</Button>
                    </CardContent>
                </Card>

                <div className="flex flex-wrap gap-2">
                    {tabs.map((tab) => (
                        <Button
                            key={tab.id}
                            type="button"
                            size="sm"
                            variant={activeTab === tab.id ? 'default' : 'outline'}
                            onClick={() => setActiveTab(tab.id)}
                        >
                            {tab.label}
                        </Button>
                    ))}
                </div>

                <Card>
                    <CardContent className="pt-6">
                        {activeTab === 'category' ? (
                            byCategory.length === 0 ? (
                                <p className="text-muted-foreground text-sm">{p.empty}</p>
                            ) : (
                                <ExpenseDayCategoryTable
                                    rows={byCategory}
                                    labels={t.expensesPage}
                                    dayTotal={report.period_total_afn}
                                />
                            )
                        ) : null}

                        {activeTab === 'payment' ? (
                            byPayment.length === 0 ? (
                                <p className="text-muted-foreground text-sm">{p.empty}</p>
                            ) : (
                                <div className="rounded-md border">
                                    <Table>
                                        <TableHeader>
                                            <TableRow>
                                                <TableHead>{t.expensesPage.colPayment}</TableHead>
                                                <TableHead>{p.colCount}</TableHead>
                                                <TableHead>{p.share}</TableHead>
                                                <TableHead className="text-end">{t.expensesPage.colAmount}</TableHead>
                                            </TableRow>
                                        </TableHeader>
                                        <TableBody>
                                            {byPayment.map((row) => (
                                                <TableRow key={row.payment_method || 'unknown'}>
                                                    <TableCell>{expensePaymentLabel(row.payment_method, t.expensesPage)}</TableCell>
                                                    <TableCell>{row.count}</TableCell>
                                                    <TableCell>{row.share_percent}%</TableCell>
                                                    <TableCell className="text-end tabular-nums">
                                                        {row.amount_afn} {t.expensesPage.currencyLabel}
                                                    </TableCell>
                                                </TableRow>
                                            ))}
                                            <TableRow>
                                                <TableCell colSpan={3} className="font-medium">{p.periodTotal}</TableCell>
                                                <TableCell className="text-end font-semibold tabular-nums">
                                                    {report.period_total_afn} {t.expensesPage.currencyLabel}
                                                </TableCell>
                                            </TableRow>
                                        </TableBody>
                                    </Table>
                                </div>
                            )
                        ) : null}

                        {activeTab === 'period' ? (
                            <div className="space-y-6">
                                {[
                                    [p.monthly, report.by_month ?? []],
                                    [p.yearly, report.by_year ?? []],
                                    [p.dailyTrend, report.by_day ?? []],
                                ].map(([title, rows]) => (
                                    <div key={title} className="space-y-3">
                                        <h3 className="font-medium">{title}</h3>
                                        {rows.length === 0 ? (
                                            <p className="text-muted-foreground text-sm">{p.empty}</p>
                                        ) : (
                                            <div className="rounded-md border">
                                                <Table>
                                                    <TableHeader>
                                                        <TableRow>
                                                            <TableHead>{title}</TableHead>
                                                            <TableHead>{p.colCount}</TableHead>
                                                            <TableHead className="text-end">{t.expensesPage.currencyLabel}</TableHead>
                                                        </TableRow>
                                                    </TableHeader>
                                                    <TableBody>
                                                        {rows.map((row) => (
                                                            <TableRow key={row.period}>
                                                                <TableCell>{row.period_label ?? formatExpenseDateOrDash(row.period)}</TableCell>
                                                                <TableCell>{row.count}</TableCell>
                                                                <TableCell className="text-end tabular-nums">{row.amount_afn}</TableCell>
                                                            </TableRow>
                                                        ))}
                                                    </TableBody>
                                                </Table>
                                            </div>
                                        )}
                                    </div>
                                ))}
                            </div>
                        ) : null}

                        {activeTab === 'details' ? (
                            (report.expenses ?? []).length === 0 ? (
                                <p className="text-muted-foreground text-sm">{p.empty}</p>
                            ) : (
                                <div className="space-y-4">
                                    <div className="overflow-x-auto rounded-md border">
                                        <Table>
                                            <TableHeader>
                                                <TableRow>
                                                    <TableHead>{t.expensesPage.colDate}</TableHead>
                                                    <TableHead>{t.expensesPage.colVoucher}</TableHead>
                                                    <TableHead>{t.expensesPage.colCategory}</TableHead>
                                                    <TableHead>{t.expensesPage.colVendor}</TableHead>
                                                    <TableHead>{t.expensesPage.colAmount}</TableHead>
                                                    <TableHead>{t.expensesPage.colStatus}</TableHead>
                                                </TableRow>
                                            </TableHeader>
                                            <TableBody>
                                                {report.expenses.map((row) => (
                                                    <TableRow key={row.id} className={cn(row.is_cancelled && 'opacity-60')}>
                                                        <TableCell>{formatExpenseDateOrDash(row.expense_date_display ?? row.expense_date)}</TableCell>
                                                        <TableCell>{row.voucher_number}</TableCell>
                                                        <TableCell>{expenseCategoryLabel(row.category_slug, row.category_name, t.expensesPage)}</TableCell>
                                                        <TableCell>{row.vendor_paid_to || '—'}</TableCell>
                                                        <TableCell className="tabular-nums">{row.amount_afn} {t.expensesPage.currencyLabel}</TableCell>
                                                        <TableCell><ExpenseStatusBadge status={row.status} label={row.status_label} /></TableCell>
                                                    </TableRow>
                                                ))}
                                            </TableBody>
                                        </Table>
                                    </div>
                                    <p className="font-semibold">
                                        {p.periodTotal}: {report.period_total_afn} {t.expensesPage.currencyLabel}
                                    </p>
                                </div>
                            )
                        ) : null}
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
