"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import { CheckCircle2, ExternalLink, Landmark, Loader2, RefreshCw, Unplug } from "lucide-react";
import type { Business, SamGovIntegration } from "@/lib/types";
import { applyLiveBidsToBusiness, fetchLiveFederalBids } from "@/lib/federal-work/fetch-live-bids";
import { isSamGovConnected, maskSamApiKey } from "@/lib/integrations/sam-gov";
import { saveBusiness } from "@/lib/data-store";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";

interface SamGovIntegrationCardProps {
  business: Business;
  onUpdate: (business: Business) => void;
  /** Auto-fetch bids immediately after successful connect */
  autoFetchOnConnect?: boolean;
  variant?: "settings" | "onboarding";
}

export function SamGovIntegrationCard({
  business,
  onUpdate,
  autoFetchOnConnect = true,
  variant = "settings",
}: SamGovIntegrationCardProps) {
  const existing = business.integrations?.samGov;
  const [apiKey, setApiKey] = useState("");
  const [uei, setUei] = useState(existing?.uei ?? "");
  const [autoFetch, setAutoFetch] = useState(existing?.autoFetchLiveBids ?? true);
  const [connecting, setConnecting] = useState(false);
  const [fetching, setFetching] = useState(false);
  const [message, setMessage] = useState<{ type: "ok" | "error"; text: string } | null>(null);

  useEffect(() => {
    if (existing?.uei) setUei(existing.uei);
    if (existing?.autoFetchLiveBids !== undefined) setAutoFetch(existing.autoFetchLiveBids);
  }, [existing?.uei, existing?.autoFetchLiveBids]);

  const connected = isSamGovConnected(existing);

  const connectAndMaybeFetch = async () => {
    const key = apiKey.trim() || existing?.apiKey || "";
    if (!key) {
      setMessage({ type: "error", text: "Paste your SAM.gov public API key first." });
      return;
    }

    setConnecting(true);
    setMessage(null);

    try {
      const testRes = await fetch("/api/integrations/sam-gov/test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ apiKey: key, uei: uei.trim() || undefined }),
      });
      const testData = (await testRes.json()) as { ok?: boolean; error?: string };

      if (!testRes.ok || !testData.ok) {
        const failed: Business = {
          ...business,
          integrations: {
            ...business.integrations,
            samGov: {
              apiKey: key,
              uei: uei.trim() || undefined,
              status: "error",
              autoFetchLiveBids: autoFetch,
              lastError: testData.error,
            },
          },
          updatedAt: new Date().toISOString(),
        };
        onUpdate(failed);
        await saveBusiness(failed);
        setMessage({ type: "error", text: testData.error ?? "SAM.gov connection failed." });
        return;
      }

      const samGov: SamGovIntegration = {
        apiKey: key,
        uei: uei.trim() || undefined,
        status: "connected",
        autoFetchLiveBids: autoFetch,
        connectedAt: new Date().toISOString(),
      };

      let next: Business = {
        ...business,
        integrations: { ...business.integrations, samGov },
        updatedAt: new Date().toISOString(),
      };

      if (autoFetchOnConnect && autoFetch) {
        setFetching(true);
        const bidData = await fetchLiveFederalBids(next, { apiKey: key });
        setFetching(false);

        if (bidData.ok && bidData.opportunities) {
          next = applyLiveBidsToBusiness(next, bidData.opportunities, {
            imported: bidData.imported,
            naicsCodes: bidData.naicsCodes,
          });
          setMessage({
            type: "ok",
            text: `Connected to SAM.gov and imported ${bidData.imported ?? 0} live federal bid${(bidData.imported ?? 0) === 1 ? "" : "s"}.`,
          });
        } else {
          setMessage({
            type: "ok",
            text: "SAM.gov connected. Could not auto-fetch bids yet — use Fetch live bids below.",
          });
        }
      } else {
        setMessage({ type: "ok", text: "SAM.gov connected. Live bid sync is enabled." });
      }

      onUpdate(next);
      await saveBusiness(next);
      setApiKey("");
    } catch {
      setMessage({ type: "error", text: "Network error — could not reach BrandLxft API." });
    } finally {
      setConnecting(false);
      setFetching(false);
    }
  };

  const fetchNow = async () => {
    setFetching(true);
    setMessage(null);
    try {
      const bidData = await fetchLiveFederalBids(business);
      if (!bidData.ok || !bidData.opportunities) {
        setMessage({
          type: "error",
          text: bidData.error ?? "Fetch failed.",
        });
        return;
      }
      const next = applyLiveBidsToBusiness(business, bidData.opportunities, {
        imported: bidData.imported,
      });
      onUpdate(next);
      await saveBusiness(next);
      setMessage({
        type: "ok",
        text: `Fetched ${bidData.imported ?? 0} live bid${(bidData.imported ?? 0) === 1 ? "" : "s"} from SAM.gov.`,
      });
    } catch {
      setMessage({ type: "error", text: "Could not fetch live bids." });
    } finally {
      setFetching(false);
    }
  };

  const disconnect = async () => {
    const next: Business = {
      ...business,
      integrations: { ...business.integrations, samGov: undefined },
      updatedAt: new Date().toISOString(),
    };
    onUpdate(next);
    await saveBusiness(next);
    setApiKey("");
    setMessage({ type: "ok", text: "SAM.gov disconnected." });
  };

  const busy = connecting || fetching;

  return (
    <Card
      id="sam-gov-api"
      className={`scroll-mt-6 ${variant === "onboarding" ? "border-emerald-500/30 bg-emerald-500/5" : "border-indigo-500/20"}`}
    >
      <CardHeader>
        <CardTitle className="flex flex-wrap items-center gap-2">
          <Landmark className="h-5 w-5 text-indigo-400" />
          SAM.gov — live federal bids
          {connected ? (
            <Badge className="border-emerald-500/30 bg-emerald-500/10 text-emerald-300">Connected</Badge>
          ) : (
            <Badge className="border-slate-700 bg-slate-800/50 text-slate-400">Not connected</Badge>
          )}
        </CardTitle>
        <p className="text-sm text-slate-400">
          Attach your SAM.gov account so BrandLxft automatically pulls open solicitations matched to your industry and
          location — no manual searching.
        </p>
      </CardHeader>
      <CardContent className="space-y-5">
        <div className="rounded-xl border border-slate-800 bg-slate-900/50 p-4">
          <p className="text-sm font-medium text-slate-200">How to connect (about 2 minutes)</p>
          <ol className="mt-3 list-decimal space-y-2 pl-5 text-sm text-slate-400">
            <li>
              Create a free account at{" "}
              <Link href="https://sam.gov" target="_blank" rel="noopener noreferrer" className="text-sky-400 hover:underline">
                sam.gov
              </Link>{" "}
              (or log in if you already registered your business).
            </li>
            <li>
              Go to <strong className="text-slate-300">Account Details → Public API Key</strong> and generate a key.
            </li>
            <li>Paste the key below and click Connect — BrandLxft will verify it and fetch live bids.</li>
            <li>
              Optional: add your <strong className="text-slate-300">UEI</strong> (Unique Entity ID) after entity
              registration so we can track your vendor profile.
            </li>
          </ol>
          <Link
            href="https://sam.gov/content/entity-registration"
            target="_blank"
            rel="noopener noreferrer"
            className="mt-3 inline-flex items-center gap-1 text-sm text-sky-400 hover:underline"
          >
            SAM.gov entity registration guide
            <ExternalLink className="h-3.5 w-3.5" />
          </Link>
        </div>

        <div className="grid gap-3 sm:grid-cols-2">
          <div className="sm:col-span-2">
            <label className="mb-1 block text-xs text-slate-500">SAM.gov public API key</label>
            <Input
              type="password"
              placeholder={existing?.apiKey ? maskSamApiKey(existing.apiKey) : "Paste your public API key"}
              value={apiKey}
              onChange={(e) => setApiKey(e.target.value)}
              autoComplete="off"
            />
          </div>
          <div className="sm:col-span-2">
            <label className="mb-1 block text-xs text-slate-500">UEI (optional — after SAM registration)</label>
            <Input
              placeholder="12-character Unique Entity ID"
              value={uei}
              onChange={(e) => setUei(e.target.value.toUpperCase())}
            />
          </div>
        </div>

        <label className="flex cursor-pointer items-start gap-3">
          <input
            type="checkbox"
            className="mt-1"
            checked={autoFetch}
            onChange={(e) => setAutoFetch(e.target.checked)}
          />
          <span className="text-sm text-slate-400">
            <span className="block font-medium text-slate-200">Auto-fetch live bids</span>
            Pull matched open solicitations whenever you connect and on manual refresh.
          </span>
        </label>

        {connected && existing ? (
          <div className="flex flex-wrap items-center gap-3 rounded-lg border border-emerald-500/20 bg-emerald-500/5 p-3 text-sm">
            <CheckCircle2 className="h-4 w-4 text-emerald-400" />
            <span className="text-slate-300">
              Live bid sync active
              {existing.lastFetchedAt
                ? ` · last fetch ${new Date(existing.lastFetchedAt).toLocaleString()} (${existing.lastFetchCount ?? 0} bids)`
                : ""}
            </span>
          </div>
        ) : null}

        {existing?.status === "error" && existing.lastError ? (
          <p className="text-sm text-red-400">{existing.lastError}</p>
        ) : null}

        {message ? (
          <p className={`text-sm ${message.type === "ok" ? "text-emerald-400" : "text-red-400"}`}>{message.text}</p>
        ) : null}

        <div className="flex flex-wrap gap-2">
          <Button type="button" className="gap-2" onClick={connectAndMaybeFetch} disabled={busy}>
            {busy ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                {fetching ? "Fetching live bids…" : "Connecting…"}
              </>
            ) : connected ? (
              "Update connection"
            ) : (
              "Connect SAM.gov & fetch bids"
            )}
          </Button>
          {connected ? (
            <>
              <Button type="button" variant="outline" className="gap-2" onClick={fetchNow} disabled={busy}>
                <RefreshCw className={`h-4 w-4 ${fetching ? "animate-spin" : ""}`} />
                Fetch live bids
              </Button>
              <Button type="button" variant="outline" className="gap-2" onClick={disconnect}>
                <Unplug className="h-4 w-4" />
                Disconnect
              </Button>
            </>
          ) : null}
          {variant === "settings" ? (
            <Link href="/opportunities" className="self-center text-sm text-sky-400 hover:text-sky-300">
              Federal work guide →
            </Link>
          ) : null}
        </div>
      </CardContent>
    </Card>
  );
}
