"use client";

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

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

import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Sheet, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Switch } from "@/components/ui/switch";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Textarea } from "@/components/ui/textarea";
import { adminRoutes } from "@/lib/admin-routes";
import {
  deleteAddOn,
  getAddOnsForSailing,
  getGlobalAddOns,
  getSailingById,
  saveAddOn,
  setLinkedAddOnsForSailing,
} from "@/lib/cruise-store";
import { formatCurrency } from "@/lib/utils";
import type { AddOn, AddOnCategory } from "@/types/cruise";

const CATEGORIES: { value: AddOnCategory; label: string }[] = [
  { value: "merchandise", label: "Merchandise" },
  { value: "excursions", label: "Excursions" },
  { value: "private_events", label: "Private Events" },
  { value: "insurance", label: "Insurance" },
  { value: "transportation", label: "Transportation" },
  { value: "upgrades", label: "Upgrades" },
  { value: "custom", label: "Custom" },
];

type AddOnForm = {
  name: string;
  description: string;
  category: AddOnCategory;
  price: string;
  active: boolean;
};

const emptyForm: AddOnForm = {
  name: "",
  description: "",
  category: "merchandise",
  price: "0",
  active: true,
};

interface SailingAddOnsPanelProps {
  sailingId: string;
}

export function SailingAddOnsPanel({ sailingId }: SailingAddOnsPanelProps) {
  const [refreshKey, setRefreshKey] = useState(0);
  const [sheetOpen, setSheetOpen] = useState(false);
  const [editing, setEditing] = useState<AddOn | null>(null);
  const [form, setForm] = useState<AddOnForm>(emptyForm);

  const reload = useCallback(() => setRefreshKey((k) => k + 1), []);

  const sailing = useMemo(() => getSailingById(sailingId), [sailingId, refreshKey]);
  const globalCatalog = useMemo(() => getGlobalAddOns(), [refreshKey]);
  const linkedIds = sailing?.linkedAddOnIds ?? globalCatalog.filter((a) => a.active).map((a) => a.id);
  const eventAddOns = useMemo(
    () => getAddOnsForSailing(sailingId).filter((a) => a.sailingId === sailingId),
    [sailingId, refreshKey],
  );
  const checkoutAddOns = useMemo(() => getAddOnsForSailing(sailingId), [sailingId, refreshKey]);

  const toggleGlobal = (addOnId: string, checked: boolean) => {
    const next = checked ? [...linkedIds, addOnId] : linkedIds.filter((id) => id !== addOnId);
    setLinkedAddOnsForSailing(sailingId, next);
    reload();
    toast.success(checked ? "Global add-on enabled for this event" : "Global add-on removed from this event");
  };

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

  const openEdit = (addOn: AddOn) => {
    setEditing(addOn);
    setForm({
      name: addOn.name,
      description: addOn.description,
      category: addOn.category,
      price: String(addOn.price),
      active: addOn.active,
    });
    setSheetOpen(true);
  };

  const handleSave = () => {
    if (!form.name.trim()) {
      toast.error("Name is required");
      return;
    }

    saveAddOn({
      id: editing?.id ?? `addon-${Date.now()}`,
      name: form.name.trim(),
      description: form.description.trim(),
      category: form.category,
      price: Number.parseFloat(form.price) || 0,
      sailingId,
      active: form.active,
      createdAt: editing?.createdAt ?? new Date().toISOString().slice(0, 10),
    });
    reload();
    setSheetOpen(false);
    toast.success(editing ? "Add-on updated" : "Add-on created");
  };

  const handleDelete = (id: string) => {
    deleteAddOn(id);
    reload();
    toast.success("Add-on removed");
  };

  const columns = useMemo<ColumnDef<AddOn>[]>(
    () => [
      { accessorKey: "name", header: "Add-on", cell: ({ row }) => <span className="font-medium text-sm">{row.original.name}</span> },
      { accessorKey: "category", header: "Category", cell: ({ row }) => <span className="text-sm capitalize">{row.original.category.replace("_", " ")}</span> },
      { accessorKey: "price", header: "Price", cell: ({ row }) => <span className="text-sm">{formatCurrency(row.original.price)}</span> },
      {
        accessorKey: "active",
        header: "Status",
        cell: ({ row }) => (
          <Badge variant={row.original.active ? "default" : "secondary"} className="text-xs">
            {row.original.active ? "Active" : "Inactive"}
          </Badge>
        ),
      },
      {
        id: "actions",
        cell: ({ row }) => (
          <DropdownMenu>
            <DropdownMenuTrigger asChild>
              <Button variant="ghost" size="icon" className="size-8">
                <MoreHorizontal className="size-4" />
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuLabel>Actions</DropdownMenuLabel>
              <DropdownMenuSeparator />
              <DropdownMenuItem onClick={() => openEdit(row.original)}>Edit</DropdownMenuItem>
              <DropdownMenuItem className="text-destructive" onClick={() => handleDelete(row.original.id)}>
                Delete
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        ),
      },
    ],
    [],
  );

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

  return (
    <div className="flex flex-col gap-4">
      <div className="rounded-lg border bg-muted/30 px-4 py-3">
        <p className="font-medium text-sm">
          {checkoutAddOns.length} add-ons at checkout
          <span className="font-normal text-muted-foreground">
            {" "}
            ({linkedIds.filter((id) => globalCatalog.some((g) => g.id === id)).length} from global catalog ·{" "}
            {eventAddOns.length} event-exclusive)
          </span>
        </p>
        <p className="text-muted-foreground text-xs">
          Prices come from the global catalog or event-specific records. Same items as{" "}
          <Link href={adminRoutes.globalAddOns()} className="text-primary hover:underline">
            Global Add-ons
          </Link>
          .
        </p>
      </div>

      <Card>
        <CardHeader className="flex flex-row items-start justify-between gap-2">
          <div>
            <CardTitle className="text-base">Global catalog</CardTitle>
            <CardDescription>
              Select upsells from the shared catalog — prices are managed centrally and shown in checkout.
            </CardDescription>
          </div>
          <Button variant="outline" size="sm" asChild>
            <Link href={adminRoutes.globalAddOns()}>
              <ExternalLink className="size-4" />
              Manage catalog
            </Link>
          </Button>
        </CardHeader>
        <CardContent className="space-y-2">
          {globalCatalog.length === 0 ? (
            <p className="text-muted-foreground text-sm">No global add-ons in catalog.</p>
          ) : (
            globalCatalog.map((addon) => {
              const checked = linkedIds.includes(addon.id);
              return (
                <label
                  key={addon.id}
                  className="flex cursor-pointer items-start gap-3 rounded-lg border p-3 hover:bg-muted/30"
                >
                  <Checkbox
                    checked={checked}
                    disabled={!addon.active}
                    onCheckedChange={(v) => toggleGlobal(addon.id, v === true)}
                    className="mt-0.5"
                  />
                  <div className="min-w-0 flex-1">
                    <div className="flex flex-wrap items-center gap-2">
                      <p className="font-medium text-sm">{addon.name}</p>
                      <Badge variant="outline" className="text-[10px] capitalize">
                        {addon.category.replace("_", " ")}
                      </Badge>
                      {!addon.active && (
                        <Badge variant="secondary" className="text-[10px]">
                          Inactive in catalog
                        </Badge>
                      )}
                    </div>
                    <p className="text-muted-foreground text-xs">{addon.description}</p>
                  </div>
                  <p className="shrink-0 font-semibold text-sm tabular-nums">{formatCurrency(addon.price)}</p>
                </label>
              );
            })
          )}
        </CardContent>
      </Card>

      <div className="flex items-center justify-between gap-3">
        <div>
          <p className="font-medium text-sm">Event-exclusive add-ons</p>
          <p className="text-muted-foreground text-xs">Only available on this event — e.g. branded excursions.</p>
        </div>
        <Button onClick={openCreate}>
          <Plus className="size-4" />
          Add event add-on
        </Button>
      </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) => (
                <TableRow key={row.id}>
                  {row.getVisibleCells().map((cell) => (
                    <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                  ))}
                </TableRow>
              ))
            ) : (
              <TableRow>
                <TableCell colSpan={columns.length} className="py-8 text-center text-muted-foreground">
                  No event-exclusive add-ons yet.
                </TableCell>
              </TableRow>
            )}
          </TableBody>
        </Table>
      </div>

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent className="w-full overflow-y-auto sm:max-w-lg">
          <SheetHeader>
            <SheetTitle>{editing ? "Edit add-on" : "New event add-on"}</SheetTitle>
            <SheetDescription>Exclusive to this event. For shared upsells, use the global catalog above.</SheetDescription>
          </SheetHeader>
          <div className="mt-4 flex flex-col gap-4 px-4">
            <div className="grid gap-1.5">
              <Label>Name</Label>
              <Input value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} />
            </div>
            <div className="grid gap-1.5">
              <Label>Description</Label>
              <Textarea value={form.description} onChange={(e) => setForm((f) => ({ ...f, description: e.target.value }))} rows={3} />
            </div>
            <div className="grid gap-1.5">
              <Label>Category</Label>
              <Select value={form.category} onValueChange={(v) => setForm((f) => ({ ...f, category: v as AddOnCategory }))}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {CATEGORIES.map((c) => (
                    <SelectItem key={c.value} value={c.value}>
                      {c.label}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
            <div className="grid gap-1.5">
              <Label>Price</Label>
              <Input type="number" value={form.price} onChange={(e) => setForm((f) => ({ ...f, price: e.target.value }))} />
            </div>
            <div className="flex items-center justify-between">
              <Label>Active</Label>
              <Switch checked={form.active} onCheckedChange={(v) => setForm((f) => ({ ...f, active: v }))} />
            </div>
          </div>
          <SheetFooter>
            <Button variant="outline" onClick={() => setSheetOpen(false)}>
              Cancel
            </Button>
            <Button onClick={handleSave}>{editing ? "Save" : "Create"}</Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>
    </div>
  );
}
