"use client";

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

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
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;
};

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 statusCounts = useMemo(
    () =>
      STATUS_ORDER.map((status) => ({
        status,
        label: t(`versionStatus.${status}`, { ns: "config" }),
        count: groupedVersions.get(status)?.length ?? 0,
      })),
    [groupedVersions, t],
  );

  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-2", className)}>
        <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">
          {selectedVersion ? (
            <>
              <span className="font-mono text-lg font-semibold leading-none tabular-nums text-foreground">
                v{selectedVersion.version_no}
              </span>
              <ConfigStatusBadge status={selectedVersion.status} />
              <span className="text-sm text-muted-foreground">#{selectedVersion.id}</span>
            </>
          ) : (
            <span className="text-sm text-muted-foreground">
              {loading
                ? t("versionSwitcher.loading", { ns: "config" })
                : t("versionSwitcher.noneSelected", { ns: "config" })}
            </span>
          )}
        </div>
        <Button
          type="button"
          variant="outline"
          disabled={loading || sortedVersions.length === 0}
          onClick={() => setSheetOpen(true)}
          className="shrink-0"
        >
          <Layers className="size-4" aria-hidden />
          {t("versionSwitcher.switch", { ns: "config" })}
        </Button>
      </div>

      <Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
        <SheetContent
          side="right"
          className="flex flex-col overflow-hidden border-l bg-background p-0 shadow-xl sm:max-w-[430px]"
        >
          <div className="border-b border-border/60 bg-card px-5 pb-4 pt-5">
            <SheetHeader className="space-y-2 text-left">
              <SheetTitle className="text-base font-semibold tracking-tight text-foreground">
                {resolvedSheetTitle}
              </SheetTitle>
              {resolvedSheetDescription ? (
                <SheetDescription className="max-w-[320px] text-sm leading-relaxed text-muted-foreground">
                  {resolvedSheetDescription}
                </SheetDescription>
              ) : null}
            </SheetHeader>
          </div>
          <div className="border-b border-border/60 bg-card px-4 py-3">
            <div className="flex flex-wrap gap-2">
              {statusCounts.map((s) => (
                <div
                  key={s.status}
                  className="inline-flex items-center gap-2 rounded-full border border-border/60 bg-muted/50 px-3 py-1.5 text-sm text-muted-foreground"
                >
                  <span className="font-medium text-foreground/80">{s.label}</span>
                  <span className="font-mono tabular-nums">{s.count}</span>
                </div>
              ))}
            </div>
          </div>
          <div className="flex-1 overflow-auto px-4 py-4">
            {sortedVersions.length === 0 ? (
              <div className="rounded-2xl border border-dashed border-border/60 bg-muted/30 p-5 text-center text-sm text-muted-foreground">
                {t("versionSwitcher.empty", { ns: "config" })}
              </div>
            ) : (
              STATUS_ORDER.map((status) => {
                const rows = groupedVersions.get(status) ?? [];
                if (rows.length === 0) {
                  return null;
                }
                return (
                  <section key={status} className="border-b border-border/60 pb-4 last:border-b-0 last:pb-0">
                    <div className="mb-2 flex items-center justify-between px-1">
                      <div className="flex items-center gap-2.5">
                        <div
                          className={cn(
                            "size-2.5 rounded-full",
                            status === "draft" && "bg-muted-foreground",
                            status === "active" && "bg-primary",
                            status === "archived" && "bg-border",
                          )}
                        />
                        <p className="text-base font-semibold text-foreground">
                          {t(`versionStatus.${status}`, { ns: "config" })}
                        </p>
                      </div>
                      <p className="rounded-full bg-muted px-2 py-0.5 text-sm font-medium tabular-nums text-muted-foreground">
                        {t("versionSwitcher.count", { ns: "config", count: rows.length })}
                      </p>
                    </div>
                    <div className="space-y-1.5">
                      {rows.map((v) => {
                        const isCurrent = selectedId === String(v.id);
                        return (
                          <div
                            key={v.id}
                            className={cn(
                              "group flex gap-3 rounded-xl border border-transparent px-2 py-3 transition-colors hover:bg-muted/30",
                              isCurrent && "border-border/60 bg-muted/20",
                            )}
                          >
                            <div
                              className={cn(
                                "mt-1 h-auto w-1 shrink-0 rounded-full bg-border",
                                v.status === "draft" && "bg-muted-foreground/60",
                                v.status === "active" && "bg-primary",
                                v.status === "archived" && "bg-muted-foreground/30",
                              )}
                            />
                            <div className="min-w-0 flex-1 space-y-2">
                              <div className="flex items-start justify-between gap-3">
                                <div className="min-w-0 space-y-1.5">
                                  <div className="flex flex-wrap items-center gap-2">
                                    <span className="font-mono text-lg font-semibold leading-none tabular-nums text-foreground">
                                      v{v.version_no}
                                    </span>
                                    <ConfigStatusBadge status={v.status} />
                                    <span className="rounded-full bg-muted px-2 py-0.5 text-sm font-medium tabular-nums text-muted-foreground">
                                      #{v.id}
                                    </span>
                                  </div>
                                  <p className="line-clamp-2 text-sm leading-relaxed text-muted-foreground">
                                    {t("versionSwitcher.effectiveAt", {
                                      ns: "config",
                                      value: v.effective_at ? formatDt(v.effective_at) : "—",
                                    })}
                                    {v.reason
                                      ? ` · ${t("versionSwitcher.note", {
                                          ns: "config",
                                          value: v.reason,
                                        })}`
                                      : ""}
                                  </p>
                                </div>
                                {isCurrent ? (
                                  <span className="shrink-0 rounded-full bg-primary px-2.5 py-1 text-sm font-medium text-primary-foreground">
                                    {t("versionSwitcher.current", { ns: "config" })}
                                  </span>
                                ) : null}
                              </div>
                              <div className="flex flex-wrap items-center gap-2">
                                <Button
                                  type="button"
                                  variant={isCurrent ? "secondary" : "outline"}
                                  size="sm"
                                  className={cn(
                                    "h-9 rounded-full px-3 text-sm",
                                    isCurrent && "bg-muted text-muted-foreground hover:bg-muted",
                                  )}
                                  onClick={() => switchTo(v.id)}
                                >
                                  {isCurrent
                                    ? t("versionSwitcher.selected", { ns: "config" })
                                    : t("versionSwitcher.view", { ns: "config" })}
                                </Button>
                                {onRollbackVersion && v.status !== "draft" ? (
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="sm"
                                    className="rounded-full text-sm text-muted-foreground hover:bg-muted hover:text-foreground"
                                    disabled={rollbackBusy}
                                    onClick={() => {
                                      onRollbackVersion(v);
                                      setSheetOpen(false);
                                    }}
                                  >
                                    {t("versionSwitcher.rollback", { ns: "config" })}
                                  </Button>
                                ) : null}
                                {onDeleteVersion && v.status !== "active" ? (
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="sm"
                                    className="rounded-full text-sm text-destructive hover:bg-destructive/10 hover:text-destructive"
                                    disabled={deletingId === v.id}
                                    onClick={() => setDeleteTarget(v)}
                                  >
                                    {t("versionSwitcher.delete", { ns: "config" })}
                                  </Button>
                                ) : null}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </section>
                );
              })
            )}
          </div>
        </SheetContent>
      </Sheet>

      <Dialog open={deleteTarget !== null} onOpenChange={(open) => !open && setDeleteTarget(null)}>
        <DialogContent>
          <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>
    </>
  );
}
