import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { create } from "zustand";
import { JSX } from "react";

// 🎯 Define types clearly
type AlertOptions = {
    title: string;
    description?: string;
    onConfirm?: () => void;
    onCancel?: () => void;
};

type AlertState = {
    open: boolean;
    title: string;
    description?: string;
    onConfirm?: () => void;
    onCancel?: () => void;
    show: (options: AlertOptions) => void;
    hide: () => void;
};

// 🧠 Zustand store
export const useAlertStore = create<AlertState>((set) => ({
    open: false,
    title: "",
    description: "",

    show: (options) =>
        set({
            open: true,
            ...options,
        }),

    hide: () =>
        set({
            open: false,
            title: "",
            description: "",
            onConfirm: undefined,
            onCancel: undefined,
        }),
}));

// 🧩 Component
export function Alert(): JSX.Element {
    const { open, title, description, hide, onConfirm, onCancel } = useAlertStore();

    return (
        <Dialog open={open} onOpenChange={hide}>
            <DialogContent>
                <DialogHeader>
                    <DialogTitle>{title}</DialogTitle>
                    {description && (
                        <DialogDescription>{description}</DialogDescription>
                    )}
                </DialogHeader>

                <DialogFooter>
                    <Button
                        variant="outline"
                        onClick={() => {
                            hide();
                            onCancel?.();
                        }}
                    >
                        Cancel
                    </Button>

                    <Button
                        onClick={() => {
                            hide();
                            onConfirm?.();
                        }}
                    >
                        OK
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    );
}