import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { ChevronLeft, ChevronRight, CreditCard, History } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Spinner } from '@/components/ui/spinner';
import {
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableHeader,
    TableRow,
} from '@/components/ui/table';
import { projectBilling, projectBillingHistory } from '@/client';
import { useProject } from '@/contexts';

const formatMoney = (amount: number, currency: string) =>
    new Intl.NumberFormat(undefined, {
        style: 'currency',
        currency: currency || 'USD',
        currencyDisplay: 'narrowSymbol',
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
    }).format(amount);

const formatDateTime = (v: string) => (v ? new Date(v).toLocaleString() : '-');

export function SettingsBilling() {
    const { project } = useProject();
    const [page, setPage] = useState(1);
    const perPage = 10;

    const {
        data: billingData,
        isLoading: billingLoading,
        isError: billingError,
    } = useQuery({
        queryKey: ['projectBilling', project?.name],
        queryFn: async () => {
            const resp = await projectBilling({ path: { project_name: project!.name } });
            return resp.data?.data ?? null;
        },
        enabled: !!project?.name,
    });

    const {
        data: historyData,
        isLoading: historyLoading,
    } = useQuery({
        queryKey: ['projectBillingHistory', project?.name, page, perPage],
        queryFn: async () => {
            const resp = await projectBillingHistory({
                path: { project_name: project!.name },
            });
            return resp.data?.data ?? null;
        },
        enabled: !!project?.name,
    });

    if (!project) return null;

    if (billingLoading) {
        return (
            <div className="flex items-center justify-center h-48">
                <Spinner />
            </div>
        );
    }

    if (billingError) {
        return (
            <div className="rounded-lg border border-destructive/30 bg-destructive/10 p-4 text-destructive">
                Failed to load billing information.
            </div>
        );
    }

    const records = Array.isArray(historyData) ? historyData : historyData?.list || [];
    const total = historyData?.total || records.length;
    const totalPages = Math.max(1, Math.ceil(total / perPage));

    return (
        <div className="space-y-6">
            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <CreditCard className="h-5 w-5" />
                        Current Billing
                    </CardTitle>
                    <CardDescription>
                        Current cycle quota, usage and account balance.
                    </CardDescription>
                </CardHeader>
                <CardContent className="space-y-5">
                    <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
                        <div className="rounded-md border p-3">
                            <p className="text-xs uppercase tracking-wide text-muted-foreground">
                                Monthly Quota
                            </p>
                            <p className="mt-1 text-xl font-semibold">
                                {formatMoney(
                                    (billingData as { monthly_quota?: number })?.monthly_quota || 0,
                                    (billingData as { currency?: string })?.currency || 'USD',
                                )}
                            </p>
                        </div>
                        <div className="rounded-md border p-3">
                            <p className="text-xs uppercase tracking-wide text-muted-foreground">
                                Current Balance
                            </p>
                            <p className="mt-1 text-xl font-semibold">
                                {formatMoney(
                                    (billingData as { balance?: number })?.balance || 0,
                                    (billingData as { currency?: string })?.currency || 'USD',
                                )}
                            </p>
                        </div>
                        <div className="rounded-md border p-3">
                            <p className="text-xs uppercase tracking-wide text-muted-foreground">
                                Current Usage
                            </p>
                            <p className="mt-1 text-xl font-semibold">
                                {formatMoney(
                                    (billingData as { month_used?: number })?.month_used || 0,
                                    (billingData as { currency?: string })?.currency || 'USD',
                                )}
                            </p>
                        </div>
                    </div>
                </CardContent>
            </Card>

            <Card>
                <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                        <History className="h-5 w-5" />
                        Billing History
                    </CardTitle>
                    <CardDescription>Project billing flow records.</CardDescription>
                </CardHeader>
                <CardContent>
                    {historyLoading ? (
                        <div className="flex items-center justify-center h-32">
                            <Spinner />
                        </div>
                    ) : records.length === 0 ? (
                        <div className="rounded-md border border-dashed p-10 text-center text-sm text-muted-foreground">
                            No billing records yet.
                        </div>
                    ) : (
                        <>
                            <Table>
                                <TableHeader>
                                    <TableRow>
                                        <TableHead>Time</TableHead>
                                        <TableHead>Reason</TableHead>
                                        <TableHead>Amount</TableHead>
                                        <TableHead>Currency</TableHead>
                                        <TableHead>Type</TableHead>
                                    </TableRow>
                                </TableHeader>
                                <TableBody>
                                    {records.map(
                                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                        (item: any) => (
                                            <TableRow key={item.uid}>
                                                <TableCell>
                                                    {formatDateTime(item.created_at)}
                                                </TableCell>
                                                <TableCell className="max-w-xs truncate">
                                                    {item.reason || '-'}
                                                </TableCell>
                                                <TableCell
                                                    className={
                                                        item.amount < 0
                                                            ? 'text-red-600'
                                                            : 'text-green-600'
                                                    }
                                                >
                                                    {formatMoney(item.amount, item.currency)}
                                                </TableCell>
                                                <TableCell>{item.currency}</TableCell>
                                                <TableCell>
                                                    <Badge variant="outline">
                                                        {item.amount < 0 ? 'Charge' : 'Credit'}
                                                    </Badge>
                                                </TableCell>
                                            </TableRow>
                                        ),
                                    )}
                                </TableBody>
                            </Table>

                            {total > perPage && (
                                <div className="mt-6 flex items-center justify-between">
                                    <div className="text-sm text-muted-foreground">
                                        Showing{' '}
                                        {Math.min((page - 1) * perPage + 1, total)} to{' '}
                                        {Math.min(page * perPage, total)} of {total} records
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setPage((p) => Math.max(p - 1, 1))}
                                            disabled={page <= 1}
                                        >
                                            <ChevronLeft className="h-4 w-4" />
                                            Previous
                                        </Button>
                                        <span className="text-sm font-medium">
                                            Page {page} of {totalPages}
                                        </span>
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={() => setPage((p) => Math.min(p + 1, totalPages))}
                                            disabled={page >= totalPages}
                                        >
                                            Next
                                            <ChevronRight className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>
                            )}
                        </>
                    )}
                </CardContent>
            </Card>
        </div>
    );
}
