"use client";

import { useState, useCallback } from "react";
import type { AlertOptions, AlertState } from "@/types/cash-charge";
import AlertModal from "./AlertModal";

export function useAlert() {
    const [alertState, setAlertState] = useState<AlertState>({
        isOpen: false,
        message: "",
        type: "info",
    });

    const showAlert = useCallback((options: AlertOptions) => {
        setAlertState({
            ...options,
            isOpen: true,
        });
    }, []);

    const hideAlert = useCallback(() => {
        setAlertState(prev => ({ ...prev, isOpen: false }));
    }, []);

    const alert = useCallback(
        (message: string, type: AlertOptions["type"] = "info") => {
            showAlert({ message, type });
        },
        [showAlert]
    );

    const confirm = useCallback(
        (message: string, onConfirm?: () => void, onCancel?: () => void) => {
            return new Promise<boolean>(resolve => {
                showAlert({
                    message,
                    type: "warning",
                    showCancel: true,
                    onConfirm: () => {
                        if (onConfirm) onConfirm();
                        resolve(true);
                        hideAlert();
                    },
                    onCancel: () => {
                        if (onCancel) onCancel();
                        resolve(false);
                        hideAlert();
                    },
                });
            });
        },
        [showAlert, hideAlert]
    );

    return {
        alertState,
        showAlert,
        hideAlert,
        alert,
        confirm,
    };
}

interface AlertSystemProps {
    alertState: AlertState;
    onHideAlert: () => void;
}

export function AlertSystem({ alertState, onHideAlert }: AlertSystemProps) {
    return (
        <AlertModal
            isOpen={alertState.isOpen}
            onClose={onHideAlert}
            title={alertState.title}
            message={alertState.message}
            type={alertState.type}
            confirmText={alertState.confirmText}
            showCancel={alertState.showCancel}
            cancelText={alertState.cancelText}
            onConfirm={alertState.onConfirm}
            onCancel={alertState.onCancel}
        />
    );
}