"use client";

import { AlertCircle, AlertTriangle, CheckCircle2, Info } from "lucide-react";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { useGlobalAlertStore } from "@/features/layout/stores/use-global-alert-store";
import { cn } from "@/lib/utils";

export function GlobalAlertModal() {
  const {
    isOpen,
    type,
    title,
    message,
    confirmLabel,
    cancelLabel,
    onConfirm,
    onCancel,
    isSingleButton,
    closeAlert,
  } = useGlobalAlertStore();

  const handleOpenChange = (open: boolean) => {
    if (!open) {
      closeAlert();
    }
  };

  const handleConfirm = () => {
    onConfirm?.();
    closeAlert();
  };

  const handleCancel = () => {
    onCancel?.();
    closeAlert();
  };

  const Icon = {
    success: CheckCircle2,
    error: AlertCircle,
    warning: AlertTriangle,
    info: Info,
  }[type];

  const iconColor = {
    success: "text-emerald-500",
    error: "text-red-500",
    warning: "text-amber-500",
    info: "text-blue-500",
  }[type];

  const bgColor = {
    success: "bg-emerald-50 dark:bg-emerald-950/20",
    error: "bg-red-50 dark:bg-red-950/20",
    warning: "bg-amber-50 dark:bg-amber-950/20",
    info: "bg-blue-50 dark:bg-blue-950/20",
  }[type];

  return (
    <AlertDialog open={isOpen} onOpenChange={handleOpenChange}>
      <AlertDialogContent className="sm:max-w-[400px]">
        <AlertDialogHeader>
          <div className="flex flex-col items-center gap-4 text-center sm:flex-row sm:text-left">
            <div
              className={cn(
                "flex h-12 w-12 shrink-0 items-center justify-center rounded-full",
                bgColor,
                iconColor,
              )}
            >
              <Icon className="h-6 w-6" />
            </div>
            <div className="flex-1 space-y-2">
              <AlertDialogTitle>{title}</AlertDialogTitle>
              <AlertDialogDescription className="text-sm leading-relaxed">
                {message}
              </AlertDialogDescription>
            </div>
          </div>
        </AlertDialogHeader>
        <AlertDialogFooter className="mt-4 sm:justify-end">
          {!isSingleButton && (
            <AlertDialogCancel onClick={handleCancel} className="mt-2 sm:mt-0">
              {cancelLabel || "취소"}
            </AlertDialogCancel>
          )}
          <AlertDialogAction
            onClick={handleConfirm}
            className={cn(
              type === "error" && "bg-red-600 hover:bg-red-700",
              type === "warning" && "bg-amber-600 hover:bg-amber-700",
              type === "success" && "bg-emerald-600 hover:bg-emerald-700",
            )}
          >
            {confirmLabel || "확인"}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}
