"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, Mail, Phone } from "lucide-react";
import { toast } from "sonner";

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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { adminRoutes } from "@/lib/admin-routes";
import {
  getBookingsByGuest,
  getGuestById,
  getSailingById,
  saveGuest,
} from "@/lib/cruise-store";
import { formatCurrency } from "@/lib/utils";
import type { Booking, BookingStatus, Guest } from "@/types/cruise";

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

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

export default function GuestDetailPage({ params }: GuestDetailPageProps) {
  const [guestId, setGuestId] = useState<string | null>(null);
  const [guest, setGuest] = useState<Guest | null>(null);
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [saving, setSaving] = useState(false);
  const [bookings, setBookings] = useState<Booking[]>([]);

  useEffect(() => {
    params.then(({ id }) => {
      setGuestId(id);
      loadGuest(id);
    });
  }, [params]);

  function loadGuest(id: string) {
    const g = getGuestById(id);
    if (g) {
      setGuest(g);
      setName(g.name);
      setEmail(g.email);
      setPhone(g.phone);
      setBookings(getBookingsByGuest(id));
    }
  }

  const columns = useMemo<ColumnDef<Booking>[]>(
    () => [
      {
        accessorKey: "bookingCode",
        header: "Code",
        cell: ({ row }) => <span className="font-medium">{row.original.bookingCode}</span>,
      },
      {
        id: "event",
        header: "Event",
        cell: ({ row }) => getSailingById(row.original.sailingId)?.name ?? "—",
      },
      {
        accessorKey: "partySize",
        header: "Party",
      },
      {
        accessorKey: "total",
        header: "Total",
        cell: ({ row }) => formatCurrency(row.original.total),
      },
      {
        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(),
      },
    ],
    [],
  );

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

  const handleSave = () => {
    if (!guest) return;
    if (!name.trim() || !email.includes("@")) {
      toast.error("Name and valid email required.");
      return;
    }
    setSaving(true);
    const updated: Guest = { ...guest, name: name.trim(), email: email.trim(), phone: phone.trim() };
    saveGuest(updated);
    setGuest(updated);
    setSaving(false);
    toast.success("Guest updated.");
  };

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

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

  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center gap-3">
        <Button variant="ghost" size="icon" asChild>
          <Link href={adminRoutes.guests()}>
            <ArrowLeft className="size-4" />
          </Link>
        </Button>
        <div>
          <h1 className="font-semibold text-xl">{guest.name}</h1>
          <p className="text-muted-foreground text-sm">
            Guest since {new Date(guest.createdAt).toLocaleDateString()}
          </p>
        </div>
        <Badge variant="secondary" className="ml-auto">
          {bookings.length} {bookings.length === 1 ? "booking" : "bookings"}
        </Badge>
      </div>

      <div className="grid gap-6 lg:grid-cols-[1fr_360px]">
        <div className="flex flex-col gap-6">
          <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 yet.</p>
              ) : (
                <div className="rounded-b-lg border-t">
                  <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>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        <div className="flex flex-col gap-6">
          <Card className="lg:sticky lg:top-4">
            <CardHeader>
              <CardTitle className="text-base">Contact</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="flex flex-col gap-2 text-sm">
                <span className="inline-flex items-center gap-2 text-muted-foreground">
                  <Mail className="size-3.5" />
                  {guest.email}
                </span>
                {guest.phone && (
                  <span className="inline-flex items-center gap-2 text-muted-foreground">
                    <Phone className="size-3.5" />
                    {guest.phone}
                  </span>
                )}
              </div>

              <div className="space-y-3 border-t pt-4">
                <div className="space-y-1.5">
                  <Label>Name</Label>
                  <Input value={name} onChange={(e) => setName(e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label>Email</Label>
                  <Input value={email} onChange={(e) => setEmail(e.target.value)} />
                </div>
                <div className="space-y-1.5">
                  <Label>Phone</Label>
                  <Input value={phone} onChange={(e) => setPhone(e.target.value)} />
                </div>
                <Button onClick={handleSave} disabled={saving} className="w-full">
                  {saving ? "Saving…" : "Save changes"}
                </Button>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
