"use client";

import React, { createContext, useContext, useState, useRef, ReactNode } from 'react';
import ConfirmModal from '@/components/ConfirmModal';
import { CheckCircle2, AlertCircle, Info, X } from 'lucide-react';
import { clsx } from "clsx";

interface Toast {
    id: string;
    message: string;
    type: 'success' | 'error' | 'info';
}

interface UIContextType {
    confirm: (options: { title: string; message: string; type?: 'danger' | 'warning' | 'info' | 'success'; confirmLabel?: string; cancelLabel?: string }) => Promise<boolean>;
    alert: (options: { title: string; message: string; type?: 'info' | 'success' | 'error' | 'warning' }) => Promise<void>;
    toast: (message: string, type?: 'success' | 'error' | 'info') => void;
}

const UIContext = createContext<UIContextType | undefined>(undefined);

export function UIProvider({ children }: { children: ReactNode }) {
    const [confirmState, setConfirmState] = useState<{
        isOpen: boolean;
        title: string;
        message: string;
        type: 'danger' | 'warning' | 'info' | 'success';
        confirmLabel: string;
        cancelLabel: string;
        resolve: (value: boolean) => void;
    } | null>(null);

    const [toasts, setToasts] = useState<Toast[]>([]);

    const confirm = React.useCallback((options: { title: string; message: string; type?: 'danger' | 'warning' | 'info' | 'success'; confirmLabel?: string; cancelLabel?: string }) => {
        return new Promise<boolean>((resolve) => {
            setConfirmState({
                isOpen: true,
                title: options.title,
                message: options.message,
                type: options.type || 'warning',
                confirmLabel: options.confirmLabel || 'Confirm',
                cancelLabel: options.cancelLabel || 'Cancel',
                resolve
            });
        });
    }, []);

    const alert = React.useCallback((options: { title: string; message: string; type?: 'info' | 'success' | 'error' | 'warning' }) => {
        return new Promise<void>((resolve) => {
            setConfirmState({
                isOpen: true,
                title: options.title,
                message: options.message,
                type: (options.type === 'error' ? 'danger' : options.type) as any || 'info',
                confirmLabel: 'OK',
                cancelLabel: '',
                resolve: () => resolve()
            });
        });
    }, []);

    const toast = React.useCallback((message: string, type: 'success' | 'error' | 'info' = 'info') => {
        const id = Math.random().toString(36).substring(2, 9);
        setToasts(prev => [...prev, { id, message, type }]);
        setTimeout(() => {
            setToasts(prev => prev.filter(t => t.id !== id));
        }, 5000);
    }, []);

    const handleConfirm = () => {
        confirmState?.resolve(true);
        setConfirmState(prev => prev ? { ...prev, isOpen: false } : null);
    };

    const handleCancel = () => {
        confirmState?.resolve(false);
        setConfirmState(prev => prev ? { ...prev, isOpen: false } : null);
    };

    const removeToast = (id: string) => {
        setToasts(prev => prev.filter(t => t.id !== id));
    };

    return (
        <UIContext.Provider value={{ confirm, alert, toast }}>
            {children}

            {/* Global Confirm/Alert Modal */}
            {confirmState && (
                <ConfirmModal
                    isOpen={confirmState.isOpen}
                    title={confirmState.title}
                    message={confirmState.message}
                    type={confirmState.type}
                    confirmLabel={confirmState.confirmLabel}
                    cancelLabel={confirmState.cancelLabel || undefined}
                    onConfirm={handleConfirm}
                    onCancel={handleCancel}
                />
            )}

            {/* Global Toast Notification System */}
            <div className="fixed top-10 left-1/2 -translate-x-1/2 z-[9999] flex flex-col gap-3 pointer-events-none w-full max-w-sm items-center">
                {toasts.map(t => (
                    <div
                        key={t.id}
                        className={clsx(
                            "pointer-events-auto flex items-center gap-3 py-4 px-6 rounded-2xl border backdrop-blur-xl shadow-2xl animate-slide-in-right",
                            t.type === 'success' ? 'bg-emerald-500/10 border-emerald-500/20 text-emerald-400 ' :
                                t.type === 'error' ? 'bg-red-500/10 border-red-500/20 text-red-400 ' :
                                    'bg-cyan-500/10 border-cyan-500/20 text-cyan-400 '
                        )}
                    >
                        {t.type === 'success' ? <CheckCircle2 className="w-5 h-5 shrink-0" /> :
                            t.type === 'error' ? <AlertCircle className="w-5 h-5 shrink-0" /> :
                                <Info className="w-5 h-5 shrink-0" />
                        }
                        <p className="text-sm font-bold tracking-tight">{t.message}</p>
                        <button
                            onClick={() => removeToast(t.id)}
                            className="ml-2 p-1.5 hover:bg-white/10 rounded-lg transition-colors group"
                            aria-label="Close notification"
                        >
                            <X className="w-4 h-4 opacity-40 group-hover:opacity-100 transition-opacity" />
                        </button>
                    </div>
                ))}
            </div>
        </UIContext.Provider>
    );
}

export function useUI() {
    const context = useContext(UIContext);
    if (context === undefined) {
        throw new Error('useUI must be used within a UIProvider');
    }
    return context;
}
