import { supabase } from "@/auth/supabase";
import { useRouter } from "@tanstack/react-router";
import { useState } from "react";
import { Button } from "../ui/button";

export function DeletePlanButton({ planId, onDeleted }: { planId: string; onDeleted?: () => void }) {
  const [confirm, setConfirm] = useState(false)
  const [loading, setLoading] = useState(false)
  const router = useRouter()

  async function handleDelete() {
    setLoading(true)
    try {
      const { error, status, statusText} = await supabase.from("plan_estudios").delete().eq("id", planId)
      console.log({status, statusText});
      

      if (error) throw error
      setConfirm(false)
      if (onDeleted) onDeleted()
      router.navigate({ to: "/planes", search: { plan: '' } })
    } catch (e: any) {
      alert(e?.message || "Error al eliminar el plan")
    } finally {
      setLoading(false)
    }
  }

  return confirm ? (
    <div className="flex gap-2">
      <Button variant="outline" onClick={() => setConfirm(false)} disabled={loading}>Cancelar</Button>
      <Button variant="destructive" onClick={handleDelete} disabled={loading}>
        {loading ? "Eliminando…" : "Confirmar eliminación"}
      </Button>
    </div>
  ) : (
    <Button variant="outline" onClick={() => setConfirm(true)}>
      Eliminar plan
    </Button>
  )
}