"use client";

import Link from "next/link";

import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { adminRoutes } from "@/lib/admin-routes";
import { getPromoCodes } from "@/lib/cruise-store";

interface EventPromoCodePickerProps {
  selectedPromoIds: string[];
  onChange: (ids: string[]) => void;
}

function promoLabel(promo: { discountType: string; discountValue: number }) {
  return promo.discountType === "percent" ? `${promo.discountValue}% off` : `$${promo.discountValue} off`;
}

export function EventPromoCodePicker({ selectedPromoIds, onChange }: EventPromoCodePickerProps) {
  const promos = getPromoCodes().filter((p) => p.active);
  const scoped = promos.filter((p) => p.sailingIds && p.sailingIds.length > 0);
  const globalAll = promos.filter((p) => !p.sailingIds || p.sailingIds.length === 0);

  const toggle = (promoId: string, checked: boolean) => {
    onChange(
      checked
        ? [...new Set([...selectedPromoIds, promoId])]
        : selectedPromoIds.filter((id) => id !== promoId),
    );
  };

  return (
    <div className="grid gap-2">
      <div className="flex items-center justify-between gap-2">
        <Label>Promo codes</Label>
        <Link href={adminRoutes.promoCodes()} className="text-primary text-xs hover:underline">
          Manage catalog
        </Link>
      </div>
      <p className="text-muted-foreground text-xs">
        Codes guests enter at checkout. All-events codes always apply; toggle event-scoped codes for this event.
      </p>

      {promos.length === 0 ? (
        <p className="rounded-lg border border-dashed p-3 text-muted-foreground text-sm">
          No promo codes yet.{" "}
          <Link href={adminRoutes.promoCodes()} className="text-primary hover:underline">
            Create one
          </Link>
        </p>
      ) : (
        <div className="max-h-48 space-y-2 overflow-y-auto rounded-lg border p-2">
          {globalAll.map((promo) => (
            <div key={promo.id} className="flex items-start gap-3 rounded-md bg-muted/30 px-2 py-1.5">
              <Checkbox checked disabled className="mt-0.5" />
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="font-mono text-sm">{promo.code}</span>
                  <Badge variant="secondary" className="text-[10px]">
                    All events
                  </Badge>
                </div>
                <p className="text-muted-foreground text-xs">
                  {promo.description} · {promoLabel(promo)}
                </p>
              </div>
            </div>
          ))}

          {scoped.map((promo) => (
            <label
              key={promo.id}
              className="flex cursor-pointer items-start gap-3 rounded-md px-2 py-1.5 hover:bg-muted/30"
            >
              <Checkbox
                checked={selectedPromoIds.includes(promo.id)}
                onCheckedChange={(v) => toggle(promo.id, v === true)}
                className="mt-0.5"
              />
              <div className="min-w-0 flex-1">
                <div className="flex flex-wrap items-center gap-2">
                  <span className="font-mono text-sm">{promo.code}</span>
                  <Badge variant="outline" className="text-[10px]">
                    {promoLabel(promo)}
                  </Badge>
                </div>
                <p className="text-muted-foreground text-xs">{promo.description}</p>
              </div>
            </label>
          ))}

          {scoped.length === 0 && globalAll.length > 0 && (
            <p className="px-2 py-1 text-muted-foreground text-xs">
              No event-scoped codes in catalog — create one on Promo Codes and assign specific events.
            </p>
          )}
        </div>
      )}
    </div>
  );
}

export function getSelectedPromoIdsForSailing(sailingId: string): string[] {
  return getPromoCodes()
    .filter((p) => p.sailingIds?.includes(sailingId))
    .map((p) => p.id);
}
