import { useEffect, useState } from "react";

import {
  fetchCatalogProducts,
  type CatalogProductSummary,
} from "@/api/catalog";
import { useAuth } from "@/auth/AuthProvider";

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]";
}

export function LandingWorkspacePage() {
  const { token, user } = useAuth();
  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(token?.access_token)
      .then((response) => {
        if (!cancelled) {
          setProducts(response);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setProducts([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [token?.access_token]);

  const highlightedProduct = products[0];

  return (
    <section className="mx-auto max-w-6xl px-6 py-10">
      <div className="grid gap-4 lg:grid-cols-[1.2fr_0.8fr]">
        <div className="rounded-[32px] border border-[#eadbcb] bg-white p-8 shadow-[0_20px_50px_rgba(123,78,42,0.08)]">
          <p className="text-sm font-semibold uppercase tracking-[0.18em] text-[var(--landing-accent)]">Protected workspace</p>
          <h1 className="mt-4 text-3xl font-black tracking-[-0.04em] text-[#2c261f]">인증된 사용자 전용 셸</h1>
          <p className="mt-4 max-w-2xl text-base leading-8 text-[var(--landing-muted)]">
            이 화면은 저장된 토큰으로 `auth/me` 검증이 끝난 뒤에만 열립니다. 랜딩 템플릿에서도 보호 라우트와 간단한 멤버 셸을 바로 사용할 수 있습니다.
          </p>
          <div className="mt-8 rounded-[24px] bg-[#fff7f0] p-6">
            <div className="flex items-center justify-between gap-4">
              <div>
                <p className="text-sm text-[var(--landing-muted)]">Catalog sync</p>
                <p className="mt-2 text-2xl font-black text-[#2c261f]">{loading ? "..." : `${products.length} products`}</p>
              </div>
              {highlightedProduct ? (
                <span className={`rounded-full px-3 py-1 text-xs font-semibold uppercase ${productStateClassName(highlightedProduct.status)}`}>
                  {highlightedProduct.status}
                </span>
              ) : null}
            </div>
            {error ? <p className="mt-4 text-sm font-semibold text-[#b85b2a]">{error}</p> : null}
            {!error ? <p className="mt-4 text-sm leading-7 text-[var(--landing-muted)]">{loading ? "Loading product catalog..." : highlightedProduct?.name ?? "No catalog products available."}</p> : null}
          </div>
        </div>
        <div className="rounded-[32px] bg-[#2c261f] p-8 text-white">
          <p className="text-sm text-white/65">Current member</p>
          <p className="mt-4 text-2xl font-black">{user?.name}</p>
          <dl className="mt-6 space-y-4 text-sm">
            <div>
              <dt className="text-white/55">Email</dt>
              <dd className="mt-1 font-semibold">{user?.email}</dd>
            </div>
            <div>
              <dt className="text-white/55">Role</dt>
              <dd className="mt-1 font-semibold">{user?.role}</dd>
            </div>
            <div>
              <dt className="text-white/55">Status</dt>
              <dd className="mt-1 font-semibold">{user?.status}</dd>
            </div>
          </dl>
        </div>
      </div>

      <div className="mt-6 grid gap-4 md:grid-cols-3">
        {loading ? (
          <div className="rounded-[28px] border border-[#eadbcb] bg-white p-6 md:col-span-3">
            <p className="text-sm text-[var(--landing-muted)]">Loading live workspace products...</p>
          </div>
        ) : null}
        {!loading && !error && !products.length ? (
          <div className="rounded-[28px] border border-[#eadbcb] bg-white p-6 md:col-span-3">
            <p className="text-sm text-[var(--landing-muted)]">There are no products to display in the workspace.</p>
          </div>
        ) : null}
        {products.map((product) => (
          <div key={product.id} className="rounded-[28px] border border-[#eadbcb] bg-white p-6 shadow-[0_16px_42px_rgba(123,78,42,0.06)]">
            <div className="flex items-center justify-between gap-3">
              <p className="text-sm text-[var(--landing-muted)]">{product.id}</p>
              <span className={`rounded-full px-3 py-1 text-xs font-semibold uppercase ${productStateClassName(product.status)}`}>{product.status}</span>
            </div>
            <p className="mt-4 text-xl font-bold text-[#2c261f]">{product.name}</p>
            <p className="mt-2 text-sm text-[var(--landing-muted)]">{product.brand}</p>
          </div>
        ))}
      </div>
    </section>
  );
}
