"use client";

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

import { ExternalLink, 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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Sheet, SheetContent, SheetFooter, SheetHeader, SheetTitle } from "@/components/ui/sheet";
import { Switch } from "@/components/ui/switch";
import { adminRoutes } from "@/lib/admin-routes";
import {
  getPromoCodes,
  getPromoCodesForSailing,
  promoAppliesToSailing,
  savePromoCode,
  togglePromoForSailing,
} from "@/lib/cruise-store";
import type { PromoCode } from "@/types/cruise";

interface SailingPromoCodesPanelProps {
  sailingId: string;
}

const emptyPromo = (sailingId: string): PromoCode => ({
  id: `promo-${Date.now()}`,
  code: "",
  description: "",
  discountType: "percent",
  discountValue: 10,
  usageLimit: 100,
  usageCount: 0,
  active: true,
  sailingIds: [sailingId],
});

export function SailingPromoCodesPanel({ sailingId }: SailingPromoCodesPanelProps) {
  const [refreshKey, setRefreshKey] = useState(0);
  const reload = useCallback(() => setRefreshKey((k) => k + 1), []);
  void refreshKey;

  const [sheetOpen, setSheetOpen] = useState(false);
  const [draft, setDraft] = useState<PromoCode>(() => emptyPromo(sailingId));

  const allPromos = useMemo(() => getPromoCodes(), [refreshKey]);
  const activeForEvent = useMemo(() => getPromoCodesForSailing(sailingId), [sailingId, refreshKey]);
  const scopedPromos = allPromos.filter((p) => p.sailingIds && p.sailingIds.length > 0);
  const globalPromos = allPromos.filter((p) => !p.sailingIds || p.sailingIds.length === 0);

  const handleToggle = (promo: PromoCode, enabled: boolean) => {
    if (!promo.sailingIds || promo.sailingIds.length === 0) {
      toast.message("This code applies to all events. Edit it in Promo Codes to restrict scope.");
      return;
    }
    togglePromoForSailing(promo.id, sailingId, enabled);
    reload();
    toast.success(enabled ? "Promo enabled for this event" : "Promo removed from this event");
  };

  const handleCreate = () => {
    if (!draft.code.trim()) {
      toast.error("Code is required");
      return;
    }
    savePromoCode({ ...draft, code: draft.code.toUpperCase(), sailingIds: [sailingId] });
    reload();
    setSheetOpen(false);
    toast.success("Promo code created for this event");
  };

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border bg-muted/30 px-4 py-3">
        <div>
          <p className="font-medium text-sm">{activeForEvent.length} promo codes available at checkout</p>
          <p className="text-muted-foreground text-xs">
            Guests enter codes in booking wizard step 6. Marketing highlights on the public page are separate.
          </p>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button variant="secondary" size="sm" onClick={() => { setDraft(emptyPromo(sailingId)); setSheetOpen(true); }}>
            <Plus className="size-4" />
            New event promo
          </Button>
          <Button variant="outline" size="sm" asChild>
            <Link href={adminRoutes.promoCodes()}>
              <ExternalLink className="size-4" />
              Global promo codes
            </Link>
          </Button>
        </div>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Active for this event</CardTitle>
          <CardDescription>These codes validate during checkout for this event.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-2">
          {activeForEvent.length === 0 ? (
            <p className="text-muted-foreground text-sm">No promo codes enabled yet.</p>
          ) : (
            activeForEvent.map((promo) => (
              <div key={promo.id} className="flex flex-wrap items-center justify-between gap-2 rounded-lg border px-3 py-2.5">
                <div>
                  <p className="font-mono font-medium text-sm">{promo.code}</p>
                  <p className="text-muted-foreground text-xs">{promo.description}</p>
                </div>
                <div className="flex items-center gap-2">
                  <Badge variant="outline">
                    {promo.discountType === "percent" ? `${promo.discountValue}%` : `$${promo.discountValue}`}
                  </Badge>
                  {!promo.sailingIds || promo.sailingIds.length === 0 ? (
                    <Badge variant="secondary" className="text-[10px]">All events</Badge>
                  ) : (
                    <Badge variant="secondary" className="text-[10px]">Event-scoped</Badge>
                  )}
                </div>
              </div>
            ))
          )}
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="text-base">Attach existing codes</CardTitle>
          <CardDescription>Enable event-scoped promos from the global catalog.</CardDescription>
        </CardHeader>
        <CardContent className="space-y-3">
          {scopedPromos.length === 0 ? (
            <p className="text-muted-foreground text-sm">No event-scoped promos in the catalog yet.</p>
          ) : (
            scopedPromos.map((promo) => {
              const enabled = promoAppliesToSailing(promo, sailingId);
              return (
                <label key={promo.id} className="flex cursor-pointer items-start gap-3 rounded-lg border p-3 hover:bg-muted/30">
                  <Checkbox checked={enabled} onCheckedChange={(v) => handleToggle(promo, v === true)} className="mt-0.5" />
                  <div className="min-w-0 flex-1">
                    <p className="font-mono font-medium text-sm">{promo.code}</p>
                    <p className="text-muted-foreground text-xs">{promo.description}</p>
                    <p className="mt-1 text-muted-foreground text-[10px]">
                      {promo.discountType === "percent" ? `${promo.discountValue}% off` : `$${promo.discountValue} off`}
                      {" · "}
                      {promo.usageCount}/{promo.usageLimit} used
                    </p>
                  </div>
                </label>
              );
            })
          )}
        </CardContent>
      </Card>

      {globalPromos.length > 0 && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">All-events codes</CardTitle>
            <CardDescription>Always valid on every active event — manage in global Promo Codes.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-2">
            {globalPromos.filter((p) => p.active).map((promo) => (
              <div key={promo.id} className="flex items-center justify-between rounded-lg border bg-muted/20 px-3 py-2">
                <div>
                  <p className="font-mono text-sm">{promo.code}</p>
                  <p className="text-muted-foreground text-xs">{promo.description}</p>
                </div>
                <Badge variant="secondary" className="text-[10px]">All events</Badge>
              </div>
            ))}
          </CardContent>
        </Card>
      )}

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent className="overflow-y-auto sm:max-w-md">
          <SheetHeader>
            <SheetTitle>New promo for this event</SheetTitle>
          </SheetHeader>
          <div className="mt-4 space-y-4 px-1">
            <div className="space-y-1.5">
              <Label>Code</Label>
              <Input value={draft.code} onChange={(e) => setDraft({ ...draft, code: e.target.value })} />
            </div>
            <div className="space-y-1.5">
              <Label>Description</Label>
              <Input value={draft.description} onChange={(e) => setDraft({ ...draft, description: e.target.value })} />
            </div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5">
                <Label>Type</Label>
                <select
                  className="flex h-8 w-full rounded-lg border border-input bg-transparent px-2 text-sm"
                  value={draft.discountType}
                  onChange={(e) => setDraft({ ...draft, discountType: e.target.value as PromoCode["discountType"] })}
                >
                  <option value="percent">Percent</option>
                  <option value="fixed">Fixed</option>
                </select>
              </div>
              <div className="space-y-1.5">
                <Label>Value</Label>
                <Input
                  type="number"
                  value={draft.discountValue}
                  onChange={(e) => setDraft({ ...draft, discountValue: Number(e.target.value) })}
                />
              </div>
            </div>
            <div className="space-y-1.5">
              <Label>Usage limit</Label>
              <Input
                type="number"
                value={draft.usageLimit}
                onChange={(e) => setDraft({ ...draft, usageLimit: Number(e.target.value) })}
              />
            </div>
            <label className="flex items-center gap-2 text-sm">
              <Switch checked={draft.active} onCheckedChange={(v) => setDraft({ ...draft, active: v })} />
              Active
            </label>
          </div>
          <SheetFooter className="mt-6">
            <Button onClick={handleCreate}>Create promo</Button>
          </SheetFooter>
        </SheetContent>
      </Sheet>
    </div>
  );
}
