"use client";

import { useMemo, useState } from "react";

import Link from "next/link";

import {
  type ColumnDef,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  type SortingState,
  useReactTable,
} from "@tanstack/react-table";
import { AlertTriangle, Search } from "lucide-react";
import { toast } from "sonner";

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { useCruiseData } from "@/hooks/use-cruise-data";
import { getBookingById, getGuestById, getPayments, markPaymentPaid, retryPayment } from "@/lib/cruise-store";
import { formatCurrency } from "@/lib/utils";
import type { Payment, PaymentStatus } from "@/types/cruise";

const statusVariant: Record<PaymentStatus, "default" | "secondary" | "destructive" | "outline"> = {
  paid: "default",
  partial: "outline",
  scheduled: "secondary",
  failed: "destructive",
  overdue: "destructive",
};

export default function PaymentsPage() {
  const { data: payments, refresh } = useCruiseData(getPayments);
  const [sorting, setSorting] = useState<SortingState>([{ id: "dueDate", desc: true }]);
  const [globalFilter, setGlobalFilter] = useState("");

  const failedCount = payments.filter((p) => p.status === "failed").length;

  const columns: ColumnDef<Payment>[] = useMemo(
    () => [
      {
        accessorKey: "label",
        header: "Label",
        cell: ({ row }) => (
          <div className="flex items-center gap-2">
            {row.original.status === "failed" && <AlertTriangle className="size-4 text-destructive" />}
            {row.original.label}
          </div>
        ),
      },
      {
        id: "booking",
        header: "Booking",
        cell: ({ row }) => {
          const booking = getBookingById(row.original.bookingId);
          return booking ? (
            <Link href={`/dashboard/bookings/${booking.id}`} className="hover:underline">
              {booking.bookingCode}
            </Link>
          ) : (
            "—"
          );
        },
      },
      {
        id: "guest",
        header: "Guest",
        cell: ({ row }) => getGuestById(row.original.guestId)?.name ?? "—",
      },
      {
        accessorKey: "amount",
        header: "Amount",
        cell: ({ row }) => formatCurrency(row.original.amount),
      },
      {
        accessorKey: "dueDate",
        header: "Due",
      },
      {
        accessorKey: "status",
        header: "Status",
        cell: ({ row }) => (
          <Badge variant={statusVariant[row.original.status]}>{row.original.status}</Badge>
        ),
      },
      {
        id: "actions",
        header: "",
        cell: ({ row }) => (
          <div className="flex gap-1">
            {row.original.status !== "paid" && (
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  markPaymentPaid(row.original.id);
                  toast.success("Marked as paid.");
                  refresh();
                }}
              >
                Mark paid
              </Button>
            )}
            {row.original.status === "failed" && (
              <Button
                variant="secondary"
                size="sm"
                onClick={() => {
                  const ok = retryPayment(row.original.id);
                  if (ok) {
                    toast.success("Retry successful (mock).");
                    refresh();
                  } else {
                    toast.error("Retry failed (mock).");
                  }
                }}
              >
                Retry
              </Button>
            )}
          </div>
        ),
      },
    ],
    [refresh],
  );

  const table = useReactTable({
    data: payments,
    columns,
    state: { sorting, globalFilter },
    onSortingChange: setSorting,
    onGlobalFilterChange: setGlobalFilter,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
  });

  return (
    <div className="flex flex-col gap-4 md:gap-6">
      <div>
        <h1 className="font-semibold text-xl">Payments</h1>
        <p className="text-muted-foreground text-sm">
          {payments.length} total · {failedCount} failed
        </p>
      </div>

      <div className="relative max-w-sm">
        <Search className="absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" />
        <Input
          placeholder="Search payments…"
          value={globalFilter}
          onChange={(e) => setGlobalFilter(e.target.value)}
          className="pl-9"
        />
      </div>

      <div className="rounded-lg border">
        <Table>
          <TableHeader>
            {table.getHeaderGroups().map((hg) => (
              <TableRow key={hg.id}>
                {hg.headers.map((h) => (
                  <TableHead key={h.id}>
                    {h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}
                  </TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.map((row) => (
              <TableRow
                key={row.id}
                className={row.original.status === "failed" ? "bg-destructive/5" : undefined}
              >
                {row.getVisibleCells().map((cell) => (
                  <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
