import { useQuery } from "@tanstack/react-query";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Download, Loader2 } from "lucide-react";
import AiTipBanner from "@/components/ai/AiTipBanner";
import AiReportNarrative from "@/components/ai/AiReportNarrative";
import { paymentsService } from "@/services/payments.service";

export default function PaymentRecordPage() {
  const { data, isLoading } = useQuery({
    queryKey: ["payment-records"],
    queryFn: () => paymentsService.list(),
  });

  const { data: paymobData } = useQuery({
    queryKey: ["paymob-orders"],
    queryFn: () => paymentsService.paymobOrders(),
  });

  const payments = data?.items ?? [];
  const totals = data?.totals;

  const handleExport = () => {
    if (!payments.length) return;
    const header = ["Ref", "Student", "Course", "Product", "Amount", "Currency", "State", "Paid", "Date"];
    const rows = payments.map((p) => [
      p.ref,
      p.student_name,
      p.course_name,
      p.product_name,
      p.amount.toFixed(2),
      p.currency,
      p.state,
      p.paid ? "yes" : "no",
      p.date,
    ]);
    const csv = [header, ...rows].map((r) => r.join(",")).join("\n");
    const blob = new Blob([csv], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `payment-records-${new Date().toISOString().slice(0, 10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Payment Record</h1>
          <p className="text-muted-foreground">
            Live student fees, invoices, and Paymob orders.
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleExport} disabled={!payments.length}>
            <Download className="h-4 w-4 mr-1" /> Export CSV
          </Button>
        </div>
      </div>

      {totals && (
        <div className="grid gap-4 md:grid-cols-4">
          <Card className="border-0 shadow-sm">
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground">Total records</p>
              <p className="text-2xl font-bold">{totals.count}</p>
            </CardContent>
          </Card>
          <Card className="border-0 shadow-sm">
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground">Paid</p>
              <p className="text-2xl font-bold text-green-600">{totals.paid}</p>
            </CardContent>
          </Card>
          <Card className="border-0 shadow-sm">
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground">Unpaid</p>
              <p className="text-2xl font-bold text-red-600">{totals.unpaid}</p>
            </CardContent>
          </Card>
          <Card className="border-0 shadow-sm">
            <CardContent className="pt-6">
              <p className="text-xs text-muted-foreground">Total amount</p>
              <p className="text-2xl font-bold">${totals.amount.toLocaleString()}</p>
            </CardContent>
          </Card>
        </div>
      )}

      <AiTipBanner context="payment-record" variant="recommendation" />

      <Tabs defaultValue="payments">
        <TabsList>
          <TabsTrigger value="payments">Payments</TabsTrigger>
          <TabsTrigger value="paymob">Paymob</TabsTrigger>
        </TabsList>

        <TabsContent value="payments" className="mt-4 space-y-4">
          <AiReportNarrative report_type="payments" data={{ payments }} />
          <Card className="border-0 shadow-sm">
            <CardContent className="p-0">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Ref</TableHead>
                    <TableHead>Student</TableHead>
                    <TableHead>Course</TableHead>
                    <TableHead>Product</TableHead>
                    <TableHead>Amount</TableHead>
                    <TableHead>State</TableHead>
                    <TableHead>Paid</TableHead>
                    <TableHead>Date</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading && (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center py-8">
                        <Loader2 className="h-5 w-5 animate-spin mx-auto" />
                      </TableCell>
                    </TableRow>
                  )}
                  {!isLoading && payments.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={8} className="text-center text-muted-foreground py-8">
                        No payment records yet.
                      </TableCell>
                    </TableRow>
                  )}
                  {payments.map((p) => (
                    <TableRow key={p.id}>
                      <TableCell className="font-mono text-xs">{p.ref}</TableCell>
                      <TableCell>{p.student_name || "—"}</TableCell>
                      <TableCell>{p.course_name || "—"}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {p.product_name || "—"}
                      </TableCell>
                      <TableCell className="font-semibold">
                        ${p.amount.toLocaleString()} {p.currency}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline">{p.state}</Badge>
                      </TableCell>
                      <TableCell>
                        <Badge variant={p.paid ? "default" : "destructive"}>
                          {p.paid ? "Paid" : "Unpaid"}
                        </Badge>
                      </TableCell>
                      <TableCell>{p.date || "—"}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </CardContent>
          </Card>
        </TabsContent>

        <TabsContent value="paymob" className="mt-4">
          <Card className="border-0 shadow-sm">
            <CardContent className="p-6">
              {(paymobData?.items?.length ?? 0) === 0 ? (
                <div className="text-center text-muted-foreground py-8">
                  {paymobData?.message ??
                    "Paymob integration is not yet wired. Orders will appear here once configured."}
                </div>
              ) : (
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead>Order ID</TableHead>
                      <TableHead>Status</TableHead>
                      <TableHead>User</TableHead>
                      <TableHead>Email</TableHead>
                      <TableHead>Amount</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {paymobData!.items.map((o) => (
                      <TableRow key={o.id}>
                        <TableCell className="font-mono text-xs">{o.id}</TableCell>
                        <TableCell>
                          <Badge
                            variant={
                              o.status === "Paid"
                                ? "default"
                                : o.status === "Pending"
                                  ? "secondary"
                                  : "destructive"
                            }
                          >
                            {o.status}
                          </Badge>
                        </TableCell>
                        <TableCell>{o.user}</TableCell>
                        <TableCell>{o.email}</TableCell>
                        <TableCell className="font-semibold">
                          ${o.amount.toFixed(2)}
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              )}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}
