"use client";

import Link from "next/link";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";

import {
  type ColumnDef,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  useReactTable,
} from "@tanstack/react-table";
import { MoreHorizontal, Plus, Search } from "lucide-react";
import { toast } from "sonner";

import { ClickableTableRow, RowActionsCell } from "@/components/admin/clickable-table-row";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { adminRoutes } from "@/lib/admin-routes";
import {
  deleteCruiseCascade,
  getCruiseCabinsByCruise,
  getCruiseDecksByCruise,
  getCruises,
  getSailings,
  saveCruise,
} from "@/lib/cruise-store";
import type { Cruise } from "@/types/cruise";

type CruiseForm = Pick<Cruise, "name" | "cruiseLine" | "description">;

const emptyForm: CruiseForm = { name: "", cruiseLine: "", description: "" };

export default function CruisesPage() {
  const router = useRouter();
  const [cruises, setCruises] = useState<Cruise[]>([]);
  const [search, setSearch] = useState("");
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<Cruise | null>(null);
  const [form, setForm] = useState<CruiseForm>(emptyForm);
  const [deleteTarget, setDeleteTarget] = useState<Cruise | null>(null);

  const load = useCallback(() => setCruises(getCruises()), []);

  useEffect(() => {
    load();
  }, [load]);

  const filtered = useMemo(() => {
    if (!search) return cruises;
    const q = search.toLowerCase();
    return cruises.filter(
      (c) => c.name.toLowerCase().includes(q) || c.cruiseLine.toLowerCase().includes(q),
    );
  }, [cruises, search]);

  const openCreate = () => {
    setEditing(null);
    setForm(emptyForm);
    setSheetOpen(true);
  };

  const openEdit = (cruise: Cruise) => {
    setEditing(cruise);
    setForm({ name: cruise.name, cruiseLine: cruise.cruiseLine, description: cruise.description ?? "" });
    setSheetOpen(true);
  };

  const handleSave = () => {
    if (!form.name.trim() || !form.cruiseLine.trim() || !form.description?.trim()) {
      toast.error("Ship name, cruise line, and description are required");
      return;
    }

    saveCruise({
      id: editing?.id ?? `cruise-${Date.now()}`,
      name: form.name.trim(),
      cruiseLine: form.cruiseLine.trim(),
      description: form.description.trim(),
      createdAt: editing?.createdAt ?? new Date().toISOString().slice(0, 10),
    });
    load();
    setSheetOpen(false);
    toast.success(editing ? "Cruise updated" : "Cruise created");
  };

  const confirmDelete = () => {
    if (!deleteTarget) return;
    const result = deleteCruiseCascade(deleteTarget.id);
    if (!result.ok) toast.error(result.error);
    else {
      toast.success("Cruise deleted");
      load();
    }
    setDeleteTarget(null);
  };

  const columns = useMemo<ColumnDef<Cruise>[]>(
    () => [
      {
        accessorKey: "name",
        header: "Cruise ship",
        cell: ({ row }) => (
          <div>
            <p className="font-medium text-sm">{row.original.name}</p>
            <p className="text-muted-foreground text-xs">{row.original.cruiseLine}</p>
          </div>
        ),
      },
      {
        id: "layout",
        header: "Layout",
        cell: ({ row }) => {
          const decks = getCruiseDecksByCruise(row.original.id).length;
          const cabins = getCruiseCabinsByCruise(row.original.id).length;
          return (
            <span className="text-sm">
              {decks} decks · {cabins} cabins
            </span>
          );
        },
      },
      {
        id: "events",
        header: "Events",
        cell: ({ row }) => {
          const count = getSailings().filter((s) => s.cruiseId === row.original.id).length;
          return <span className="text-sm">{count}</span>;
        },
      },
      {
        id: "actions",
        cell: ({ row }) => (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="size-8" onClick={(e) => e.stopPropagation()}>
                <MoreHorizontal className="size-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Actions</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem asChild>
                <Link href={adminRoutes.cruise(row.original.id)}>View cruise</Link>
              </DropdownMenuItem>
              <DropdownMenuItem onClick={() => openEdit(row.original)}>Edit details</DropdownMenuItem>
              <DropdownMenuItem className="text-destructive" onClick={() => setDeleteTarget(row.original)}>
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ),
      },
    ],
    [],
  );

  const table = useReactTable({
    data: filtered,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: { pagination: { pageSize: 10 } },
  });

  return (
    <div className="flex flex-col gap-4 md:gap-6">
      <div className="flex items-start justify-between gap-3">
        <div>
          <h1 className="font-semibold text-xl">Cruises</h1>
          <p className="text-muted-foreground text-sm">
            Define ship layouts — decks and cabin catalog. Events import inventory from a cruise when created.
          </p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="size-4" />
          Add cruise
        </Button>
      </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 cruises..." value={search} onChange={(e) => setSearch(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}>{flexRender(h.column.columnDef.header, h.getContext())}</TableHead>
                ))}
              </TableRow>
            ))}
          </TableHeader>
          <TableBody>
            {table.getRowModel().rows.length ? (
              table.getRowModel().rows.map((row) => (
                <ClickableTableRow key={row.id} href={adminRoutes.cruise(row.original.id)}>
                  {row.getVisibleCells().map((cell) =>
                    cell.column.id === "actions" ? (
                      <RowActionsCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</RowActionsCell>
                    ) : (
                      <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                    ),
                  )}
                </ClickableTableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={columns.length} className="py-8 text-center text-muted-foreground">
                  No cruise ships defined yet.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent className="w-full sm:max-w-md">
          <SheetHeader>
            <SheetTitle>{editing ? "Edit cruise" : "New cruise ship"}</SheetTitle>
            <SheetDescription>Physical vessel used for events. Add decks and cabins after creating.</SheetDescription>
          </SheetHeader>
          <div className="mt-6 flex w-full flex-col gap-5">
            <div className="space-y-2">
              <Label>Ship name *</Label>
              <Input className="w-full" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} placeholder="Harmony of the Seas" />
            </div>
            <div className="space-y-2">
              <Label>Cruise line *</Label>
              <Input className="w-full" value={form.cruiseLine} onChange={(e) => setForm((f) => ({ ...f, cruiseLine: e.target.value }))} placeholder="Royal Caribbean" />
            </div>
            <div className="space-y-2">
              <Label>Description *</Label>
              <Textarea className="w-full" value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} rows={4} placeholder="Brief description of the vessel and typical use" />
            </div>
          </div>
          <SheetFooter>
            <Button variant="outline" onClick={() => setSheetOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSave}>{editing ? "Save" : "Create"}</Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>

      <AlertDialog open={!!deleteTarget} onOpenChange={(o) => !o && setDeleteTarget(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete {deleteTarget?.name}?</AlertDialogTitle>
            <AlertDialogDescription>Removes decks and cabin catalog. Blocked if linked to events.</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
