import { supabase } from "@/auth/supabase";
import { useQueryClient } from "@tanstack/react-query";
import { useRouter } from "@tanstack/react-router";
import { useState } from "react";
import { Button } from "../ui/button";
import { carrerasKeys } from "@/routes/_authenticated/carreras";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from "../ui/dialog";

export function useDeleteCarreraDialog(carreraId: string, onDeleted?: () => void) {
    const [open, setOpen] = useState(false)
    const [loading, setLoading] = useState(false)
    const qc = useQueryClient()
    const router = useRouter()

    async function handleDelete() {
        setLoading(true)
        try {
            const { error } = await supabase.from("carreras").delete().eq("id", carreraId)
            if (error) throw error
            setOpen(false)
            if (onDeleted) onDeleted()
            await qc.invalidateQueries({ queryKey: carrerasKeys.root })
            router.invalidate()
        } catch (e: any) {
            alert(e?.message || "Error al eliminar la carrera")
        } finally {
            setLoading(false)
        }
    }

    const dialog = (
        <Dialog open={open} onOpenChange={setOpen}>
            <DialogContent className="bg-white">
                <DialogHeader>
                    <DialogTitle className="font-mono" >¿Eliminar carrera?</DialogTitle>
                    <DialogDescription>
                        Esta acción no se puede deshacer. ¿Seguro que quieres eliminar esta carrera?
                    </DialogDescription>
                </DialogHeader>
                <DialogFooter>
                    <Button variant="outline" onClick={() => setOpen(false)} disabled={loading}>
                        Cancelar
                    </Button>
                    <Button variant="destructive" onClick={handleDelete} disabled={loading}>
                        {loading ? "Eliminando…" : "Eliminar"}
                    </Button>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    )

    return { open, setOpen, dialog }
}