"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { toast } from "sonner";
import {
  Archive, ArrowLeft, BarChart3, Copy, Eye, FlaskConical, Loader2, MoreHorizontal, Pencil, RotateCcw, Save, Send, Trash2, Undo2,
} from "lucide-react";
import { useRepositories } from "@/di/repository-provider";
import { env } from "@/infrastructure/config/env";
import { useT } from "@/shared/i18n/client";
import { ROUTES } from "@/shared/constants";
import { FORMAT_FIELDS } from "@/shared/constants/announcements";
import { displayState, emptyInput, extractFieldErrors, toInput } from "@/shared/lib/announcements";
import { cn } from "@/shared/lib/utils";
import { usePageHeader } from "@/presentation/hooks/use-page-header";
import { useApiQuery } from "@/presentation/hooks/use-api-query";
import { Button } from "@/presentation/components/ui/button";
import { Skeleton } from "@/presentation/components/ui/skeleton";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/presentation/components/ui/tabs";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/presentation/components/ui/dropdown-menu";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/presentation/components/ui/alert-dialog";
import { DisplayStateBadge, FormatBadge } from "@/presentation/components/announcements/announcement-badges";
import { useAnnouncementActions, useAvailableActions, type AnnouncementAction } from "@/presentation/components/announcements/announcement-actions";
import { useAnnouncementPermissions } from "@/presentation/components/announcements/use-announcement-permissions";
import { useAudienceCount } from "@/presentation/components/announcements/use-audience-count";
import { AnnouncementSimulation } from "@/presentation/components/announcements/announcement-simulation";
import { AnnouncementStats } from "@/presentation/components/announcements/announcement-stats";
import { AudiencePanel, HistoryPanel } from "@/presentation/components/announcements/side-panels";
import { PreviewDialog, PublishDialog } from "@/presentation/components/announcements/announcement-dialogs";
import { FormatSection } from "@/presentation/components/announcements/editor-sections/format-section";
import { ContentSection } from "@/presentation/components/announcements/editor-sections/content-section";
import { PlacementSection } from "@/presentation/components/announcements/editor-sections/placement-section";
import { StepsSection } from "@/presentation/components/announcements/editor-sections/steps-section";
import { AudienceSection } from "@/presentation/components/announcements/editor-sections/audience-section";
import { ScheduleSection } from "@/presentation/components/announcements/editor-sections/schedule-section";
import { AdoptionSection } from "@/presentation/components/announcements/editor-sections/adoption-section";
import type {
  Announcement,
  AnnouncementCatalogs,
  AnnouncementFieldErrors,
  AnnouncementInput,
} from "@/domain/entities/announcement";

/** Loads the catalogs (and the announcement) then mounts the editor, once per announcement. */
export function AnnouncementEditorPage({ id }: { id: number | null }) {
  const t = useT();
  usePageHeader(id ? t.announcements.editor.editTitle : t.announcements.editor.newTitle, t.pages.announcements.title);
  const { announcementRepository } = useRepositories();

  const catalogs = useApiQuery(() => announcementRepository.catalogs(), { deps: [] });
  const announcement = useApiQuery(() => announcementRepository.get(id!), { enabled: id !== null, deps: [id] });

  if (catalogs.error || announcement.error) {
    return (
      <div className="p-6">
        <BackLink dirty={false} />
        <div className="mt-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
          {id && announcement.error ? t.announcements.errors.notFound : t.announcements.errors.load}
        </div>
      </div>
    );
  }
  if (!catalogs.data || (id !== null && !announcement.data)) {
    return (
      <div className="space-y-4 p-6">
        <Skeleton className="h-10 w-80" />
        <div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_420px]">
          <Skeleton className="h-[600px] rounded-xl" />
          <Skeleton className="h-[480px] rounded-xl" />
        </div>
      </div>
    );
  }
  return <AnnouncementEditor key={id ?? "new"} initial={announcement.data} catalogs={catalogs.data} />;
}

function draftKey(id: number | null) {
  return `dadycar-admin:announcement-draft:${id ?? "new"}`;
}

