"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { CheckCircle2, ExternalLink, Globe, KeyRound, Loader2, Unplug } from "lucide-react";
import type { Business, WordPressIntegration } from "@/lib/types";
import { isWordPressConnected, maskWordPressPassword, normalizeWordPressSiteUrl } from "@/lib/integrations/wordpress";
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 WordPressIntegrationCardProps {
  business: Business;
  onUpdate: (business: Business) => void;
}

export function WordPressIntegrationCard({ business, onUpdate }: WordPressIntegrationCardProps) {
  const existing = business.integrations?.wordpress;
  const [siteUrl, setSiteUrl] = useState(
    existing?.siteUrl ?? normalizeWordPressSiteUrl(business.input.websiteUrl ?? ""),
  );
  const [username, setUsername] = useState(existing?.username ?? "");
  const [applicationPassword, setApplicationPassword] = useState("");
  const [testing, setTesting] = useState(false);
  const [message, setMessage] = useState<{ type: "ok" | "error"; text: string } | null>(null);

  useEffect(() => {
    if (existing?.siteUrl) setSiteUrl(existing.siteUrl);
    if (existing?.username) setUsername(existing.username);
  }, [existing?.siteUrl, existing?.username]);

  const connected = isWordPressConnected(existing);

  const testAndSave = async () => {
    setTesting(true);
    setMessage(null);
    try {
      const password = applicationPassword || existing?.applicationPassword || "";
      const res = await fetch("/api/integrations/wordpress/test", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ siteUrl, username, applicationPassword: password }),
      });
      const data = (await res.json()) as {
        ok?: boolean;
        error?: string;
        siteName?: string;
        adminUrl?: string;
        applicationPassword?: string;
      };

      if (!res.ok || !data.ok) {
        setMessage({ type: "error", text: data.error ?? "Connection failed." });
        const next: Business = {
          ...business,
          integrations: {
            ...business.integrations,
            wordpress: {
              siteUrl: normalizeWordPressSiteUrl(siteUrl),
              username: username.trim(),
              applicationPassword: password,
              status: "error",
              lastTestedAt: new Date().toISOString(),
              lastError: data.error,
            },
          },
          updatedAt: new Date().toISOString(),
        };
        onUpdate(next);
        await saveBusiness(next);
        return;
      }

      const wp: WordPressIntegration = {
        siteUrl: normalizeWordPressSiteUrl(siteUrl),
        username: username.trim(),
        applicationPassword: data.applicationPassword ?? password,
        status: "connected",
        connectedAt: new Date().toISOString(),
        lastTestedAt: new Date().toISOString(),
        siteName: data.siteName,
        adminUrl: data.adminUrl,
      };

      const next: Business = {
        ...business,
        input: { ...business.input, websiteUrl: wp.siteUrl },
        integrations: { ...business.integrations, wordpress: wp },
        updatedAt: new Date().toISOString(),
      };
      onUpdate(next);
      await saveBusiness(next);
      setApplicationPassword("");
      setMessage({
        type: "ok",
        text: `Connected to ${data.siteName ?? "WordPress"}. Website aesthetic uploads can now target your live site (draft mode until you publish).`,
      });
    } catch {
      setMessage({ type: "error", text: "Network error — could not reach BrandLxft API." });
    } finally {
      setTesting(false);
    }
  };

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

  return (
    <Card id="wordpress-api" className="scroll-mt-6 border-sky-500/20">
      <CardHeader>
        <CardTitle className="flex flex-wrap items-center gap-2">
          <Globe className="h-5 w-5 text-sky-400" />
          WordPress API
          {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">
          Connect your WordPress site so BrandLxft can upload website aesthetic drafts and Role Agent CMS updates via the REST API.
        </p>
      </CardHeader>
      <CardContent className="space-y-5">
        <div className="rounded-xl border border-slate-800 bg-slate-900/50 p-4">
          <p className="flex items-center gap-2 text-sm font-medium text-slate-200">
            <KeyRound className="h-4 w-4 text-amber-400" />
            How to create a WordPress Application Password
          </p>
          <ol className="mt-3 list-decimal space-y-2 pl-5 text-sm text-slate-400">
            <li>Log in to your WordPress admin (<code className="text-sky-300">yoursite.com/wp-admin</code>).</li>
            <li>Go to <strong className="text-slate-300">Users → Profile</strong> (for your account).</li>
            <li>Scroll to <strong className="text-slate-300">Application Passwords</strong> (WordPress 5.6+).</li>
            <li>Enter a name like <strong className="text-slate-300">BrandLxft</strong> and click <strong className="text-slate-300">Add New Application Password</strong>.</li>
            <li>Copy the password WordPress shows <em>once</em> — paste it below (spaces are OK).</li>
          </ol>
          <p className="mt-3 text-xs text-slate-500">
            Requires HTTPS on your site. If you don&apos;t see Application Passwords, ask your host to enable REST API / disable security plugins blocking <code>/wp-json/</code>.
          </p>
        </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">WordPress site URL</label>
            <Input
              placeholder="https://yoursite.com"
              value={siteUrl}
              onChange={(e) => setSiteUrl(e.target.value)}
            />
          </div>
          <div>
            <label className="mb-1 block text-xs text-slate-500">WordPress username</label>
            <Input
              placeholder="admin or your WP login"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              autoComplete="username"
            />
          </div>
          <div>
            <label className="mb-1 block text-xs text-slate-500">Application password</label>
            <Input
              type="password"
              placeholder={existing?.applicationPassword ? maskWordPressPassword(existing.applicationPassword) : "xxxx xxxx xxxx xxxx xxxx xxxx"}
              value={applicationPassword}
              onChange={(e) => setApplicationPassword(e.target.value)}
              autoComplete="new-password"
            />
            {connected && !applicationPassword ? (
              <p className="mt-1 text-xs text-slate-500">Leave blank to re-test with saved password.</p>
            ) : null}
          </div>
        </div>

        {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">
              {existing.siteName ?? existing.siteUrl}
              {existing.lastTestedAt ? ` · tested ${new Date(existing.lastTestedAt).toLocaleDateString()}` : ""}
            </span>
            {existing.adminUrl ? (
              <Link
                href={existing.adminUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1 text-sky-400 hover:text-sky-300"
              >
                Open wp-admin
                <ExternalLink className="h-3 w-3" />
              </Link>
            ) : null}
          </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={testAndSave} disabled={testing}>
            {testing ? (
              <>
                <Loader2 className="h-4 w-4 animate-spin" />
                Testing connection…
              </>
            ) : connected ? (
              "Test & save"
            ) : (
              "Connect WordPress"
            )}
          </Button>
          {connected ? (
            <Button type="button" variant="outline" className="gap-2" onClick={disconnect}>
              <Unplug className="h-4 w-4" />
              Disconnect
            </Button>
          ) : null}
          <Link href="/profile#website-analysis" className="self-center text-sm text-sky-400 hover:text-sky-300">
            Website aesthetic analysis →
          </Link>
        </div>
      </CardContent>
    </Card>
  );
}
