"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { toast } from "sonner"
import { Pencil, Ban, Trash2 } from "lucide-react"
import { ConfirmModal } from "@/components/ui/confirm-modal"

type Action = "terminate" | "delete" | null

export function LeaseActions({ lease }: { lease: any }) {
  const router = useRouter()
  const [pending, setPending] = useState<Action>(null)
  const [loading, setLoading] = useState(false)

  async function handleTerminate() {
    setLoading(true)
    try {
      const res = await fetch(`/api/leases/${lease.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status: "terminated" }),
      })
      const data = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(typeof data?.error === "string" ? data.error : "Could not terminate lease")
        return
      }
      toast.success("Lease terminated")
      setPending(null)
      router.refresh()
    } catch {
      toast.error("Something went wrong")
    } finally {
      setLoading(false)
    }
  }

  async function handleDelete() {
    setLoading(true)
    try {
      const res = await fetch(`/api/leases/${lease.id}`, { method: "DELETE" })
      const data = await res.json().catch(() => ({}))
      if (!res.ok) {
        toast.error(typeof data?.error === "string" ? data.error : "Could not delete lease")
        return
      }
      toast.success("Lease deleted")
      setPending(null)
      router.push("/leases")
      router.refresh()
    } catch {
      toast.error("Something went wrong")
    } finally {
      setLoading(false)
    }
  }

  return (
    <>
      <div className="flex items-center gap-2">
        <Link
          href={`/leases/${lease.id}/edit`}
          className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2 text-sm text-white/60 transition hover:border-white/20 hover:text-white"
        >
          <Pencil className="h-3.5 w-3.5" />
          Edit
        </Link>
        {lease.status !== "terminated" && (
          <button
            onClick={() => setPending("terminate")}
            className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2 text-sm text-amber-400/80 transition hover:border-amber-500/30 hover:text-amber-400"
          >
            <Ban className="h-3.5 w-3.5" />
            Terminate
          </button>
        )}
        <button
          onClick={() => setPending("delete")}
          className="flex items-center gap-1.5 rounded-lg border border-white/10 px-3 py-2 text-sm text-white/40 transition hover:border-red-500/30 hover:text-red-400"
        >
          <Trash2 className="h-3.5 w-3.5" />
          Delete
        </button>
      </div>

      <ConfirmModal
        open={pending === "terminate"}
        variant="warning"
        title="Terminate this lease?"
        description="The lease will be marked as terminated. You can still view it afterwards."
        confirmLabel="Terminate"
        loading={loading}
        onConfirm={handleTerminate}
        onCancel={() => !loading && setPending(null)}
      />

      <ConfirmModal
        open={pending === "delete"}
        variant="danger"
        title="Delete this lease?"
        description="This permanently removes the lease record. This action cannot be undone."
        confirmLabel="Delete"
        loading={loading}
        onConfirm={handleDelete}
        onCancel={() => !loading && setPending(null)}
      />
    </>
  )
}
