import { useEffect, useState } from "react";
import { Archive, ArrowRight, Boxes, CheckCircle2, Clock3 } from "lucide-react";
import { Link } from "react-router-dom";

import { fetchCatalogProducts, type CatalogProductSummary } from "@/api/catalog";
import { useAuth } from "@/auth/AuthProvider";
import { landingTheme } from "@/theme";
import { landingThemeVars } from "@/theme-vars";

const productStateCopy: Record<string, string> = {
  active: "즉시 연결 가능한 template surface",
  draft: "구성 중인 화면 및 플로우 실험",
  archived: "보관된 이전 실험 기록",
};

function productStateClassName(state: string) {
  if (state === "active") {
    return "bg-[var(--landing-accent-soft)] text-[var(--landing-accent)]";
  }
  if (state === "draft") {
    return "bg-[#fff2e4] text-[#b46c35]";
  }

  return "bg-[#efe4d7] text-[#7f5b39]";
}

function productStateIcon(state: string) {
  if (state === "active") {
    return CheckCircle2;
  }
  if (state === "draft") {
    return Clock3;
  }

  return Archive;
}

export function LandingHomePage() {
  const { user } = useAuth();
  const ctaTo = user ? "/workspace" : "/login";
  const ctaLabel = user ? "Open workspace" : "Sign in";
  const [products, setProducts] = useState<CatalogProductSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;

    setLoading(true);
    setError(null);

    fetchCatalogProducts()
      .then((response) => {
        if (!cancelled) {
          setProducts(response);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setProducts([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, []);

  const activeCount = products.filter((product) => product.status === "active").length;
  const highlightedProduct = products[0];

  return (
    <div className="min-h-screen bg-[var(--landing-bg)] text-[var(--landing-text)]" style={landingThemeVars(landingTheme)}>
      <header className="mx-auto flex max-w-6xl items-center justify-between px-6 py-6">
        <div className="text-[20px] font-black tracking-[0.18em]">PRODUCT</div>
        <nav className="hidden items-center gap-8 text-sm font-semibold md:flex">
          <a href="#features">Features</a>
          <a href="#proof">Proof</a>
          <a href="#cta">Contact</a>
          <Link className="rounded-full border border-[#d8cabb] px-4 py-2" to={ctaTo}>
            {ctaLabel}
          </Link>
        </nav>
      </header>

      <main className="space-y-[var(--landing-section-gap)]">
        <section className="mx-auto grid max-w-6xl gap-10 px-6 py-[var(--landing-hero-pad-y)] lg:grid-cols-[1.1fr_0.9fr]">
          <div>
            <p className="inline-flex rounded-full bg-[var(--landing-accent-soft)] px-4 py-2 text-sm font-semibold text-[var(--landing-accent)]">
              Built for product-grade delivery
            </p>
            <h1 className="mt-6 max-w-3xl text-5xl font-black leading-[1.05] tracking-[-0.04em]">
              서비스로 바로 이어지는
              <br />
              프론트엔드 템플릿
            </h1>
            <p className="mt-6 max-w-2xl text-lg leading-8 text-[var(--landing-muted)]">
              제품 DOM은 유지하고, 시각 계약만 안전하게 조정하는 React 보일러플레이트다. 랜딩, 일반 앱, 어드민 콘솔을 같은 철학으로 시작할 수 있다.
            </p>
            <div className="mt-8 flex flex-wrap gap-3">
              <Link
                className="inline-flex items-center gap-2 rounded-full bg-[var(--landing-accent)] px-6 py-3 text-sm font-semibold text-white"
                to={ctaTo}
              >
                {ctaLabel}
                <ArrowRight className="h-4 w-4" />
              </Link>
              <a className="rounded-full border border-[#d8cabb] px-6 py-3 text-sm font-semibold" href="#features">
                See examples
              </a>
            </div>
          </div>

          <div className="rounded-[var(--landing-card-radius)] border border-[#eadbcb] bg-[#fffaf5] p-6 shadow-[0_24px_70px_rgba(123,78,42,0.08)]">
            <div className="grid gap-4 md:grid-cols-2">
              <div className="rounded-[20px] bg-[#2c261f] p-5 text-white">
                <p className="text-sm text-white/70">Live catalog</p>
                <p className="mt-4 text-3xl font-black">{loading ? "..." : products.length}</p>
              </div>
              <div className="rounded-[20px] bg-[var(--landing-accent-soft)] p-5 text-[var(--landing-accent)]">
                <p className="text-sm opacity-80">Active products</p>
                <p className="mt-4 text-3xl font-black">{loading ? "..." : activeCount}</p>
              </div>
            </div>
            <div className="mt-4 rounded-[20px] border border-[#eadbcb] bg-white p-5">
              <p className="text-sm text-[var(--landing-muted)]">Catalog snapshot</p>
              {error ? <p className="mt-3 text-lg font-bold text-[#b85b2a]">{error}</p> : null}
              {!error ? <p className="mt-3 text-lg font-bold">{loading ? "Loading live catalog..." : highlightedProduct?.name ?? "No live products"}</p> : null}
              {!loading && highlightedProduct ? <p className="mt-2 text-sm text-[var(--landing-muted)]">State: {highlightedProduct.status}</p> : null}
            </div>
          </div>
        </section>

        <section id="features" className="mx-auto max-w-6xl px-6 py-10">
          <div className="grid gap-4 lg:grid-cols-3">
            {loading ? (
              <div className="rounded-[var(--landing-card-radius)] border border-[#eadbcb] bg-white px-6 py-7 lg:col-span-3">
                <p className="text-sm text-[var(--landing-muted)]">Loading live catalog...</p>
              </div>
            ) : null}
            {!loading && !error && !products.length ? (
              <div className="rounded-[var(--landing-card-radius)] border border-[#eadbcb] bg-white px-6 py-7 lg:col-span-3">
                <p className="text-sm text-[var(--landing-muted)]">No catalog products are available yet.</p>
              </div>
            ) : null}
            {products.map((product) => {
              const Icon = productStateIcon(product.status);
              return (
                <div key={product.id} className="rounded-[var(--landing-card-radius)] border border-[#eadbcb] bg-white px-6 py-7">
                  <div className={`inline-flex rounded-2xl p-3 ${productStateClassName(product.status)}`}>
                    <Icon className="h-5 w-5" />
                  </div>
                  <div className="mt-5 flex items-center justify-between gap-4">
                    <h2 className="text-xl font-bold">{product.name}</h2>
                    <span className={`rounded-full px-3 py-1 text-xs font-semibold uppercase ${productStateClassName(product.status)}`}>{product.status}</span>
                  </div>
                  <p className="mt-2 text-sm font-semibold text-[#7f5b39]">{product.brand}</p>
                  <p className="mt-3 text-sm leading-7 text-[var(--landing-muted)]">{product.short_description}</p>
                  <p className="mt-3 text-xs uppercase tracking-[0.16em] text-[var(--landing-muted)]">
                    {productStateCopy[product.status] ?? "Catalog product delivered from the live backend contract."}
                  </p>
                </div>
              );
            })}
          </div>
        </section>

        <section id="proof" className="mx-auto max-w-6xl px-6 py-4">
          <div className="rounded-[32px] border border-[#eadbcb] bg-white px-8 py-8 shadow-[0_18px_48px_rgba(123,78,42,0.06)]">
            <div className="flex flex-wrap items-center justify-between gap-4">
              <div>
                <p className="text-sm font-semibold uppercase tracking-[0.18em] text-[var(--landing-accent)]">Live proof</p>
                <h2 className="mt-3 text-3xl font-black tracking-[-0.04em]">`/api/v1/catalog/products` 기반 catalog surface</h2>
              </div>
              <div className="inline-flex items-center gap-2 rounded-full bg-[var(--landing-accent-soft)] px-4 py-2 text-sm font-semibold text-[var(--landing-accent)]">
                <Boxes className="h-4 w-4" />
                {loading ? "Syncing..." : `${products.length} products synced`}
              </div>
            </div>
            <div className="mt-6 grid gap-4 md:grid-cols-3">
              {[
                { label: "Active", value: products.filter((product) => product.status === "active").length.toString() },
                { label: "Draft", value: products.filter((product) => product.status === "draft").length.toString() },
                { label: "Archived", value: products.filter((product) => product.status === "archived").length.toString() },
              ].map((entry) => (
                <div key={entry.label} className="rounded-[24px] bg-[#fff7f0] px-5 py-5">
                  <p className="text-sm text-[var(--landing-muted)]">{entry.label}</p>
                  <p className="mt-3 text-3xl font-black text-[#2c261f]">{loading ? "..." : entry.value}</p>
                </div>
              ))}
            </div>
          </div>
        </section>

        <section id="cta" className="mx-auto max-w-6xl px-6 pb-16">
          <div className="rounded-[32px] bg-[#2c261f] px-8 py-10 text-white">
            <p className="text-sm text-white/60">Ready to start</p>
            <div className="mt-4 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
              <h2 className="max-w-2xl text-3xl font-black leading-tight">제품 구조를 무너뜨리지 않는 보일러플레이트로 시작하세요.</h2>
              <Link className="rounded-full bg-white px-6 py-3 text-sm font-semibold text-[#2c261f]" to={ctaTo}>
                {ctaLabel}
              </Link>
            </div>
          </div>
        </section>
      </main>
    </div>
  );
}