function readDraft(id: number | null, baseline: string, savedAt: string | null): AnnouncementInput | null {
  try {
    const raw = window.localStorage.getItem(draftKey(id));
    if (!raw) return null;
    const { input, at } = JSON.parse(raw) as { input: AnnouncementInput; at: string };
    if (JSON.stringify(input) === baseline) return null;
    if (savedAt && new Date(at) <= new Date(savedAt)) return null;
    return input;
  } catch {
    return null;
  }
}

function AnnouncementEditor({ initial, catalogs }: { initial: Announcement | null; catalogs: AnnouncementCatalogs }) {
  const t = useT();
  const e = t.announcements.editor;
  const router = useRouter();
  const params = useSearchParams();
  const { announcementRepository } = useRepositories();
  const { canManage, canPublish } = useAnnouncementPermissions();
  const available = useAvailableActions();

  const [saved, setSaved] = useState<Announcement | null>(initial);
  const [input, setInput] = useState<AnnouncementInput>(() => (initial ? toInput(initial) : emptyInput("banner")));
  const [baseline, setBaseline] = useState(() => JSON.stringify(input));
  const [restorable, setRestorable] = useState<AnnouncementInput | null>(() =>
    typeof window === "undefined" ? null : readDraft(initial?.id ?? null, JSON.stringify(input), initial?.updated_at ?? null),
  );
  const [errors, setErrors] = useState<AnnouncementFieldErrors>({});
  const [saving, setSaving] = useState(false);
  const [publishing, setPublishing] = useState(false);
  const [publishOpen, setPublishOpen] = useState(() => params.get("publish") === "1");
  const [previewOpen, setPreviewOpen] = useState(() => params.get("preview") === "1");
  const [tab, setTab] = useState(() => (params.get("tab") === "stats" ? "stats" : "editor"));
  const [panel, setPanel] = useState("simulation");
  const [audienceConfirm, setAudienceConfirm] = useState<{ before: number; after: number } | null>(null);
  const [exampleVehicleId, setExampleVehicleId] = useState<number | null>(null);
  const [historyKey, setHistoryKey] = useState(0);
  // The step being edited: the preview shows it, and a click in the preview attaches it.
  const [activeStep, setActiveStep] = useState(0);

  const { data: exampleVehicles } = useApiQuery(() => announcementRepository.exampleVehicles(""), { deps: [] });
  const count = useAudienceCount(input.audience, input.rules);

  const id = saved?.id ?? null;
  const current = useMemo(() => JSON.stringify(input), [input]);
  const dirty = current !== baseline;
  const state = saved ? displayState(saved) : "draft";
  const locked = !!saved?.first_published_at;
  const readOnly = !canManage || state === "ended" || state === "archived";
  const disabled = readOnly || saving || publishing;

  // Autosave of unsaved changes (restored on the next visit) and the leave guard.
  useEffect(() => {
    if (readOnly) return;
    const timer = setTimeout(() => {
      try {
        if (dirty) window.localStorage.setItem(draftKey(id), JSON.stringify({ input, at: new Date().toISOString() }));
        else window.localStorage.removeItem(draftKey(id));
      } catch {
        // Storage unavailable: no autosave.
      }
    }, 800);
    return () => clearTimeout(timer);
  }, [current, dirty, id, input, readOnly]);

  useEffect(() => {
    if (!dirty) return;
    const warn = (ev: BeforeUnloadEvent) => {
      ev.preventDefault();
    };
    window.addEventListener("beforeunload", warn);
    return () => window.removeEventListener("beforeunload", warn);
  }, [dirty]);

  const update = (patch: Partial<AnnouncementInput>) => {
    setInput((prev) => ({ ...prev, ...patch }));
    const keys = Object.keys(patch);
    setErrors((prev) => Object.fromEntries(Object.entries(prev).filter(([field]) => !keys.some((k) => field === k || field.startsWith(`${k}.`) || field.startsWith(`${k}_`)))));
  };

  const accept = (a: Announcement) => {
    const next = toInput(a);
    setSaved(a);
    setInput(next);
    setBaseline(JSON.stringify(next));
    setErrors({});
    setHistoryKey((k) => k + 1);
    try {
      window.localStorage.removeItem(draftKey(a.id));
      window.localStorage.removeItem(draftKey(null));
    } catch {
      // ignore
    }
  };

  const showErrors = (err: unknown) => {
    const fieldErrors = extractFieldErrors(err);
    if (fieldErrors) {
      setErrors(fieldErrors);
      toast.error(t.announcements.toasts.fixErrors);
      setTab("editor");
      requestAnimationFrame(() =>
        document.querySelector('[aria-invalid="true"], [role="alert"]')?.scrollIntoView({ behavior: "smooth", block: "center" }),
      );
      return;
    }
    const message = (err as { response?: { data?: { message?: string } } })?.response?.data?.message ?? (err as Error).message;
    toast.error(message);
  };

  /** Saves; a new announcement then moves to its own page (with `then` appended, e.g. "?publish=1"). */
  const persist = async (then = ""): Promise<Announcement | null> => {
    setSaving(true);
    try {
      if (!saved) {
        const created = await announcementRepository.create(input);
        accept(created);
        toast.success(t.announcements.toasts.saved);
        router.replace(`${ROUTES.announcements}/${created.id}${then}`);
        return created;
      }
      const updated = await announcementRepository.update(saved.id, input);
      accept(updated);
      toast.success(t.announcements.toasts.saved);
      return updated;
    } catch (err) {
      showErrors(err);
      return null;
    } finally {
      setSaving(false);
    }
  };

  const save = async () => {
    // Changing who sees a live announcement is confirmed with the user delta (spec §6.2).
    const visible = state === "live" || state === "scheduled";
    if (saved && visible && JSON.stringify(saved.audience) !== JSON.stringify(input.audience) && count.count) {
      setAudienceConfirm({ before: saved.counts.eligible, after: count.count.count });
      return;
    }
    await persist();
  };

  const openPublish = async () => {
    if (!saved) {
      await persist("?publish=1");
      return;
    }
    if (dirty && !(await persist())) return;
    setPublishOpen(true);
  };

  const publish = async () => {
    if (!saved) return;
    setPublishing(true);
    try {
      const published = await announcementRepository.publish(saved.id);
      accept(published);
      setPublishOpen(false);
      toast.success(displayState(published) === "scheduled" ? t.announcements.toasts.scheduled : t.announcements.toasts.published);
    } catch (err) {
      setPublishOpen(false);
      showErrors(err);
    } finally {
      setPublishing(false);
    }
  };

  const { run, dialogs } = useAnnouncementActions((updated, action) => {
    if (action === "delete") return router.push(ROUTES.announcements);
    if (updated && action !== "duplicate") accept(updated);
  });

  const moreActions = saved
    ? available(saved).filter((a) => !["edit", "preview", "publish", "stats"].includes(a) && (canManage || a === "duplicate"))
    : [];
  const ACTION_ICONS: Partial<Record<AnnouncementAction, React.ComponentType<{ className?: string }>>> = {
    duplicate: Copy, delete: Trash2, unpublish: Undo2, archive: Archive, reset: RotateCcw,
  };

  const sectionProps = { input, update, errors, catalogs, locked, disabled };
  const spec = FORMAT_FIELDS[input.format];
  const statsAvailable = !!saved?.first_published_at;

  return (
    <div className="space-y-4 p-6">
      {/* Header */}
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="min-w-0 space-y-1.5">
          <BackLink dirty={dirty} />
          <div className="flex flex-wrap items-center gap-2">
            <h1 className="truncate text-lg font-semibold">{input.title.fr || (saved ? e.editTitle : e.newTitle)}</h1>
            <DisplayStateBadge state={state} />
            <FormatBadge format={input.format} stepCount={input.steps.length} />
            {saved && saved.round > 1 && <span className="text-xs text-muted-foreground">{t.announcements.list.round(saved.round)}</span>}
            {env.announcementsMock && (
              <span className="inline-flex items-center gap-1 rounded-full border border-purple-200 bg-purple-50 px-2 py-0.5 text-[11px] font-medium text-purple-700">
                <FlaskConical className="h-3 w-3" />
                Mock
              </span>
            )}
          </div>
        </div>
        <div className="flex flex-wrap items-center gap-2">
          {!readOnly && (
            <span className={cn("text-xs", dirty ? "font-medium text-amber-700" : "text-muted-foreground")} aria-live="polite">
              {dirty ? e.unsaved : e.allSaved}
            </span>
          )}
          {!readOnly && (
            <Button type="button" variant="outline" size="sm" onClick={save} disabled={saving || publishing || (!dirty && !!saved)}>
              {saving ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : <Save className="mr-1.5 h-3.5 w-3.5" />}
              {saving ? t.announcements.actions.saving : t.announcements.actions.saveDraft}
            </Button>
          )}
          {saved && state !== "archived" && (
            <Button type="button" variant="outline" size="sm" onClick={() => setPreviewOpen(true)}>
              <Eye className="mr-1.5 h-3.5 w-3.5" />
              {t.announcements.actions.preview}
            </Button>
          )}
          {state === "draft" && canPublish && canManage && (
            <Button type="button" size="sm" onClick={openPublish} disabled={saving || publishing}>
              <Send className="mr-1.5 h-3.5 w-3.5" />
              {t.announcements.actions.publish}
            </Button>
          )}
          {moreActions.length > 0 && saved && (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button type="button" variant="ghost" size="icon-sm" aria-label="…">
                  <MoreHorizontal className="h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent align="end">
                {moreActions.map((action) => {
                  const Icon = ACTION_ICONS[action] ?? Pencil;
                  return (
                    <DropdownMenuItem key={action} onClick={() => run(action, saved)} className={action === "delete" ? "text-destructive focus:text-destructive" : undefined}>
                      <Icon className="mr-2 h-4 w-4" />
                      {t.announcements.actions[action]}
                    </DropdownMenuItem>
                  );
                })}
              </DropdownMenuContent>
            </DropdownMenu>
          )}
        </div>
      </div>

      {restorable && !readOnly && (
        <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-blue-200 bg-blue-50 px-4 py-2.5 text-sm text-blue-900">
          {e.autosaveFound}
          <div className="flex gap-2">
            <Button
              size="sm"
              onClick={() => {
                setInput(restorable);
                setRestorable(null);
              }}
            >
              {e.autosaveRestore}
            </Button>
            <Button
              size="sm"
              variant="outline"
              onClick={() => {
                setRestorable(null);
                try {
                  window.localStorage.removeItem(draftKey(id));
                } catch {
                  // ignore
                }
              }}
            >
              {e.autosaveDiscard}
            </Button>
          </div>
        </div>
      )}

      {state === "live" && canManage && <p className="rounded-lg border border-emerald-200 bg-emerald-50 px-4 py-2 text-xs text-emerald-800">{e.liveEditNote}</p>}

      <Tabs value={tab} onValueChange={setTab}>
        <TabsList>
          <TabsTrigger value="editor">
            <Pencil className="mr-1.5 h-3.5 w-3.5" />
            {e.tabEditor}
          </TabsTrigger>
          <TabsTrigger value="stats" disabled={!statsAvailable}>
            <BarChart3 className="mr-1.5 h-3.5 w-3.5" />
            {t.announcements.stats.title}
          </TabsTrigger>
        </TabsList>

        <TabsContent value="editor" className="mt-4">
          <div className="grid items-start gap-5 lg:grid-cols-[minmax(0,1fr)_420px]">
            <div className="space-y-5">
              <FormatSection {...sectionProps} />
              <ContentSection {...sectionProps} />
              <PlacementSection
                {...sectionProps}
                exampleVehicles={exampleVehicles ?? []}
                exampleVehicleId={exampleVehicleId}
                onExampleVehicle={setExampleVehicleId}
              />
              {spec.steps && <StepsSection {...sectionProps} activeStep={activeStep} onActiveStep={setActiveStep} />}
              <AudienceSection {...sectionProps} count={count} />
              <ScheduleSection {...sectionProps} announcementId={id} />
              <AdoptionSection {...sectionProps} />
            </div>

            <aside className="space-y-3 lg:sticky lg:top-4">
              <Tabs value={panel} onValueChange={setPanel}>
                <TabsList className="w-full">
                  <TabsTrigger value="simulation" className="flex-1">{t.announcements.panel.simulation}</TabsTrigger>
                  <TabsTrigger value="audience" className="flex-1">{t.announcements.panel.audience}</TabsTrigger>
                  <TabsTrigger value="history" className="flex-1">{t.announcements.panel.history}</TabsTrigger>
                </TabsList>
                <div className="mt-3 rounded-xl border bg-card p-4">
                  <TabsContent value="simulation" className="mt-0">
                    <AnnouncementSimulation
                      input={input}
                      catalogs={catalogs}
                      stepIndex={activeStep}
                      onStepIndexChange={setActiveStep}
                      onPickAnchor={
                        readOnly || spec.steps?.anchor === "none"
                          ? undefined
                          : (anchorKey) => {
                              const i = Math.min(activeStep, input.steps.length - 1);
                              update({ steps: input.steps.map((st, j) => (j === i ? { ...st, anchor_key: anchorKey } : st)) });
                            }
                      }
                    />
                  </TabsContent>
                  <TabsContent value="audience" className="mt-0">
                    <AudiencePanel announcementId={id} input={input} status={saved?.status ?? "draft"} catalogs={catalogs} count={count} />
                  </TabsContent>
                  <TabsContent value="history" className="mt-0">
                    <HistoryPanel announcementId={id} refreshKey={historyKey} />
                  </TabsContent>
                </div>
              </Tabs>
            </aside>
          </div>
        </TabsContent>

        <TabsContent value="stats" className="mt-4">
          {saved && <AnnouncementStats announcement={saved} />}
        </TabsContent>
      </Tabs>

      <PreviewDialog
        open={previewOpen}
        onOpenChange={setPreviewOpen}
        announcement={saved}
        dirty={dirty}
        catalogs={catalogs}
        exampleVehicles={exampleVehicles ?? []}
        exampleVehicleId={exampleVehicleId}
        onExampleVehicle={setExampleVehicleId}
      />
      <PublishDialog
        open={publishOpen && !!saved}
        onOpenChange={setPublishOpen}
        announcement={saved}
        input={input}
        count={count.count}
        onConfirm={publish}
        onFix={(fieldErrors) => {
          setPublishOpen(false);
          setErrors(fieldErrors);
          requestAnimationFrame(() =>
            document.querySelector('[aria-invalid="true"], [role="alert"]')?.scrollIntoView({ behavior: "smooth", block: "center" }),
          );
        }}
        publishing={publishing}
      />
      <AlertDialog open={!!audienceConfirm} onOpenChange={(open) => !open && setAudienceConfirm(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>{t.announcements.publish.audienceChangeTitle}</AlertDialogTitle>
            <AlertDialogDescription>
              {audienceConfirm && t.announcements.publish.audienceChange(audienceConfirm.before, audienceConfirm.after)}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>{t.announcements.confirm.cancel}</AlertDialogCancel>
            <AlertDialogAction
              onClick={() => {
                setAudienceConfirm(null);
                void persist();
              }}
            >
              {t.announcements.publish.audienceChangeConfirm}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
      {dialogs}
    </div>
  );
}

function BackLink({ dirty }: { dirty: boolean }) {
  const t = useT();
  return (
    <Link
      href={ROUTES.announcements}
      onClick={(ev) => {
        if (dirty && !window.confirm(t.announcements.editor.leaveConfirm)) ev.preventDefault();
      }}
      className="inline-flex items-center gap-1 text-xs font-medium text-muted-foreground hover:text-foreground"
    >
      <ArrowLeft className="h-3.5 w-3.5" />
      {t.announcements.actions.back}
    </Link>
  );
}
