import { Head, Link, usePage } from '@inertiajs/react';
import { Plus } from 'lucide-react';
import { useMemo, useState } from 'react';
import { show as customerAccount } from '@/actions/App/Http/Controllers/CustomerAccountController';
import { index as customersIndex } from '@/actions/App/Http/Controllers/CustomerController';
import { index as oldDebtsIndex } from '@/actions/App/Http/Controllers/CustomerOldDebtController';
import { CustomerOldDebtDialog } from '@/components/customers/customer-old-debt-dialog';
import { CustomerOldDebtsDataTable } from '@/components/customers/customer-old-debts-data-table';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import { useLanguage } from '@/contexts/language-context';
import AppLayout from '@/layouts/app-layout';
import {
    formatMoneyAmountOrDash,
    formatPurchaseCurrencyLabel,
} from '@/lib/dates';
import { dashboard } from '@/routes';

export default function CustomerOldDebtsIndex() {
    const { t, locale } = useLanguage();
    const p = t.customersOldDebtsPage;
    const salesLabels = t.salesPage;
    const auth = usePage().props.auth ?? {};
    const canCreate = auth.canCreateCustomerPayments === true;
    const {
        customer,
        debts = [],
        summary,
        currencies = ['afn', 'usd'],
    } = usePage().props;
    const [dialogOpen, setDialogOpen] = useState(false);

    const breadcrumbs = useMemo(
        () => [
            { title: t.dashboard.breadcrumb, href: dashboard() },
            { title: t.customersPage.breadcrumb, href: customersIndex() },
            {
                title: customer?.full_name ?? '',
                href: customerAccount.url(customer?.id),
            },
            {
                title: p.breadcrumb,
                href: oldDebtsIndex.url(customer?.id),
            },
        ],
        [
            t.dashboard.breadcrumb,
            t.customersPage.breadcrumb,
            customer?.id,
            customer?.full_name,
            p.breadcrumb,
        ],
    );

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={p.headTitle} />
            <div className="flex h-full flex-1 flex-col gap-6 overflow-x-auto p-4">
                <Button variant="outline" size="sm" asChild className="w-fit">
                    <Link href={customerAccount.url(customer.id)} prefetch>
                        {p.backToAccount}
                    </Link>
                </Button>

                {canCreate ? (
                    <CustomerOldDebtDialog
                        customer={customer}
                        open={dialogOpen}
                        onOpenChange={setDialogOpen}
                        labels={p}
                        validation={t.validation}
                        appActions={t.appActions}
                        locale={locale}
                        currencies={currencies}
                    />
                ) : null}

                <Card>
                    <CardHeader className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                        <div className="space-y-2">
                            <CardTitle>{p.listTitle}</CardTitle>
                            <CardDescription>
                                {p.listSubtitle.replace('{customer}', customer?.full_name ?? '')}
                            </CardDescription>
                        </div>
                        {canCreate ? (
                            <Button type="button" onClick={() => setDialogOpen(true)}>
                                <Plus className="size-4" />
                                {p.addOldDebt}
                            </Button>
                        ) : null}
                    </CardHeader>
                    <CardContent className="space-y-4">
                        {summary ? (
                            <div className="grid gap-3 sm:grid-cols-3">
                                <div className="rounded-lg border px-3 py-2">
                                    <p className="text-muted-foreground text-xs">
                                        {p.totalBilledLabel}
                                    </p>
                                    <p className="mt-1 font-semibold tabular-nums">
                                        {formatMoneyAmountOrDash(summary.total_billed, locale)}{' '}
                                        {formatPurchaseCurrencyLabel(summary.currency, locale)}
                                    </p>
                                </div>
                                <div className="rounded-lg border px-3 py-2">
                                    <p className="text-muted-foreground text-xs">
                                        {p.purchaseOutstandingLabel}
                                    </p>
                                    <p className="mt-1 font-semibold tabular-nums">
                                        {formatMoneyAmountOrDash(
                                            summary.purchase_outstanding,
                                            locale,
                                        )}{' '}
                                        {formatPurchaseCurrencyLabel(summary.currency, locale)}
                                    </p>
                                </div>
                                <div className="rounded-lg border px-3 py-2">
                                    <p className="text-muted-foreground text-xs">
                                        {p.totalOutstandingLabel}
                                    </p>
                                    <p className="mt-1 font-semibold tabular-nums">
                                        {formatMoneyAmountOrDash(summary.outstanding, locale)}{' '}
                                        {formatPurchaseCurrencyLabel(summary.currency, locale)}
                                    </p>
                                </div>
                            </div>
                        ) : null}

                        <CustomerOldDebtsDataTable
                            debts={debts}
                            labels={p}
                            statusLabels={salesLabels}
                            locale={locale}
                        />
                    </CardContent>
                </Card>
            </div>
        </AppLayout>
    );
}
