// app/rigs/RigsListClient.tsx
"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";

type RigRow = {
    id: number | string;
    name: string;
    rig_type_name?: string | null;
};

async function apiJson<T>(url: string, init?: RequestInit): Promise<T> {
    const res = await fetch(url, {
        ...init,
        headers: {
            Accept: "application/json",
            ...(init?.headers || {}),
        },
        credentials: "include",
        cache: "no-store",
    });

    const txt = await res.text().catch(() => "");
    if (res.ok) {
        try {
            return (txt ? JSON.parse(txt) : ({} as any)) as T;
        } catch {
            return {} as T;
        }
    }

    let body: any = null;
    try { body = txt ? JSON.parse(txt) : null; } catch {}
    const message = body?.error || body?.message || txt || `HTTP ${res.status} for ${url}`;

    // If unauthorized, send to sign-in (our flow always lands on /portal)
    if (res.status === 401 && typeof window !== "undefined") {
        window.location.assign("/auth/sign-in");
    }

    const err: any = new Error(message);
    err.status = res.status;
    err.body = body ?? txt;
    throw err;
}

export default function RigsListClient() {
    const { toast } = useToast();
    const [rigs, setRigs] = useState<RigRow[] | null>(null);
    const [loading, setLoading] = useState<boolean>(true);
    const [err, setErr] = useState<string | null>(null);
    const [deleting, setDeleting] = useState<Record<string | number, boolean>>({});

    useEffect(() => {
        (async () => {
            try {
                setLoading(true);
                setErr(null);
                const j = await apiJson<{ data: RigRow[] }>("/api/my/rigs");
                setRigs(j?.data ?? []);
            } catch (e: any) {
                setErr(e?.message || "Failed to load rigs");
            } finally {
                setLoading(false);
            }
        })();
    }, []);

    async function onDelete(id: string | number) {
        if (!confirm("Delete this rig?")) return;
        try {
            setDeleting((d) => ({ ...d, [id]: true }));
            await apiJson(`/api/my/rigs/${id}`, { method: "DELETE" });
            setRigs((prev) => (prev ? prev.filter((r) => r.id !== id) : prev));
            toast({ title: "Rig deleted" });
        } catch (e: any) {
            toast({
                title: "Delete failed",
                description: e?.message || "Could not delete rig.",
                variant: "destructive",
            });
        } finally {
            setDeleting((d) => {
                const copy = { ...d };
                delete copy[id];
                return copy;
            });
        }
    }

    if (loading) {
        return (
            <div className="rounded-md border p-4 text-sm opacity-70">
            Loading your rigs…
            </div>
        );
    }

    if (err) {
        return (
            <div className="rounded-md border border-red-300 bg-red-50 p-4 text-sm text-red-700">
            {err}
            </div>
        );
    }

    return (
        <div className="space-y-3">
        <div className="divide-y divide-border rounded-md border">
        {(!rigs || rigs.length === 0) && (
            <div className="p-4 text-sm opacity-70">No rigs yet.</div>
        )}

        {rigs?.map((r) => (
            <div key={r.id} className="flex items-center justify-between p-4">
            <div className="flex items-center gap-3">
            <div className="font-medium">{r.name}</div>
            {r.rig_type_name && (
                <Badge variant="secondary">{r.rig_type_name}</Badge>
            )}
            </div>

            <Button
            variant="destructive"
            size="sm"
            onClick={() => onDelete(r.id)}
            disabled={!!deleting[r.id]}
            >
            {deleting[r.id] ? "Deleting…" : "Delete"}
            </Button>
            </div>
        ))}
        </div>
        </div>
    );
}
