"use client";

import { useMemo, useState } from "react";
import { Check, ChevronRight, Layers, MoreHorizontal } from "lucide-react";
import { useTranslation } from "react-i18next";

import { Button } from "@/components/ui/button";
import { AdminNoResourceState, AdminTableNoResourceRow } from "@/components/admin/admin-no-resource-state";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Sheet,
  SheetContent,
  SheetDescription,
  SheetHeader,
  SheetTitle,
} from "@/components/ui/sheet";
import { cn } from "@/lib/utils";
import { ConfigStatusBadge } from "@/modules/config/config-status-badge";
import { useAdminDateTimeFormatter } from "@/hooks/use-admin-datetime-formatter";
import type { ConfigVersionSummary } from "@/types/api/admin-config";

const STATUS_ORDER = ["draft", "active", "archived"] as const;

export type ConfigVersionSwitcherProps = {
  versions: ConfigVersionSummary[];
  selectedId: string;
  onSelectedIdChange: (id: string) => void;
  loading?: boolean;
  label?: string;
  sheetTitle?: string;
  sheetDescription?: string;
  className?: string;
  onDeleteVersion?: (row: ConfigVersionSummary) => Promise<void>;
  onRollbackVersion?: (row: ConfigVersionSummary) => void;
  rollbackBusy?: boolean;
};

function formatVersionNote(
  reason: string | null | undefined,
  formatDt: (iso: string | null | undefined) => string,
): string | null {
  if (!reason?.trim()) {
    return null;
  }
  const trimmed = reason.trim();
  const isoMatch = trimmed.match(/\d{4}-\d{2}-\d{2}T[\d:.]+Z?/);
  if (trimmed.startsWith("draft") && isoMatch) {
    return formatDt(isoMatch[0]);
  }
  if (trimmed.startsWith("seed:")) {
    return trimmed.slice(5);
  }
  if (trimmed.length > 56) {
    return `${trimmed.slice(0, 56)}…`;
  }
  return trimmed;
}

