'use client';

import Link from 'next/link';
import { useEffect, useMemo, useState } from 'react';
import { PublicFlowNav } from '../public-flow-nav';
import { formatCurrency, publicApiBase } from '../lib/public-order-store';

type PublicStore = {
  id: string;
  slug: string;
  name: string;
  description?: string | null;
  city?: string | null;
  neighborhood?: string | null;
  baseDeliveryFee?: number | string | null;
  categories?: string[];
  featuredProducts?: string[];
};

export default function PublicOrderDiscoverPage() {
  const [stores, setStores] = useState<PublicStore[]>([]);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('Todos');

  useEffect(() => {
    const params = new URLSearchParams();
    if (search.trim()) {
      params.set('search', search.trim());
    }
    if (selectedCategory !== 'Todos') {
      params.set('category', selectedCategory);
    }

    void fetch(`${publicApiBase}/public/catalog/stores${params.toString() ? `?${params.toString()}` : ''}`, { cache: 'no-store' })
      .then(async (response) => {
        const payload = await response.json().catch(() => null);
        if (!response.ok) {
          throw new Error(payload?.message ?? 'Falha ao carregar lojas publicas.');
        }
        return payload as PublicStore[];
      })
      .then(setStores)
      .catch((err) => setError(err instanceof Error ? err.message : 'Falha ao carregar lojas publicas.'));
  }, [search, selectedCategory]);

  const cuisines = useMemo(() => {
    const dynamic = Array.from(new Set(stores.flatMap((store) => store.categories ?? []).filter(Boolean))).sort((a, b) => a.localeCompare(b));
    return ['Todos', ...dynamic];
  }, [stores]);

  return (
    <main className="min-h-screen bg-[radial-gradient(circle_at_top_left,rgba(251,146,60,0.16),transparent_22%),linear-gradient(180deg,#fff8f1_0%,#fffdf8_48%,#eefaf3_100%)] px-4 py-6 text-slate-950 lg:px-8 lg:py-8">
      <div className="mx-auto max-w-7xl space-y-6">
        <PublicFlowNav />

        <section className="overflow-hidden rounded-[2.2rem] border border-white/80 bg-[linear-gradient(135deg,#0f172a_0%,#1d4ed8_48%,#f59e0b_100%)] p-6 text-white shadow-[0_30px_90px_rgba(15,23,42,0.18)] lg:p-8">
          <div className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.34em] text-amber-200">Descoberta do cliente</p>
              <h1 className="mt-4 max-w-4xl text-4xl font-black tracking-tight lg:text-5xl">Pesquise pela comida e veja quais lojas entregam o que voce quer.</h1>
              <p className="mt-4 max-w-3xl text-sm leading-7 text-slate-100/90 lg:text-base">
                Digite pizza, hamburger, sushi, a categoria desejada ou toque nas categorias para listar todos os restaurantes que oferecem aquele tipo de comida.
              </p>
              <div className="mt-5 max-w-2xl rounded-[1.4rem] border border-white/10 bg-white/10 p-3 backdrop-blur">
                <input
                  value={search}
                  onChange={(event) => setSearch(event.target.value)}
                  placeholder="Buscar comida, prato ou item. Ex.: pizza calabresa"
                  className="h-12 w-full rounded-[1rem] border border-white/10 bg-white/10 px-4 text-sm font-semibold text-white outline-none placeholder:text-white/65"
                />
              </div>
            </div>
            <div className="grid gap-4 sm:grid-cols-3 xl:grid-cols-1">
              <div className="rounded-[1.6rem] border border-white/10 bg-white/10 p-4 backdrop-blur">
                <p className="text-[11px] font-black uppercase tracking-[0.22em] text-amber-100">Lojas abertas</p>
                <p className="mt-3 text-3xl font-black">{stores.length}</p>
                <p className="mt-2 text-sm text-slate-100/80">Catálogo remoto</p>
              </div>
              <div className="rounded-[1.6rem] border border-white/10 bg-white/10 p-4 backdrop-blur">
                <p className="text-[11px] font-black uppercase tracking-[0.22em] text-amber-100">Frete base</p>
                <p className="mt-3 text-3xl font-black">{stores[0] ? formatCurrency(stores[0].baseDeliveryFee ?? 0) : '--'}</p>
                <p className="mt-2 text-sm text-slate-100/80">Primeira loja ativa</p>
              </div>
              <div className="rounded-[1.6rem] border border-white/10 bg-white/10 p-4 backdrop-blur">
                <p className="text-[11px] font-black uppercase tracking-[0.22em] text-amber-100">Fluxo</p>
                <p className="mt-3 text-3xl font-black">Real</p>
                <p className="mt-2 text-sm text-slate-100/80">Cardapio e pedido conectados</p>
              </div>
            </div>
          </div>
        </section>

        {error ? <section className="rounded-[1.4rem] border border-rose-200 bg-rose-50 px-5 py-4 text-sm text-rose-700">{error}</section> : null}

        <section className="rounded-[1.8rem] border border-slate-200 bg-white/90 p-4 shadow-[0_20px_50px_rgba(43,24,15,0.06)]">
          <div className="flex flex-wrap gap-2">
            {cuisines.map((cuisine) => (
              <button
                type="button"
                key={cuisine}
                onClick={() => setSelectedCategory(cuisine)}
                className={[
                  'inline-flex min-h-[2.7rem] items-center justify-center rounded-full px-4 text-xs font-black uppercase tracking-[0.16em]',
                  selectedCategory === cuisine ? 'bg-slate-950 text-white' : 'border border-slate-200 bg-slate-50 text-slate-800',
                ].join(' ')}
              >
                {cuisine}
              </button>
            ))}
          </div>
        </section>

        {!error && !stores.length ? (
          <section className="rounded-[1.6rem] border border-slate-200 bg-white px-5 py-8 text-center shadow-[0_20px_50px_rgba(43,24,15,0.06)]">
            <p className="text-xs font-black uppercase tracking-[0.22em] text-slate-500">Sem resultado</p>
            <h2 className="mt-3 text-2xl font-black text-slate-950">Nenhuma loja encontrou esse item.</h2>
            <p className="mt-3 text-sm text-slate-600">Tente outro nome de comida ou toque em uma categoria diferente.</p>
          </section>
        ) : null}

        <section className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
          {stores.map((store, index) => (
            <article key={store.id} className="overflow-hidden rounded-[1.9rem] border border-white/80 bg-white p-5 shadow-[0_22px_52px_rgba(43,24,15,0.08)]">
              <div className={`rounded-[1.5rem] bg-gradient-to-br ${index % 3 === 0 ? 'from-[#7c421d] to-[#f59e0b]' : index % 3 === 1 ? 'from-[#0f172a] to-[#2563eb]' : 'from-[#065f46] to-[#10b981]'} p-5 text-white`}>
                <p className="text-[11px] font-black uppercase tracking-[0.22em] text-white/80">{store.neighborhood ?? 'Loja ativa'}</p>
                <h2 className="mt-3 text-2xl font-black">{store.name}</h2>
                <p className="mt-3 inline-flex rounded-full bg-white/15 px-3 py-2 text-[11px] font-black uppercase tracking-[0.16em] text-white">
                  {store.city ?? 'Sao Paulo'}
                </p>
              </div>
              <div className="mt-4 grid grid-cols-2 gap-3 text-center">
                <div className="rounded-[1rem] bg-slate-50 px-3 py-3">
                  <p className="text-[10px] font-black uppercase tracking-[0.16em] text-slate-500">Frete base</p>
                  <p className="mt-2 text-sm font-black text-slate-900">{formatCurrency(store.baseDeliveryFee ?? 0)}</p>
                </div>
                <div className="rounded-[1rem] bg-slate-50 px-3 py-3">
                  <p className="text-[10px] font-black uppercase tracking-[0.16em] text-slate-500">Cidade</p>
                  <p className="mt-2 text-sm font-black text-slate-900">{store.city ?? '--'}</p>
                </div>
              </div>
              <p className="mt-4 text-sm text-slate-600">{store.description ?? 'Sem descricao cadastrada.'}</p>
              {store.categories?.length ? (
                <div className="mt-4 flex flex-wrap gap-2">
                  {store.categories.slice(0, 4).map((category) => (
                    <button
                      type="button"
                      key={category}
                      onClick={() => setSelectedCategory(category)}
                      className="rounded-full border border-slate-200 bg-slate-50 px-3 py-1 text-[10px] font-black uppercase tracking-[0.16em] text-slate-700"
                    >
                      {category}
                    </button>
                  ))}
                </div>
              ) : null}
              {store.featuredProducts?.length ? (
                <div className="mt-4 rounded-[1rem] bg-slate-50 px-4 py-3">
                  <p className="text-[10px] font-black uppercase tracking-[0.16em] text-slate-500">Comidas encontradas</p>
                  <p className="mt-2 text-sm font-semibold text-slate-900">{store.featuredProducts.join(' • ')}</p>
                </div>
              ) : null}
              <Link href={`/public-order?store=${store.slug}`} className="mt-5 inline-flex min-h-[3rem] w-full items-center justify-center rounded-full bg-slate-950 px-4 text-xs font-black uppercase tracking-[0.18em] text-white">
                Abrir cardapio
              </Link>
            </article>
          ))}
        </section>
      </div>
    </main>
  );
}
