"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { api, auth } from "@/lib/api";
import { Card, Button, Input, FormField, Checkbox } from "@/components/ui";

type Field = { id: string; label: string; type: string; required: boolean };
type Toggle = { enabled: boolean; required: boolean };
type Defaults = Record<string, Toggle>;

const DEFAULT_META: { key: string; label: string; type: string }[] = [
  { key: "phone", label: "Phone number", type: "tel" },
  { key: "social", label: "Social media handle", type: "text" },
  { key: "website", label: "Website / blog", type: "text" },
  { key: "address", label: "Address", type: "text" },
];

export default function SignupPage() {
  const [form, setForm] = useState({ name: "", email: "", password: "", social: "", website: "" });
  const [fields, setFields] = useState<Field[]>([]);
  const [defaults, setDefaults] = useState<Defaults>({});
  const [ref, setRef] = useState<string>("");

  // MLM: capture the recruiter's ?ref= code from the invite link.
  useEffect(() => {
    const r = new URLSearchParams(window.location.search).get("ref");
    if (r) setRef(r);
  }, []);
  const [custom, setCustom] = useState<Record<string, string>>({});
  const [terms, setTerms] = useState<string | null>(null);
  const [brand, setBrand] = useState<{ logoUrl: string | null; name: string }>({ logoUrl: null, name: "the program" });
  const [agreed, setAgreed] = useState(false);
  const [result, setResult] = useState<{ status: string; message: string } | null>(null);
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [noStore, setNoStore] = useState(false);
  const [loading, setLoading] = useState(true);

  const [siteKey, setSiteKey] = useState<string | null>(null);

  useEffect(() => {
    // Public signup config (branding, fields, reCAPTCHA) — no admin auth needed.
    api.get("/affiliates/signup-config").then((c) => {
      // No store in the link → this page can't enrol anyone. Show guidance.
      if (c?.noStore) { setNoStore(true); setLoading(false); return; }
      setFields(c?.fields || []);
      setDefaults(c?.signupDefaults || {});
      setTerms(c?.branding?.termsText || null);
      setBrand({ logoUrl: c?.branding?.logoUrl ?? null, name: c?.programName || "the program" });
      if (c?.recaptchaSiteKey) {
        setSiteKey(c.recaptchaSiteKey);
        const s = document.createElement("script");
        s.src = `https://www.google.com/recaptcha/api.js?render=${c.recaptchaSiteKey}`;
        document.head.appendChild(s);
      }
      setLoading(false);
    }).catch(() => setLoading(false));
  }, []);

  const onDefault = (key: string, label: string, value: string) => {
    if (key === "social") setForm((f) => ({ ...f, social: value }));
    else if (key === "website") setForm((f) => ({ ...f, website: value }));
    else setCustom((c) => ({ ...c, [label]: value }));
  };
  const defaultValue = (key: string, label: string) =>
    key === "social" ? form.social : key === "website" ? form.website : custom[label] ?? "";

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (terms && !agreed) {
      setError("Please accept the Terms & Conditions.");
      return;
    }
    setBusy(true);
    setError("");
    try {
      let recaptchaToken: string | undefined;
      const grecaptcha = (window as unknown as { grecaptcha?: { ready: (cb: () => void) => void; execute: (k: string, o: { action: string }) => Promise<string> } }).grecaptcha;
      if (siteKey && grecaptcha) {
        recaptchaToken = await new Promise<string>((resolve) =>
          grecaptcha.ready(() => grecaptcha.execute(siteKey, { action: "signup" }).then(resolve)),
        );
      }
      const r = await api.post("/affiliates/signup", { ...form, signupData: custom, ref, recaptchaToken });
      setResult(r);
      const login = await api.post("/affiliates/login", { email: form.email, password: form.password });
      auth.save(login.id, login.name, login.token);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setBusy(false);
    }
  };

  if (loading) {
    return (
      <div className="mx-auto flex max-w-md items-center justify-center py-24">
        <div className="h-8 w-8 animate-spin rounded-full border-2 border-gray-200 border-t-[var(--brand)]" />
      </div>
    );
  }

  if (noStore) {
    return (
      <div className="mx-auto max-w-lg">
        <Card>
          <div className="text-center">
            <div className="text-4xl">🔗</div>
            <h1 className="mt-2 text-xl font-bold text-gray-900">This sign-up link is incomplete</h1>
            <p className="mt-2 text-gray-600">
              Trackopia is a multi-store app, so every store has its <b>own</b> affiliate
              sign-up link that includes the store, like{" "}
              <span className="whitespace-nowrap font-mono text-sm text-gray-800">…/signup?shop=your-store.myshopify.com</span>.
            </p>
            <div className="mt-5 rounded-xl border border-gray-200 bg-gray-50 p-4 text-left text-sm text-gray-600">
              <p className="font-semibold text-gray-800">Testing the app?</p>
              <p className="mt-1">
                Open the Trackopia app in your Shopify admin, then either:
              </p>
              <ul className="mt-2 list-disc space-y-1 pl-5">
                <li>go to <b>Affiliates → Add affiliate</b> to create one directly, or</li>
                <li>on the <b>Overview</b> page, copy the <b>Affiliate sign-up</b> link under <b>Important links</b> (it already includes your store) and open that.</li>
              </ul>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  if (result) {
    return (
      <div className="mx-auto max-w-md">
        <Card>
          <div className="text-center">
            <div className="text-4xl">🎉</div>
            <h1 className="mt-2 text-xl font-bold text-gray-900">You&apos;re registered!</h1>
            <p className="mt-2 text-gray-600">{result.message}</p>
            <p className="mt-1 text-sm text-gray-500">Status: {result.status}</p>
            <div className="mt-5 flex justify-center gap-3">
              <Link href="/dashboard"><Button>Go to my dashboard</Button></Link>
              <Link href="/admin"><Button variant="secondary">Admin (approve me)</Button></Link>
            </div>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className="mx-auto max-w-md">
      <div className="mb-4 flex items-center gap-3">
        {brand.logoUrl ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img src={brand.logoUrl} alt={brand.name} className="h-11 w-11 rounded-xl object-contain" />
        ) : (
          <span className="flex h-11 w-11 items-center justify-center rounded-xl bg-[var(--brand)] text-base font-bold text-white">{brand.name.slice(0, 2).toUpperCase()}</span>
        )}
        <div>
          <h1 className="text-2xl font-bold text-gray-900">Become an affiliate</h1>
          <p className="text-sm text-gray-600">Join {brand.name} and earn commission on every sale you refer.</p>
        </div>
      </div>
      <form onSubmit={submit} className="mt-6">
        <Card>
          <div className="space-y-4">
            <FormField label="Full name" required>
              <Input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} />
            </FormField>
            <FormField label="Email" required>
              <Input type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
            </FormField>
            <FormField label="Password" required>
              <Input type="password" required value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
            </FormField>
            {/* Built-in optional fields the merchant enabled */}
            {DEFAULT_META.filter((f) => defaults[f.key]?.enabled).map((f) => (
              <FormField key={f.key} label={f.label} required={defaults[f.key]?.required}>
                <Input
                  type={f.type}
                  required={defaults[f.key]?.required}
                  value={defaultValue(f.key, f.label)}
                  onChange={(e) => onDefault(f.key, f.label, e.target.value)}
                />
              </FormField>
            ))}

            {/* Merchant-defined custom fields */}
            {fields.map((f) => (
              <FormField key={f.id} label={f.label} required={f.required}>
                <Input
                  type={f.type === "number" ? "number" : f.type === "email" ? "email" : "text"}
                  required={f.required}
                  value={custom[f.label] ?? ""}
                  onChange={(e) => setCustom({ ...custom, [f.label]: e.target.value })}
                />
              </FormField>
            ))}

            {terms && (
              <div className="rounded-lg border border-gray-200 bg-gray-50 p-3">
                <div className="max-h-24 overflow-y-auto text-xs text-gray-500">{terms}</div>
                <div className="mt-2">
                  <Checkbox label="I agree to the Terms & Conditions" checked={agreed} onChange={(e) => setAgreed(e.target.checked)} />
                </div>
              </div>
            )}

            {error && <p className="text-sm text-red-600">{error}</p>}
            <Button type="submit" loading={busy} className="w-full">Sign up</Button>
            <p className="text-center text-sm text-gray-500">
              Already have an account? <Link href="/dashboard" className="font-medium text-[var(--brand)] hover:underline">Log in</Link>
            </p>
          </div>
        </Card>
      </form>
    </div>
  );
}
