"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { api, auth } from "@/lib/api";
import { FormField, Input, Button } from "@/components/ui";
import { readBrand, applyBrandVars, DEFAULT_BRAND, type Brand } from "@/lib/brand";

/** Dedicated affiliate login page. On success it sends the affiliate to their
 *  portal at /dashboard. New affiliates apply at /signup. */
export default function LoginPage() {
  const router = useRouter();
  const [form, setForm] = useState({ email: "", password: "" });
  const [error, setError] = useState("");
  const [busy, setBusy] = useState(false);
  const [noStore, setNoStore] = useState(false);
  const [brand, setBrand] = useState<Brand>(DEFAULT_BRAND);

  useEffect(() => {
    // Already logged in → straight to the portal.
    if (auth.get()?.id) router.replace("/dashboard");
    const b = readBrand();
    setBrand(b);
    applyBrandVars(b);
    api
      .get("/affiliates/signup-config")
      .then((c) => {
        if (c?.noStore) { setNoStore(true); return; }
        const bb = c?.branding ?? {};
        const next: Brand = { logoUrl: bb.logoUrl ?? DEFAULT_BRAND.logoUrl, name: c?.programName || DEFAULT_BRAND.name, brandColor: bb.brandColor ?? null, brandSecondaryColor: bb.brandSecondaryColor ?? null };
        setBrand(next);
        applyBrandVars(next);
      })
      .catch(() => {});
  }, [router]);

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError("");
    try {
      const r = await api.post("/affiliates/login", form);
      auth.save(r.id, r.name, r.token);
      router.push("/dashboard");
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setBusy(false);
    }
  };

  if (noStore) {
    return (
      <div className="flex min-h-[80vh] items-center justify-center px-4 py-12">
        <div className="w-full max-w-md rounded-xl border border-gray-200 bg-white p-6 text-center shadow-sm">
          <div className="text-4xl">🔗</div>
          <h1 className="mt-2 text-xl font-bold text-gray-900">This login link is incomplete</h1>
          <p className="mt-2 text-gray-600">
            Affiliate portals on Trackopia belong to a specific store. Please open the login link
            the store shared with you — it looks like{" "}
            <span className="whitespace-nowrap font-mono text-sm text-gray-800">…/login?shop=your-store.myshopify.com</span>.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex min-h-[80vh] items-center justify-center px-4 py-12">
      <div className="w-full max-w-sm">
        <div className="mb-6 text-center">
          {brand.logoUrl ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={brand.logoUrl} alt={brand.name} className="mx-auto h-12 w-12 rounded-xl object-contain" />
          ) : (
            <span className="mx-auto 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>
          )}
          <h1 className="mt-3 text-xl font-bold text-gray-900">Affiliate login</h1>
          <p className="text-sm text-gray-500">Log in to track your earnings and request payouts</p>
        </div>
        <form onSubmit={submit} className="space-y-4 rounded-xl border border-gray-200 bg-white p-6 shadow-sm">
          <FormField label="Email">
            <Input type="email" required value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
          </FormField>
          <FormField label="Password" error={error}>
            <Input type="password" required error={!!error} value={form.password} onChange={(e) => setForm({ ...form, password: e.target.value })} />
          </FormField>
          <Button type="submit" loading={busy} className="w-full">Log in</Button>
          <p className="text-center text-sm text-gray-500">
            No account? <Link href="/signup" className="font-medium text-[var(--brand)] hover:underline">Sign up</Link>
          </p>
        </form>
      </div>
    </div>
  );
}
