"use client";

import { useEffect, useMemo, useState } from "react";

import Link from "next/link";

import {
  type ColumnDef,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { ArrowLeft } from "lucide-react";

import { ClickableTableRow } from "@/components/admin/clickable-table-row";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { adminRoutes } from "@/lib/admin-routes";
import {
  getBookingsByReferralCode,
  getGuestById,
  getReferralById,
  getReferralEarnedTotal,
  getSailingById,
} from "@/lib/cruise-store";
import { formatCurrency } from "@/lib/utils";
import type { Booking, BookingStatus, ReferralRecord } from "@/types/cruise";

const statusVariant: Record<BookingStatus, "default" | "secondary" | "destructive" | "outline"> = {
  confirmed: "default",
  pending: "secondary",
  cancelled: "destructive",
  waitlist: "outline",
};

interface ReferralDetailPageProps {
  params: Promise<{ id: string }>;
}

function referralCommission(bookingTotal: number, commissionPercent: number): number {
  return Math.round(bookingTotal * (commissionPercent / 100) * 100) / 100;
}

export default function ReferralDetailPage({ params }: ReferralDetailPageProps) {
  const [referralId, setReferralId] = useState<string | null>(null);
  const [referral, setReferral] = useState<ReferralRecord | null>(null);
  const [bookings, setBookings] = useState<Booking[]>([]);

  useEffect(() => {
    params.then(({ id }) => {
      setReferralId(id);
      const ref = getReferralById(id);
      if (ref) {
        setReferral(ref);
        setBookings(getBookingsByReferralCode(ref.code));
      }
    });
  }, [params]);

  const columns = useMemo<ColumnDef<Booking>[]>(
    () => [
      {
        accessorKey: "bookingCode",
        header: "Code",
        cell: ({ row }) => <span className="font-medium">{row.original.bookingCode}</span>,
      },
      {
        id: "guest",
        header: "Guest",
        cell: ({ row }) => getGuestById(row.original.guestId)?.name ?? "—",
      },
      {
        id: "event",
        header: "Event",
        cell: ({ row }) => getSailingById(row.original.sailingId)?.name ?? "—",
      },
      {
        accessorKey: "total",
        header: "Booking total",
        cell: ({ row }) => formatCurrency(row.original.total),
      },
      {
        id: "commission",
        header: "Commission",
        cell: ({ row }) =>
          referral
            ? formatCurrency(referralCommission(row.original.total, referral.commissionPercent))
            : "—",
      },
      {
        accessorKey: "status",
        header: "Status",
        cell: ({ row }) => (
          <Badge variant={statusVariant[row.original.status]} className="capitalize">
            {row.original.status}
          </Badge>
        ),
      },
      {
        accessorKey: "createdAt",
        header: "Booked",
        cell: ({ row }) => new Date(row.original.createdAt).toLocaleDateString(),
      },
    ],
    [referral],
  );

  const table = useReactTable({ data: bookings, columns, getCoreRowModel: getCoreRowModel() });

  if (referralId && !referral) {
    return (
      <div className="flex flex-col gap-4">
        <p className="text-muted-foreground text-sm">Referral not found.</p>
        <Button asChild variant="outline" className="w-fit">
          <Link href={adminRoutes.referrals()}>Back to referrals</Link>
        </Button>
      </div>
    );
  }

  if (!referral) {
    return <div className="text-muted-foreground text-sm">Loading referral…</div>;
  }

  const earnedTotal = getReferralEarnedTotal(referral);

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" asChild>
          <Link href={adminRoutes.referrals()}>
            <ArrowLeft className="size-4" />
          </Link>
        </Button>
        <div>
          <h1 className="font-mono font-semibold text-xl">{referral.code}</h1>
          <p className="text-muted-foreground text-sm">{referral.affiliateName}</p>
        </div>
        <Badge variant="secondary" className="ml-auto">
          {bookings.length} {bookings.length === 1 ? "booking" : "bookings"}
        </Badge>
      </div>

      <div className="grid gap-4 sm:grid-cols-3">
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="font-normal text-muted-foreground text-sm">Commission rate</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="font-semibold text-2xl">{referral.commissionPercent}%</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="font-normal text-muted-foreground text-sm">Total earned</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="font-semibold text-2xl">{formatCurrency(earnedTotal)}</p>
          </CardContent>
        </Card>
        <Card>
          <CardHeader className="pb-2">
            <CardTitle className="font-normal text-muted-foreground text-sm">Created</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="font-semibold text-2xl">{new Date(referral.createdAt).toLocaleDateString()}</p>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Bookings</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          {bookings.length === 0 ? (
            <p className="px-6 pb-6 text-muted-foreground text-sm">No bookings have used this referral code yet.</p>
          ) : (
            <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) => (
                  <ClickableTableRow key={row.id} href={`/dashboard/bookings/${row.original.id}`}>
                    {row.getVisibleCells().map((cell) => (
                      <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                    ))}
                  </ClickableTableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