export function ConfigVersionSwitcher({
  versions,
  selectedId,
  onSelectedIdChange,
  loading = false,
  sheetTitle,
  sheetDescription,
  className,
  onDeleteVersion,
  onRollbackVersion,
  rollbackBusy = false,
}: ConfigVersionSwitcherProps) {
  const { t } = useTranslation(["config", "adminUsers"]);
  const formatDt = useAdminDateTimeFormatter();
  const [sheetOpen, setSheetOpen] = useState(false);
  const [deleteTarget, setDeleteTarget] = useState<ConfigVersionSummary | null>(null);
  const [deletingId, setDeletingId] = useState<number | null>(null);
  const resolvedSheetTitle = sheetTitle ?? t("versionSwitcher.sheetTitle", { ns: "config" });
  const resolvedSheetDescription =
    sheetDescription ?? t("versionSwitcher.sheetDescription", { ns: "config" });

  const sortedVersions = useMemo(
    () => [...versions].sort((a, b) => b.id - a.id),
    [versions],
  );

  const groupedVersions = useMemo(() => {
    const groups = new Map<string, ConfigVersionSummary[]>();
    for (const status of STATUS_ORDER) {
      groups.set(status, []);
    }
    for (const v of sortedVersions) {
      const list = groups.get(v.status) ?? [];
      list.push(v);
      groups.set(v.status, list);
    }
    return groups;
  }, [sortedVersions]);

  const selectedVersion = useMemo(
    () => sortedVersions.find((v) => String(v.id) === selectedId) ?? null,
    [selectedId, sortedVersions],
  );

  const visibleSections = useMemo(
    () =>
      STATUS_ORDER.map((status) => ({
        status,
        rows: groupedVersions.get(status) ?? [],
      })).filter((section) => section.rows.length > 0),
    [groupedVersions],
  );

  function switchTo(id: number) {
    onSelectedIdChange(String(id));
    setSheetOpen(false);
  }

  async function confirmDelete() {
    if (!deleteTarget || !onDeleteVersion) {
      return;
    }
    setDeletingId(deleteTarget.id);
    try {
      await onDeleteVersion(deleteTarget);
      if (selectedId === String(deleteTarget.id)) {
        onSelectedIdChange("");
      }
      setDeleteTarget(null);
    } finally {
      setDeletingId(null);
    }
  }

  return (
    <>
      <div className={cn("flex min-w-0 items-center gap-3", className)}>
        <div className="flex min-w-0 flex-1 items-center gap-2">
          {selectedVersion ? (
            <>
              <span className="font-mono text-base font-semibold tabular-nums text-foreground">
                v{selectedVersion.version_no}
              </span>
              <ConfigStatusBadge status={selectedVersion.status} className="h-5 px-1.5 text-[11px]" />
            </>
          ) : (
            <span className="text-sm text-muted-foreground">
              {loading
                ? t("versionSwitcher.loading", { ns: "config" })
                : t("versionSwitcher.noneSelected", { ns: "config" })}
            </span>
          )}
        </div>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          disabled={loading || sortedVersions.length === 0}
          onClick={() => setSheetOpen(true)}
          className="h-8 shrink-0 gap-1.5 text-muted-foreground hover:text-foreground"
        >
          <Layers className="size-3.5" aria-hidden />
          {t("versionSwitcher.switch", { ns: "config" })}
        </Button>
      </div>

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent
          side="right"
          className="flex w-full flex-col gap-0 overflow-hidden border-l bg-background p-0 sm:max-w-md"
        >
          <SheetHeader className="space-y-1 border-b border-border/60 px-5 py-4 text-left">
            <SheetTitle className="text-[15px] font-semibold tracking-tight">
              {resolvedSheetTitle}
            </SheetTitle>
            {resolvedSheetDescription ? (
              <SheetDescription className="text-[13px] leading-relaxed">
                {resolvedSheetDescription}
              </SheetDescription>
            ) : null}
          </SheetHeader>

          <div className="flex-1 overflow-y-auto px-3 py-3">
            {sortedVersions.length === 0 ? (
              <AdminNoResourceState compact className="px-2 py-8" />
            ) : (
              <div className="space-y-5">
                {visibleSections.map((section) => (
                  <section key={section.status}>
                    <p className="mb-2 px-2 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">
                      {t(`versionStatus.${section.status}`, { ns: "config" })}
                    </p>
                    <ul className="space-y-1">
                      {section.rows.map((v) => {
                        const isCurrent = selectedId === String(v.id);
                        const note = formatVersionNote(v.reason, formatDt);
                        const effectiveLabel = v.effective_at
                          ? formatDt(v.effective_at)
                          : null;
                        const meta = [effectiveLabel, note].filter(Boolean).join(" · ");
                        const showMenu =
                          (onDeleteVersion && v.status !== "active") ||
                          (onRollbackVersion && v.status !== "draft");

                        return (
                          <li key={v.id}>
                            <div
                              className={cn(
                                "group flex items-stretch gap-0.5 rounded-lg border transition-colors",
                                isCurrent
                                  ? "border-primary/40 bg-primary/[0.04]"
                                  : "border-transparent hover:border-border/60 hover:bg-muted/30",
                              )}
                            >
                              <button
                                type="button"
                                className="flex min-w-0 flex-1 items-center gap-3 px-3 py-2.5 text-left"
                                onClick={() => switchTo(v.id)}
                              >
                                <div className="min-w-0 flex-1">
                                  <div className="flex items-center gap-2">
                                    <span className="font-mono text-[15px] font-semibold tabular-nums text-foreground">
                                      v{v.version_no}
                                    </span>
                                    <ConfigStatusBadge
                                      status={v.status}
                                      className="h-5 px-1.5 text-[11px]"
                                    />
                                  </div>
                                  {meta ? (
                                    <p className="mt-0.5 truncate text-xs text-muted-foreground">
                                      {meta}
                                    </p>
                                  ) : null}
                                </div>
                                {isCurrent ? (
                                  <span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground">
                                    <Check className="size-3.5" strokeWidth={2.5} aria-hidden />
                                    <span className="sr-only">
                                      {t("versionSwitcher.current", { ns: "config" })}
                                    </span>
                                  </span>
                                ) : (
                                  <ChevronRight
                                    className="size-4 shrink-0 text-muted-foreground/50 group-hover:text-muted-foreground"
                                    aria-hidden
                                  />
                                )}
                              </button>

                              {showMenu ? (
                                <div className="flex shrink-0 items-center pr-1">
                                  <DropdownMenu>
                                    <DropdownMenuTrigger
                                      className="inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground opacity-0 outline-none transition-opacity hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100 data-popup-open:opacity-100"
                                      aria-label={t("versionSwitcher.moreActions", {
                                        ns: "config",
                                        version: v.version_no,
                                      })}
                                      onClick={(e) => e.stopPropagation()}
                                    >
                                      <MoreHorizontal className="size-4" />
                                    </DropdownMenuTrigger>
                                    <DropdownMenuContent align="end" className="min-w-36">
                                      {onRollbackVersion && v.status !== "draft" ? (
                                        <DropdownMenuItem
                                          disabled={rollbackBusy}
                                          onClick={() => {
                                            onRollbackVersion(v);
                                            setSheetOpen(false);
                                          }}
                                        >
                                          {t("versionSwitcher.rollback", { ns: "config" })}
                                        </DropdownMenuItem>
                                      ) : null}
                                      {onDeleteVersion && v.status !== "active" ? (
                                        <DropdownMenuItem
                                          variant="destructive"
                                          disabled={deletingId === v.id}
                                          onClick={() => setDeleteTarget(v)}
                                        >
                                          {t("versionSwitcher.delete", { ns: "config" })}
                                        </DropdownMenuItem>
                                      ) : null}
                                    </DropdownMenuContent>
                                  </DropdownMenu>
                                </div>
                              ) : null}
                            </div>
                          </li>
                        );
                      })}
                    </ul>
                  </section>
                ))}
              </div>
            )}
          </div>
        </SheetContent>
      </Sheet>

      <Dialog open={deleteTarget !== null} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <DialogContent showCloseButton className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{t("versionSwitcher.deleteConfirmTitle", { ns: "config" })}</DialogTitle>
            <DialogDescription>
              {t("versionSwitcher.deleteConfirmDescription", {
                ns: "config",
                id: deleteTarget?.id,
                version: deleteTarget?.version_no,
              })}
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button type="button" variant="outline" onClick={() => setDeleteTarget(null)}>
              {t("actions.cancel", { ns: "adminUsers" })}
            </Button>
            <Button
              type="button"
              variant="destructive"
              disabled={deletingId !== null}
              onClick={() => void confirmDelete()}
            >
              {t("versionSwitcher.delete", { ns: "config" })}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}
