import { Head, Link, router, usePage } from '@inertiajs/react';
import { ArrowLeft, MoreHorizontal, Pencil, UserCheck, UserX } from 'lucide-react';
import { useMemo, useState } from 'react';
import {
    edit as advanceEdit,
    index as advancesIndex,
    staff as advancesStaff,
    updateStatus as advanceUpdateStatus,
} from '@/actions/App/Http/Controllers/PermanentEmployeeAdvanceController';
import { ConfirmActionDialog } from '@/components/confirm-action-dialog';
import {
    PermanentEmployeeAdvanceDetailDialog,
    SettlementBadge,
} from '@/components/employees/permanent-employee-advance-detail-dialog';
import { Button } from '@/components/ui/button';
import {
    Card,
    CardContent,
    CardDescription,
    CardHeader,
    CardTitle,
} from '@/components/ui/card';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuSeparator,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { useLanguage } from '@/contexts/language-context';
import {
    formatEmployeeJoiningDateNumericOrDash,
    formatMoneyAmountOrDash,
} from '@/lib/dates';
import AppLayout from '@/layouts/app-layout';
import { dashboard } from '@/routes';

export default function PermanentEmployeeAdvancesStaff({ employee, summary, advances }) {
    const { t, locale } = useLanguage();
    const p = t.permanentEmployeeAdvancesPage;
    const page = usePage();
    const auth = page.props.auth ?? {};
    const canUpdate = auth.canUpdatePermanentAdvances === true;

    const [viewRecord, setViewRecord] = useState(null);
    const [toToggle, setToToggle] = useState(null);
    const [toggling, setToggling] = useState(false);

    const breadcrumbs = useMemo(
        () => [
            { title: t.dashboard.breadcrumb, href: dashboard() },
            { title: t.nav.employeeManagement, href: '#' },
            { title: p.breadcrumb, href: advancesIndex.url() },
            {
                title: employee.full_name,
                href: advancesStaff.url(employee.id),
            },
        ],
        [t.dashboard.breadcrumb, t.nav.employeeManagement, p.breadcrumb, employee],
    );

    const labels = useMemo(
        () => ({
            ...p,
            cancel: t.appActions.cancel,
            close: t.appActions.dismiss,
        }),
        [p, t.appActions.cancel, t.appActions.dismiss],
    );

    function formatType(type) {
        return type === 'product' ? p.typeProduct : p.typeCash;
    }

    function confirmToggle() {
        if (!toToggle) {
            return;
        }

        setToggling(true);
        router.patch(
            advanceUpdateStatus.url(toToggle.id),
            { is_active: !toToggle.is_active },
            {
                preserveScroll: true,
                onFinish: () => {
                    setToggling(false);
                    setToToggle(null);
                },
            },
        );
    }

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`${p.staffDetailsHeadTitle} — ${employee.full_name}`} />
            <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={advancesIndex.url()} prefetch>
                        <ArrowLeft className="size-4" />
                        {p.backToAdvances}
                    </Link>
                </Button>

                <Card>
                    <CardHeader className="bg-muted/45 dark:bg-muted/20 rounded-t-xl border-b border-border px-6 py-5">
                        <CardTitle className="text-xl font-semibold tracking-tight">
                            {employee.full_name}
                        </CardTitle>
                        <CardDescription>
                            {employee.designation_name
                                ? `${p.staffDetailsSubtitle} · ${employee.designation_name}`
                                : p.staffDetailsSubtitle}
                        </CardDescription>
                    </CardHeader>
                    <CardContent className="space-y-6 px-4 py-5 sm:px-6">
                        <div className="grid gap-3 sm:grid-cols-3">
                            <div className="rounded-lg border bg-muted/20 px-4 py-3">
                                <p className="text-muted-foreground text-xs">{p.summaryTotalAdvance}</p>
                                <p className="mt-1 text-lg font-semibold tabular-nums">
                                    {formatMoneyAmountOrDash(summary.total_advances, locale)}
                                </p>
                            </div>
                            <div className="rounded-lg border bg-muted/20 px-4 py-3">
                                <p className="text-muted-foreground text-xs">{p.summaryTotalPaid}</p>
                                <p className="mt-1 text-lg font-semibold tabular-nums text-emerald-700 dark:text-emerald-400">
                                    {formatMoneyAmountOrDash(summary.total_paid, locale)}
                                </p>
                            </div>
                            <div className="rounded-lg border bg-muted/20 px-4 py-3">
                                <p className="text-muted-foreground text-xs">{p.summaryTotalRemaining}</p>
                                <p className="mt-1 text-lg font-semibold tabular-nums text-destructive">
                                    {formatMoneyAmountOrDash(summary.total_remaining, locale)}
                                </p>
                            </div>
                        </div>

                        <div className="overflow-x-auto rounded-md border">
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>{p.colAdvanceNumber}</TableHead>
                                        <TableHead>{p.colAdvanceDate}</TableHead>
                                        <TableHead>{p.colAdvanceType}</TableHead>
                                        <TableHead className="text-end">{p.colAdvanceAmount}</TableHead>
                                        <TableHead className="text-end">{p.colPaidAmount}</TableHead>
                                        <TableHead className="text-end">{p.colRemainingBalance}</TableHead>
                                        <TableHead>{p.colStatus}</TableHead>
                                        {canUpdate ? (
                                            <TableHead className="w-[1%] text-end">{p.colAction}</TableHead>
                                        ) : null}
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {advances.length === 0 ? (
                                        <TableRow>
                                            <TableCell
                                                colSpan={canUpdate ? 8 : 7}
                                                className="text-muted-foreground h-24 text-center"
                                            >
                                                {p.empty}
                                            </TableCell>
                                        </TableRow>
                                    ) : (
                                        advances.map((row) => (
                                            <TableRow key={row.id}>
                                                <TableCell className="font-medium tabular-nums">
                                                    {row.advance_number}
                                                </TableCell>
                                                <TableCell className="whitespace-nowrap">
                                                    {formatEmployeeJoiningDateNumericOrDash(
                                                        row.advance_date,
                                                        locale,
                                                    )}
                                                </TableCell>
                                                <TableCell>{formatType(row.type)}</TableCell>
                                                <TableCell className="text-end tabular-nums">
                                                    {formatMoneyAmountOrDash(row.amount, locale)}
                                                </TableCell>
                                                <TableCell className="text-end tabular-nums text-emerald-700 dark:text-emerald-400">
                                                    {formatMoneyAmountOrDash(row.paid_amount, locale)}
                                                </TableCell>
                                                <TableCell className="text-end tabular-nums text-destructive">
                                                    {formatMoneyAmountOrDash(row.unpaid_amount, locale)}
                                                </TableCell>
                                                <TableCell>
                                                    <div className="space-y-1">
                                                        <SettlementBadge
                                                            status={row.settlement_status}
                                                            labels={labels}
                                                        />
                                                        {!row.is_active ? (
                                                            <div className="text-muted-foreground text-xs">
                                                                {p.statusInactive}
                                                            </div>
                                                        ) : null}
                                                    </div>
                                                </TableCell>
                                                {canUpdate ? (
                                                    <TableCell className="text-end">
                                                        <DropdownMenu>
                                                            <DropdownMenuTrigger asChild>
                                                                <Button
                                                                    variant="ghost"
                                                                    size="icon"
                                                                    className="size-8"
                                                                >
                                                                    <MoreHorizontal className="size-4" />
                                                                    <span className="sr-only">
                                                                        {p.actionsMenuAria}
                                                                    </span>
                                                                </Button>
                                                            </DropdownMenuTrigger>
                                                            <DropdownMenuContent align="end">
                                                                <DropdownMenuItem
                                                                    onSelect={() => setViewRecord(row)}
                                                                >
                                                                    {p.viewRecordDetails}
                                                                </DropdownMenuItem>
                                                                <DropdownMenuItem asChild>
                                                                    <Link
                                                                        href={advanceEdit.url(row.id)}
                                                                        prefetch
                                                                    >
                                                                        <Pencil className="size-4" />
                                                                        {p.editAdvance}
                                                                    </Link>
                                                                </DropdownMenuItem>
                                                                <DropdownMenuSeparator />
                                                                <DropdownMenuItem
                                                                    onSelect={() => setToToggle(row)}
                                                                >
                                                                    {row.is_active ? (
                                                                        <>
                                                                            <UserX className="size-4" />
                                                                            {p.deactivateAdvance}
                                                                        </>
                                                                    ) : (
                                                                        <>
                                                                            <UserCheck className="size-4" />
                                                                            {p.activateAdvance}
                                                                        </>
                                                                    )}
                                                                </DropdownMenuItem>
                                                            </DropdownMenuContent>
                                                        </DropdownMenu>
                                                    </TableCell>
                                                ) : null}
                                            </TableRow>
                                        ))
                                    )}
                                </TableBody>
                            </Table>
                        </div>
                    </CardContent>
                </Card>
            </div>

            <PermanentEmployeeAdvanceDetailDialog
                open={Boolean(viewRecord)}
                onOpenChange={(open) => {
                    if (!open) {
                        setViewRecord(null);
                    }
                }}
                record={viewRecord}
                labels={labels}
                locale={locale}
            />

            <ConfirmActionDialog
                open={Boolean(toToggle)}
                onOpenChange={(open) => {
                    if (!open) {
                        setToToggle(null);
                    }
                }}
                title={
                    toToggle?.is_active
                        ? p.confirmDeactivateTitle
                        : p.confirmActivateTitle
                }
                description={
                    toToggle?.is_active
                        ? p.confirmDeactivateBody
                        : p.confirmActivateBody
                }
                confirmLabel={
                    toToggle?.is_active ? p.deactivateAdvance : p.activateAdvance
                }
                cancelLabel={t.appActions.cancel}
                onConfirm={confirmToggle}
                processing={toggling}
            />
        </AppLayout>
    );
}
