import { useCallback, useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { LogOut, RotateCcw } from "lucide-react";

/**
 * Notice-to-Vacate toggle for an RV/Boat lot rental linked to an owner or unit.
 * Renders nothing if there's no active/vacating rental for the given owner/unit.
 * Toggles the rental status between "active" (renting) and "vacating".
 */
export default function RvRentalVacateButton({ ownerId, unitId }: { ownerId?: string; unitId?: string }) {
  const [rental, setRental] = useState<any>(null);
  const [saving, setSaving] = useState(false);

  const fetchRental = useCallback(async () => {
    if (!ownerId && !unitId) { setRental(null); return; }
    let q = supabase
      .from("rv_boat_lot_rentals")
      .select("id, status, renter_name")
      .in("status", ["active", "vacating"]);
    q = ownerId ? q.eq("owner_id", ownerId) : q.eq("unit_id", unitId!);
    const { data } = await q.order("start_date", { ascending: false }).limit(1);
    setRental(data?.[0] || null);
  }, [ownerId, unitId]);

  useEffect(() => { fetchRental(); }, [fetchRental]);

  if (!rental) return null;
  const isVacating = rental.status === "vacating";

  const toggle = async () => {
    setSaving(true);
    const next = isVacating ? "active" : "vacating";
    const { error } = await supabase.from("rv_boat_lot_rentals").update({ status: next }).eq("id", rental.id);
    setSaving(false);
    if (error) { toast.error(error.message); return; }
    toast.success(isVacating ? "Marked as renting" : "Notice to vacate recorded");
    fetchRental();
  };

  return (
    <Button variant={isVacating ? "outline" : "destructive"} size="sm" className="gap-1.5" disabled={saving} onClick={toggle}>
      {isVacating ? <RotateCcw className="h-3.5 w-3.5" /> : <LogOut className="h-3.5 w-3.5" />}
      {isVacating ? "Mark Renting" : "Notice to Vacate"}
    </Button>
  );
}
