"use client";

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

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

  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. You can connect later in Settings.");
        return;
      }
      window.location.href = data.url;
    } catch {
      setError("Could not connect to LinkedIn. You can try later from Settings.");
    } finally {
      setLoading(false);
    }
  };

  const handleSkip = () => {
    router.push("/dashboard");
  };

  return (
    <div className="flex h-screen items-center justify-center bg-background text-foreground">
      <div className="w-full max-w-md p-8 bg-card rounded-lg border border-border shadow-sm">
        <div className="mb-6 text-center">
          <div className="flex justify-center mb-4">
            <div className="bg-[#0077B5]/10 rounded-full p-3">
              <Linkedin className="h-8 w-8 text-[#0077B5]" />
            </div>
          </div>
          <h1 className="text-2xl font-semibold mb-2">Connect LinkedIn</h1>
          <p className="text-sm text-muted-foreground">
            Connect your LinkedIn account to start automated outreach campaigns. You
            can also do this later from your Settings.
          </p>
        </div>

        <div className="space-y-3">
          <button
            onClick={handleConnect}
            disabled={loading}
            className="w-full inline-flex items-center justify-center gap-2 bg-[#0077B5] hover:bg-[#005983] text-white py-2.5 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 to LinkedIn…" : "Connect LinkedIn Account"}
          </button>

          <button
            onClick={handleSkip}
            disabled={loading}
            className="w-full inline-flex items-center justify-center gap-2 text-muted-foreground hover:text-foreground text-sm transition-colors py-2"
          >
            Skip for now
            <ArrowRight className="h-4 w-4" />
          </button>
        </div>

        {error && (
          <p className="mt-4 text-xs text-destructive text-center">{error}</p>
        )}
      </div>
    </div>
  );
}
