'use client';

import { createContext, useContext, useState, useCallback, ReactNode } from 'react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { AlertCircle } from 'lucide-react';

interface ErrorAlertState {
  open: boolean;
  title: string;
  message: string;
}

interface ErrorAlertContextType {
  showErrorAlert: (message: string, title?: string) => void;
}

const ErrorAlertContext = createContext<ErrorAlertContextType | null>(null);

/**
 * 에러 알림 Context 사용 훅
 */
export function useErrorAlert() {
  const context = useContext(ErrorAlertContext);
  if (!context) {
    throw new Error('useErrorAlert must be used within ErrorAlertProvider');
  }
  return context;
}

interface ErrorAlertProviderProps {
  children: ReactNode;
}

/**
 * 에러 알림 Provider
 * ItemMasterDataManagement 컴포넌트에서 사용
 */
export function ErrorAlertProvider({ children }: ErrorAlertProviderProps) {
  const [errorAlert, setErrorAlert] = useState<ErrorAlertState>({
    open: false,
    title: '오류',
    message: '',
  });

  const showErrorAlert = useCallback((message: string, title: string = '오류') => {
    setErrorAlert({
      open: true,
      title,
      message,
    });
  }, []);

  const closeErrorAlert = useCallback(() => {
    setErrorAlert(prev => ({
      ...prev,
      open: false,
    }));
  }, []);

  return (
    <ErrorAlertContext.Provider value={{ showErrorAlert }}>
      {children}

      {/* 에러 알림 다이얼로그 */}
      <AlertDialog open={errorAlert.open} onOpenChange={(isOpen) => !isOpen && closeErrorAlert()}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="flex items-center gap-2 text-destructive">
              <AlertCircle className="h-5 w-5" />
              {errorAlert.title}
            </AlertDialogTitle>
            <AlertDialogDescription className="text-base text-foreground">
              {errorAlert.message}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogAction onClick={closeErrorAlert}>
              확인
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </ErrorAlertContext.Provider>
  );
}
