"use client";

import { useState } from "react";
import Link from "next/link";
import { ArrowLeft, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { useRepositories } from "@/di/repository-provider";
import { useT } from "@/shared/i18n/client";
import { ROUTES } from "@/shared/constants";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { Button } from "@/presentation/components/ui/button";
import { Input } from "@/presentation/components/ui/input";
import { Switch } from "@/presentation/components/ui/switch";
import { useAnnouncementPermissions } from "@/presentation/components/announcements/use-announcement-permissions";
import type { MenuLabelEntry } from "@/domain/entities/announcement";

/** The pill holds a word or two (the API's MenuLabels::MAX_LENGTH). */
const MAX_LENGTH = 12;

/** The label as Fleet draws it in its menu (SidebarMenu's StatusLabel): same gradient, size and case. */
function LabelPill({ text }: { text: string | null }) {
  return (
    <span className="inline-flex shrink-0 items-center whitespace-nowrap rounded-[4px] bg-gradient-to-br from-[#6366F1] to-[#8B5CF6] px-1.5 py-px text-[9px] font-bold uppercase leading-tight tracking-[0.04em] text-white shadow-[0_1px_3px_rgba(99,102,241,0.3)]">
      {text || "Beta"}
    </span>
  );
}

/** One menu entry: its label on or off and its words, saved on purpose (every client sees it). */
function EntryRow({ entry, canEdit }: { entry: MenuLabelEntry; canEdit: boolean }) {
  const t = useT();
  const L = t.announcements.menuLabels;
  const { announcementRepository } = useRepositories();
  const [saved, setSaved] = useState(entry);
  const [shown, setShown] = useState(entry.shown);
  const [text, setText] = useState(entry.text ?? "");
  const [saving, setSaving] = useState(false);
  const words = text.trim() || null;
  const dirty = shown !== saved.shown || words !== saved.text;

  const save = async () => {
    setSaving(true);
    try {
      const next = await announcementRepository.updateMenuLabel(entry.id, { shown, text: words });
      setSaved(next);
      setText(next.text ?? "");
      toast.success(L.saved);
    } catch (err) {
      const message = (err as { response?: { data?: { message?: string } }; message?: string })?.response?.data?.message ?? (err as Error).message;
      toast.error(message);
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="flex flex-wrap items-center gap-3 px-4 py-2.5">
      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-2">
          <span className="truncate text-sm font-medium">{entry.label}</span>
          {shown && <LabelPill text={words} />}
        </div>
        <p className="truncate text-xs text-muted-foreground">
          {entry.hint && <span>{entry.hint} · </span>}
          <span className="font-mono">{entry.path}</span>
        </p>
      </div>
      <label className="flex items-center gap-2 text-xs text-muted-foreground">
        <Switch checked={shown} onCheckedChange={setShown} disabled={!canEdit || saving} aria-label={`${L.shown} — ${entry.label}`} />
        {L.shown}
      </label>
      <Input
        value={text}
        onChange={(e) => setText(e.target.value)}
        maxLength={MAX_LENGTH}
        placeholder={L.textPlaceholder}
        disabled={!canEdit || saving}
        aria-label={`${L.text} — ${entry.label}`}
        className="h-8 w-32 text-xs"
      />
      <Button type="button" size="sm" variant={dirty ? "default" : "outline"} onClick={save} disabled={!canEdit || !dirty || saving}>
        {saving ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : L.save}
      </Button>
    </div>
  );
}

/**
 * « Étiquettes du menu » (SCRUM-443): the BETA-like labels of Fleet's menu entries, for every client,
 * without a deploy. Fleet reads them with its menu on the next page load.
 */
export function MenuLabelsPage() {
  const t = useT();
  const L = t.announcements.menuLabels;
  usePageHeader(t.pages.announcementMenuLabels.title, t.pages.announcementMenuLabels.subtitle);
  const { announcementRepository } = useRepositories();
  const { canPublish } = useAnnouncementPermissions();
  const { data, loading, error } = useApiQuery(() => announcementRepository.menuLabels());

  return (
    <div className="space-y-4 p-6">
      <div className="flex flex-wrap items-center justify-between gap-3">
        <Link href={ROUTES.announcements} className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground">
          <ArrowLeft className="h-3.5 w-3.5" />
          {t.announcements.actions.back}
        </Link>
        <p className="text-xs text-muted-foreground">{canPublish ? L.help : L.readOnly}</p>
      </div>

      {error ? (
        <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {L.loadError} <span className="text-red-500">({error})</span>
        </div>
      ) : loading || !data ? (
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          <Loader2 className="h-4 w-4 animate-spin" />
          {L.loading}
        </div>
      ) : (
        data.map((section) =>
          section.items.length === 1 ? (
            <div key={section.id} className="rounded-xl border bg-background">
              <EntryRow entry={section.items[0]} canEdit={canPublish} />
            </div>
          ) : (
            <div key={section.id} className="rounded-xl border bg-background">
              <p className="border-b px-4 py-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                {section.label}
                {section.hint && <span className="ml-1.5 font-normal normal-case">{section.hint}</span>}
              </p>
              <div className="divide-y">
                {section.items.map((entry) => <EntryRow key={entry.id} entry={entry} canEdit={canPublish} />)}
              </div>
            </div>
          ),
        )
      )}
    </div>
  );
}
