"use client";

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

import { AdminNoResourceState } from "@/components/admin/admin-no-resource-state";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
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";

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;
};

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

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

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

  function switchTo(id: number) {
    onSelectedIdChange(String(id));
    setOpen(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);
    }
  }

  const triggerLabel = loading
    ? t("versionSwitcher.loading", { ns: "config" })
    : selectedVersion
      ? `v${selectedVersion.version_no}`
      : t("versionSwitcher.noneSelected", { ns: "config" });

  return (
    <>
      <Popover open={open} onOpenChange={setOpen}>
        <PopoverTrigger
          disabled={loading || sortedVersions.length === 0}
          className={cn(
            "inline-flex h-9 min-w-[10rem] max-w-full items-center justify-between gap-2 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none transition-colors hover:bg-muted/40 disabled:cursor-not-allowed disabled:opacity-50",
            className,
          )}
        >
          <span className="flex min-w-0 items-center gap-2">
            <span className="truncate font-mono tabular-nums">{triggerLabel}</span>
            {selectedVersion ? (
              <ConfigStatusBadge status={selectedVersion.status} className="h-5 shrink-0 px-1.5 text-[11px]" />
            ) : null}
          </span>
          <ChevronDown className="size-4 shrink-0 text-muted-foreground" aria-hidden />
        </PopoverTrigger>

        <PopoverContent align="start" className="w-[min(20rem,calc(100vw-2rem))] p-0">
          <div className="border-b border-border/60 px-3 py-2 text-sm font-medium">{resolvedTitle}</div>
          <ScrollArea className="max-h-72">
            {sortedVersions.length === 0 ? (
              <AdminNoResourceState compact className="px-3 py-6" />
            ) : (
              <ul className="p-1">
                {sortedVersions.map((v) => {
                  const isCurrent = selectedId === String(v.id);
                  const secondary =
                    v.status === "active" && v.effective_at ? formatDt(v.effective_at) : null;
                  const showMenu =
                    (onDeleteVersion && v.status !== "active") ||
                    (onRollbackVersion && v.status !== "draft");

                  return (
                    <li key={v.id} className="flex items-center gap-0.5">
                      <button
                        type="button"
                        className={cn(
                          "flex min-w-0 flex-1 items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm transition-colors",
                          isCurrent ? "bg-muted" : "hover:bg-muted/60",
                        )}
                        onClick={() => switchTo(v.id)}
                      >
                        <span className="font-mono tabular-nums">v{v.version_no}</span>
                        <ConfigStatusBadge status={v.status} className="h-5 px-1.5 text-[11px]" />
                        {secondary ? (
                          <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
                            {secondary}
                          </span>
                        ) : (
                          <span className="flex-1" />
                        )}
                        {isCurrent ? <Check className="size-4 shrink-0 text-foreground" aria-hidden /> : null}
                      </button>

                      {showMenu ? (
                        <DropdownMenu>
                          <DropdownMenuTrigger
                            className="inline-flex size-8 shrink-0 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-muted hover:text-foreground"
                            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-32">
                            {onRollbackVersion && v.status !== "draft" ? (
                              <DropdownMenuItem
                                disabled={rollbackBusy}
                                onClick={() => {
                                  onRollbackVersion(v);
                                  setOpen(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>
                      ) : null}
                    </li>
                  );
                })}
              </ul>
            )}
          </ScrollArea>
        </PopoverContent>
      </Popover>

      <Dialog open={deleteTarget !== null} onOpenChange={(openState) => !openState && setDeleteTarget(null)}>
        <DialogContent showCloseButton className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>{t("versionSwitcher.deleteConfirmTitle", { ns: "config" })}</DialogTitle>
            <DialogDescription>
              {t("versionSwitcher.deleteConfirmDescription", {
                ns: "config",
                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>
    </>
  );
}