import Layout from '@/components/Layout';
import {
    Table,
    TableBody,
    TableCell,
    TableFooter,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { EllipsisVertical, FolderClosed } from 'lucide-react';
import {
    Empty,
    EmptyDescription,
    EmptyHeader,
    EmptyMedia,
    EmptyTitle,
} from '@/components/ui/empty';
import { router } from '@inertiajs/react';
import AppPagination from '@/components/AppPagination';
import PageHeader from '@/components/PageHeader';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { useEffect, useRef, useState } from 'react';

interface TableData {
    uid: string;
    bank: {
        label: string;
        bank_name: string;
    };
    company: {
        name: string;
        phone?: string;
    };
    purchases: {
        id: string;
    };
    date: string;
    purchases_amount?: number | 0;
    amount: number | 0;
}
interface LinkData {
    url: string | null;
    label: string;
    active: boolean;
}
interface StaticData {
    totalPurchaseAmount: number;
    totalPayment: number;
    totalDue: number;
    totalPurchase: number;
}
interface FilterData {
    start_at?: string;
    end_at?: string;
    pid?: number;
}
interface PageProps {
    data: {
        data: TableData[];
        current_page: number;
        last_page: number;
        links: LinkData[];
        from: number | null;
        to: number | null;
        total: number;
    };
    back: string;
    stats: StaticData;
    filter?: FilterData;
    id: number;
}

export default function transaction({
    data: initData,
    back,
    stats,
    filter,
    id,
}: PageProps) {
    // statics
    const staticsData = [
        {
            name: 'Total Purchases',
            stat: stats.totalPurchaseAmount?.toLocaleString('en-BD', {
                minimumFractionDigits: 1,
                maximumFractionDigits: 1,
            }),
        },
        {
            name: 'Total Payment',
            stat: `+${stats.totalPayment?.toLocaleString('en-BD', {
                minimumFractionDigits: 1,
                maximumFractionDigits: 1,
            })}`,
        },
        {
            name: 'Total Balance',
            stat: `-${stats.totalDue?.toLocaleString('en-BD', {
                minimumFractionDigits: 1,
                maximumFractionDigits: 1,
            })}`,
        },
        {
            name: 'Total Transactions',
            stat: stats.totalPurchase,
        },
    ];

    const [searchStartAt, setSearchStartAt] = useState(filter?.start_at || '');
    const [searchEndAt, setSearchEndAt] = useState(filter?.end_at || '');
    const isFirstRender = useRef(true);
    useEffect(() => {
        if (isFirstRender.current) {
            isFirstRender.current = false;
            return;
        }
        const delayDebounceFn = setTimeout(() => {
            router.get(
                route('purchase.transactions', { id: id }),
                {
                    pid: filter?.pid,
                    start_at: searchStartAt,
                    end_at: searchEndAt,
                },
                {
                    preserveState: true,
                    replace: true,
                },
            );
        }, 500);
        return () => clearTimeout(delayDebounceFn);
    }, [searchStartAt, searchEndAt]);
    return (
        <Layout title="Bank Transactions">
            <PageHeader
                title="Purchase Transactions"
                subtitle="Track and manage all transactions related to your purchases."
            >
                <div className="flex items-center gap-2">
                    <div className="grid grid-cols-2 gap-2">
                        <Input
                            type="date"
                            value={searchStartAt}
                            onChange={(e) => setSearchStartAt(e.target.value)}
                        />
                        <Input
                            type="date"
                            value={searchEndAt}
                            onChange={(e) => setSearchEndAt(e.target.value)}
                        />
                    </div>
                    <Button
                        variant="destructive"
                        onClick={() => router.get(route(back))}
                    >
                        Go back
                    </Button>
                </div>
            </PageHeader>

            <div className="mb-5 flex w-full items-center justify-center">
                <dl className="grid w-full grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-4">
                    {staticsData.map((item) => (
                        <Card className="p-6 py-4 shadow-2xs" key={item.name}>
                            <CardContent className="p-0">
                                <dt className="text-sm font-medium text-muted-foreground">
                                    {item.name}
                                </dt>
                                <dd className="mt-2 flex items-baseline space-x-2.5">
                                    <span className="text-3xl font-semibold text-foreground tabular-nums">
                                        {item.stat}
                                    </span>
                                </dd>
                            </CardContent>
                        </Card>
                    ))}
                </dl>
            </div>

            <Card>
                <CardContent>
                    {initData?.data?.length > 0 ? (
                        <Table>
                            <TableHeader>
                                <TableRow>
                                    <TableHead className="w-25">ID</TableHead>
                                    <TableHead>Date</TableHead>
                                    <TableHead>Purchases</TableHead>
                                    <TableHead>Company</TableHead>
                                    <TableHead>Bank</TableHead>
                                    <TableHead className="text-right">
                                        Credit
                                    </TableHead>
                                    <TableHead className="text-right">
                                        Debit
                                    </TableHead>
                                </TableRow>
                            </TableHeader>
                            <TableBody>
                                {initData?.data?.map((items) => (
                                    <TableRow key={items.uid}>
                                        <TableCell className="font-medium">
                                            {items.uid}
                                        </TableCell>
                                        <TableCell>{items.date}</TableCell>
                                        <TableCell>
                                            #{items.purchases.id}
                                        </TableCell>
                                        <TableCell>
                                            <p className="text-base font-medium">
                                                {items?.company?.name}
                                            </p>
                                            <p className="text-sm">
                                                {items?.company?.phone}
                                            </p>
                                        </TableCell>
                                        <TableCell>
                                            <p className="text-base font-medium">
                                                {items?.bank?.label}
                                            </p>
                                            <p className="text-sm">
                                                {items?.bank?.bank_name}
                                            </p>
                                        </TableCell>
                                        <TableCell className="text-right">
                                            {(
                                                items.purchases_amount || 0
                                            ).toLocaleString('en-BD')}
                                        </TableCell>
                                        <TableCell className="text-right">
                                            {items.amount.toLocaleString(
                                                'en-BD',
                                            )}
                                        </TableCell>
                                    </TableRow>
                                ))}
                            </TableBody>
                        </Table>
                    ) : (
                        <Empty>
                            <EmptyHeader>
                                <EmptyMedia variant="icon">
                                    <FolderClosed />
                                </EmptyMedia>
                                <EmptyTitle>No Transactions Yet</EmptyTitle>
                                <EmptyDescription>
                                    You haven't recorded any transactions yet.
                                    Get started by adding your first
                                    transaction.
                                </EmptyDescription>
                            </EmptyHeader>
                        </Empty>
                    )}

                    <AppPagination data={initData} />
                </CardContent>
            </Card>
        </Layout>
    );
}
