"use client";

import { FormEvent, useEffect, useState } from "react";
import { ArrowRight, Check, ExternalLink, LoaderCircle, LockKeyhole, Server, ShieldCheck } from "lucide-react";
import Link from "next/link";
import "./connect.css";

type PendingPair = { site: string; code: string };
type PairResult = { site?: { id: string; name: string }; message?: string };

const storageKey = "aiwc-pending-site-pair";

export default function ConnectPage() {
  const [pending, setPending] = useState<PendingPair | null>(null);
  const [checking, setChecking] = useState(true);
  const [authenticated, setAuthenticated] = useState(false);
  const [name, setName] = useState("");
  const [environment, setEnvironment] = useState("Production");
  const [profile, setProfile] = useState<"read_only" | "standard">("read_only");
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState("");
  const [connected, setConnected] = useState(false);

  function cancel() {
    window.sessionStorage.removeItem(storageKey);
    setPending(null);
    setError("");
  }

  useEffect(() => {
    const site = new URLSearchParams(window.location.search).get("site");
    const code = new URLSearchParams(window.location.hash.slice(1)).get("code");
    let saved: PendingPair | null = null;
    if (site && code && /^[a-f0-9]{64}$/.test(code)) {
      saved = { site, code };
      window.sessionStorage.setItem(storageKey, JSON.stringify(saved));
      window.history.replaceState(null, "", "/connect");
    } else {
      try { saved = JSON.parse(window.sessionStorage.getItem(storageKey) || "null") as PendingPair | null; }
      catch { saved = null; }
    }
    let validSite = false;
    try { validSite = Boolean(saved && new URL(saved.site).protocol === "https:"); } catch { validSite = false; }
    if (saved && validSite && /^[a-f0-9]{64}$/.test(saved.code)) {
      const selected = saved;
      queueMicrotask(() => { setPending(selected); setName(new URL(selected.site).hostname); });
    } else {
      window.sessionStorage.removeItem(storageKey);
    }
    fetch("/api/sites/pair", { cache: "no-store" })
      .then((response) => setAuthenticated(response.ok))
      .catch(() => setAuthenticated(false))
      .finally(() => setChecking(false));
  }, []);

  async function submit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!pending) return;
    setSubmitting(true);
    setError("");
    try {
      const response = await fetch("/api/sites/pair", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ url: pending.site, code: pending.code, name, environment, profile }),
      });
      const result = await response.json() as PairResult;
      if (!response.ok || !result.site) throw new Error(result.message || "The site could not be connected.");
      window.sessionStorage.removeItem(storageKey);
      setConnected(true);
    } catch (caught) {
      setError(caught instanceof Error ? caught.message : "The site could not be connected.");
    } finally {
      setSubmitting(false);
    }
  }

  return <main className="connect-shell">
    <header className="connect-header"><span className="connect-mark"><ShieldCheck size={19} /></span><strong>AI Web Command</strong><Link href="/overview" onClick={cancel}>Open dashboard <ExternalLink size={14} /></Link></header>
    <div className="connect-main">
      <div className="connect-title"><span className="connect-eyebrow">SITE CONNECTION</span><h1>Connect your WordPress site</h1><p>Finish the secure pairing started in the AI Web Command plugin.</p></div>
      {checking ? <section className="connect-panel connect-centered"><LoaderCircle className="spin" size={24} /><p>Checking your account...</p></section>
      : connected ? <section className="connect-panel connect-centered"><span className="connect-success"><Check size={24} /></span><h2>Site connected</h2><p>{name} is now in your workspace. The MCP client connection is configured separately.</p><Link className="button button-primary" href="/sites">View site <ArrowRight size={16} /></Link></section>
      : !pending ? <section className="connect-panel connect-centered"><Server size={25} /><h2>No pairing in progress</h2><p>Open AI Web Command in your WordPress admin and select Connect to AI Web Command.</p><Link className="button" href="/sites">Go to sites</Link></section>
      : !authenticated ? <section className="connect-panel connect-centered"><LockKeyhole size={27} /><h2>Sign in to continue</h2><p>Use the WooCommerce account for your subscription. This pairing stays in this browser tab.</p><Link className="button button-primary" href="/login">Sign in <ArrowRight size={16} /></Link></section>
      : <section className="connect-panel">
        <div className="connect-site-line"><span className="connect-site-icon"><Server size={19} /></span><div><strong>{name}</strong><small>{pending.site}</small></div><span className="connect-pending">Awaiting approval</span></div>
        <form onSubmit={submit}>
          <div className="connect-fields"><label className="field"><span>Site name</span><input value={name} onChange={(event) => setName(event.target.value)} required maxLength={100} /></label><label className="field"><span>Environment</span><select value={environment} onChange={(event) => setEnvironment(event.target.value)}><option>Production</option><option>Staging</option><option>Development</option></select></label></div>
          <fieldset className="connect-permissions"><legend>Site access</legend><label className={profile === "read_only" ? "connect-choice is-selected" : "connect-choice"}><input type="radio" name="profile" value="read_only" checked={profile === "read_only"} onChange={() => setProfile("read_only")} /><span><strong>Read-only</strong><small>Inspect content, plugins, diagnostics and site information.</small></span></label><label className={profile === "standard" ? "connect-choice is-selected" : "connect-choice"}><input type="radio" name="profile" value="standard" checked={profile === "standard"} onChange={() => setProfile("standard")} /><span><strong>Full site management</strong><small>Content, updates, settings, orders and security tools. Requires approval in WordPress.</small></span></label></fieldset>
          {error ? <p className="connect-error" role="alert">{error}</p> : null}
          <div className="connect-actions"><span>One-time pairing code. No WordPress password is shared.</span><div className="connect-action-buttons"><button className="button" type="button" onClick={cancel} disabled={submitting}>Cancel</button><button className="button button-primary" type="submit" disabled={submitting}>{submitting ? <><LoaderCircle className="spin" size={16} /> Connecting...</> : <>Connect site <ArrowRight size={16} /></>}</button></div></div>
        </form>
      </section>}
    </div>
  </main>;
}
