"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { Loader2, Unlink } from "lucide-react";

export function DisconnectLinkedInButton() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const router = useRouter();

  const handleDisconnect = async () => {
    if (!confirm("Are you sure you want to disconnect your LinkedIn account?")) return;
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/linkedin/disconnect", { method: "DELETE" });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Something went wrong");
        return;
      }
      router.refresh();
    } catch {
      setError("Failed to disconnect. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col gap-2">
      <button
        onClick={handleDisconnect}
        disabled={loading}
        className="inline-flex items-center gap-2 border border-destructive text-destructive hover:bg-destructive/10 px-4 py-2 rounded-md text-sm font-medium transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
      >
        {loading ? (
          <Loader2 className="h-4 w-4 animate-spin" />
        ) : (
          <Unlink className="h-4 w-4" />
        )}
        {loading ? "Disconnecting…" : "Disconnect"}
      </button>
      {error && <p className="text-xs text-destructive">{error}</p>}
    </div>
  );
}
