"use client";

import { useState } from "react";
import { Linkedin, Loader2 } from "lucide-react";

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

  const handleConnect = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetch("/api/linkedin/connect", { method: "POST" });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error ?? "Something went wrong");
        return;
      }
      window.location.href = data.url;
    } catch {
      setError("Failed to initiate connection. Please try again.");
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex flex-col gap-2">
      <button
        onClick={handleConnect}
        disabled={loading}
        className="inline-flex items-center gap-2 bg-[#0077B5] hover:bg-[#005983] text-white 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" />
        ) : (
          <Linkedin className="h-4 w-4" />
        )}
        {loading ? "Redirecting…" : "Connect LinkedIn"}
      </button>
      {error && <p className="text-xs text-destructive">{error}</p>}
    </div>
  );
}
