'use client';

import { useCallback, useRef, useState } from 'react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';

interface ConfirmOptions {
  title: string;
  description?: React.ReactNode;
  confirmText?: string;
  cancelText?: string;
  /** danger 样式 — 红色 confirm 按钮 */
  danger?: boolean;
}

/**
 * useConfirm — shadcn AlertDialog 包装的 Promise<boolean> API。
 *
 *   const confirm = useConfirm();
 *   if (!(await confirm({ title: '确定?' }))) return;
 *
 * 返回 <ConfirmDialog/> 必须挂在组件树里(provider 就近即可)。
 */
export function useConfirm() {
  const [opts, setOpts] = useState<ConfirmOptions | null>(null);
  const [open, setOpen] = useState(false);
  const resolveRef = useRef<((v: boolean) => void) | null>(null);

  const confirm = useCallback((o: ConfirmOptions): Promise<boolean> => {
    setOpts(o);
    setOpen(true);
    return new Promise((resolve) => {
      resolveRef.current = resolve;
    });
  }, []);

  const onAction = () => {
    resolveRef.current?.(true);
    setOpen(false);
  };
  const onCancel = () => {
    resolveRef.current?.(false);
    setOpen(false);
  };

  const dialog = (
    <AlertDialog open={open} onOpenChange={(v) => (!v ? onCancel() : undefined)}>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>{opts?.title}</AlertDialogTitle>
          {opts?.description && <AlertDialogDescription asChild>
            <div>{opts.description}</div>
          </AlertDialogDescription>}
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel onClick={onCancel}>{opts?.cancelText ?? '取消'}</AlertDialogCancel>
          <AlertDialogAction
            onClick={onAction}
            className={opts?.danger ? 'bg-destructive text-destructive-foreground hover:bg-destructive/90' : ''}
          >
            {opts?.confirmText ?? '确定'}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );

  return { confirm, dialog };
}
