"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { apiPost } from "@/lib/client-api";

interface Verification {
  method: string;
  token: string;
  status: string;
  error: string | null;
}

const METHOD_HELP: Record<string, (token: string, url: string) => React.ReactNode> = {
  HTML_FILE: (token, url) => (
    <>
      Upload a file named <code className="rounded bg-slate-100 px-1">{token}.html</code> containing
      exactly <code className="rounded bg-slate-100 px-1">{token}</code> to your website root, so it
      is reachable at{" "}
      <code className="rounded bg-slate-100 px-1 break-all">
        {url}/{token}.html
      </code>
      .
    </>
  ),
  META_TAG: (token) => (
    <>
      Add this tag inside your homepage&apos;s <code>&lt;head&gt;</code>:{" "}
      <code className="mt-1 block break-all rounded bg-slate-100 p-2 text-xs">
        &lt;meta name=&quot;nws-site-verification&quot; content=&quot;{token}&quot; /&gt;
      </code>
    </>
  ),
  DNS_TXT: (token) => (
    <>
      Add a DNS TXT record to your domain with the value:{" "}
      <code className="mt-1 block break-all rounded bg-slate-100 p-2 text-xs">
        nws-site-verification={token}
      </code>
      DNS changes can take up to an hour to appear.
    </>
  ),
};

const METHOD_NAMES: Record<string, string> = {
  HTML_FILE: "HTML file upload",
  META_TAG: "Meta tag",
  DNS_TXT: "DNS TXT record",
};

export function VerificationPanel({
  websiteId,
  websiteUrl,
  verifications,
}: {
  websiteId: string;
  websiteUrl: string;
  verifications: Verification[];
}) {
  const router = useRouter();
  const [busyMethod, setBusyMethod] = useState<string | null>(null);
  const [results, setResults] = useState<Record<string, string>>({});

  async function check(method: string) {
    setBusyMethod(method);
    const result = await apiPost<{ verified: boolean; error: string | null }>(
      `/api/websites/${websiteId}/verify`,
      { method }
    );
    setBusyMethod(null);
    if (result.ok && result.data.verified) {
      setResults((r) => ({ ...r, [method]: "Verified!" }));
      router.refresh();
    } else {
      setResults((r) => ({
        ...r,
        [method]: result.ok ? (result.data.error ?? "Not verified yet.") : result.error,
      }));
    }
  }

  return (
    <section className="rounded-xl border border-amber-200 bg-amber-50 p-6">
      <h2 className="font-semibold text-amber-900">Verify you own this website</h2>
      <p className="mt-1 text-sm text-amber-800">
        Verification proves you control the site before we audit it. Pick whichever method is
        easiest — you only need one.
      </p>
      <div className="mt-4 space-y-4">
        {verifications.map((v) => (
          <details key={v.method} className="rounded-lg border border-amber-200 bg-white p-4">
            <summary className="cursor-pointer text-sm font-medium">
              {METHOD_NAMES[v.method] ?? v.method}
            </summary>
            <div className="mt-3 text-sm text-slate-600">
              {METHOD_HELP[v.method]?.(v.token, websiteUrl)}
              <div className="mt-3 flex items-center gap-3">
                <button
                  type="button"
                  disabled={busyMethod !== null}
                  onClick={() => check(v.method)}
                  className="rounded-lg bg-slate-900 px-4 py-2 text-xs font-medium text-white hover:bg-slate-700 disabled:opacity-50"
                >
                  {busyMethod === v.method ? "Checking…" : "Check now"}
                </button>
                {results[v.method] && (
                  <span
                    className={`text-xs ${results[v.method] === "Verified!" ? "text-green-700" : "text-red-700"}`}
                  >
                    {results[v.method]}
                  </span>
                )}
              </div>
            </div>
          </details>
        ))}
      </div>
    </section>
  );
}
