'use client';

import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { Suspense, useEffect, useState } from 'react';
import { PublicFlowNav } from './public-flow-nav';
import { buildCartItemId, calculateUnitPrice, defaultOrderState, fetchStorefront, formatCurrency, readOrderState, type StoreProduct, type Storefront, writeOrderState } from './lib/public-order-store';

function PublicOrderPageContent() {
  const searchParams = useSearchParams();
  const [store, setStore] = useState<Storefront | null>(null);
  const [error, setError] = useState('');
  const [feedback, setFeedback] = useState('');

  useEffect(() => {
    const state = readOrderState();
    const requestedSlug = searchParams.get('store') || state.restaurantSlug;
    void fetchStorefront(requestedSlug)
      .then((payload) => {
        setStore(payload);
        writeOrderState({ ...state, restaurantSlug: payload.slug });
      })
      .catch((err) => setError(err instanceof Error ? err.message : 'Falha ao carregar vitrine publica.'));
  }, [searchParams]);

  const products = store?.productCategories.flatMap((category) =>
    category.products.map((product) => ({ ...product, categoryName: category.name })),
  ) ?? [];

  const quickAdd = (product: StoreProduct) => {
    const hasOptions = (product.additionals?.length ?? 0) > 0 || (product.variations?.length ?? 0) > 0;
    if (hasOptions) {
      return;
    }

    const state = readOrderState();
    const next = state.cart.slice();
    const id = buildCartItemId({ productId: product.id });
    const existing = next.find((item) => item.id === id);
    if (existing) {
      existing.quantity += 1;
    } else {
      next.push({
        id,
        productId: product.id,
        name: product.name,
        basePrice: Number(product.price),
        unitPrice: calculateUnitPrice(product),
        quantity: 1,
        selectedVariation: null,
        selectedAdditionals: [],
      });
    }
    writeOrderState({ ...defaultOrderState, ...state, cart: next });
    setFeedback(`${product.name} adicionado ao carrinho.`);
    window.setTimeout(() => setFeedback(''), 1800);
  };

  return (
    <main className="min-h-screen bg-[#f7f7f8] px-4 py-4 text-slate-950 lg:px-8 lg:py-6">
      <div className="mx-auto max-w-7xl space-y-6">
        <PublicFlowNav />

        <section className="overflow-hidden rounded-[2.2rem] bg-[linear-gradient(135deg,#111827_0%,#1f2937_58%,#f97316_100%)] p-6 text-white shadow-[0_26px_80px_rgba(15,23,42,0.16)] lg:p-8">
          <div className="grid gap-6 xl:grid-cols-[1.15fr_0.85fr]">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.34em] text-orange-200">Delivery</p>
              <h1 className="mt-4 max-w-3xl text-4xl font-black tracking-tight lg:text-5xl">{store?.name ?? 'Carregando loja...'}</h1>
              <p className="mt-4 max-w-2xl text-sm leading-7 text-orange-50/90 lg:text-base">{store?.description ?? 'Pedido simples, rapido e direto.'}</p>
              <div className="mt-6 flex flex-wrap gap-3">
                <Link href="/public-order/discover" className="inline-flex min-h-[3.2rem] items-center justify-center rounded-full bg-white px-5 text-xs font-black uppercase tracking-[0.22em] text-[#2b180f]">
                  Ver todas as lojas
                </Link>
                <Link href="/public-order/cart" className="inline-flex min-h-[3.2rem] items-center justify-center rounded-full bg-white px-5 text-xs font-black uppercase tracking-[0.22em] text-[#2b180f]">
                  Ver carrinho
                </Link>
              </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-orange-100">Entrega</p>
                <p className="mt-3 text-3xl font-black">{store?.city ?? 'Sao Paulo'}</p>
                <p className="mt-2 text-sm text-orange-50/80">{store?.neighborhood ?? 'Centro'}</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-orange-100">Catalogo</p>
                <p className="mt-3 text-3xl font-black">{products.length}</p>
                <p className="mt-2 text-sm text-orange-50/80">Itens ativos</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-orange-100">Frete base</p>
                <p className="mt-3 text-3xl font-black">{formatCurrency(store?.baseDeliveryFee ?? 0)}</p>
                <p className="mt-2 text-sm text-orange-50/80">Cobrado no fechamento</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}
        {feedback ? <section className="rounded-[1.4rem] border border-emerald-200 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700">{feedback}</section> : null}

        <section className="grid gap-6 xl:grid-cols-[1.1fr_0.9fr]">
          <section className="rounded-[2rem] bg-white/95 p-5 shadow-[0_14px_40px_rgba(15,23,42,0.06)] lg:p-6">
            <div>
              <p className="text-xs font-black uppercase tracking-[0.3em] text-slate-500">Cardapio</p>
              <h2 className="mt-3 text-3xl font-black tracking-tight text-slate-950">Escolha seu pedido</h2>
            </div>

            {store?.activePromotions?.length ? (
              <div className="mt-5 rounded-[1.4rem] bg-emerald-50 px-4 py-4">
                <p className="text-sm font-black text-emerald-800">{store.activePromotions[0].title}</p>
                {store.activePromotions[0].description ? (
                  <p className="mt-1 text-sm text-emerald-700">{store.activePromotions[0].description}</p>
                ) : null}
              </div>
            ) : null}

            <div className="mt-6 grid gap-4 lg:grid-cols-2">
              {products.map((item) => (
                <article key={item.id} className="rounded-[1.5rem] border border-slate-200 bg-slate-50/80 p-4">
                  <div className="flex items-start justify-between gap-4">
                    <div>
                      <p className="text-lg font-black text-slate-950">{item.name}</p>
                      <p className="mt-2 text-sm text-slate-600">{item.description ?? 'Sem descricao'}</p>
                    </div>
                    <span className="rounded-full bg-white px-3 py-1 text-[11px] font-black uppercase tracking-[0.18em] text-slate-700">{item.categoryName}</span>
                  </div>
                  <div className="mt-4 flex items-center justify-between gap-4">
                    <p className="text-xl font-black text-[#7c421d]">{formatCurrency(item.price)}</p>
                    <div className="flex gap-2">
                      {(item.additionals?.length ?? 0) === 0 && (item.variations?.length ?? 0) === 0 ? (
                        <button
                          type="button"
                          onClick={() => quickAdd(item)}
                          className="inline-flex min-h-[2.9rem] items-center justify-center rounded-full bg-[#2b180f] px-4 text-xs font-black uppercase tracking-[0.18em] text-white"
                        >
                          + Adicionar
                        </button>
                      ) : (
                        <Link href={`/public-order/product?id=${item.id}`} className="inline-flex min-h-[2.9rem] items-center justify-center rounded-full bg-[#2b180f] px-4 text-xs font-black uppercase tracking-[0.18em] text-white">
                          Escolher
                        </Link>
                      )}
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </section>

          <aside className="rounded-[2rem] border border-slate-200 bg-white p-5 shadow-[0_14px_40px_rgba(15,23,42,0.06)]">
            <p className="text-[11px] font-black uppercase tracking-[0.22em] text-slate-500">Atalhos</p>
            <div className="mt-4 space-y-3">
              <div className="rounded-[1.2rem] border border-slate-100 bg-slate-50 px-4 py-3">
                <p className="text-sm font-black text-slate-900">{products.length} itens disponiveis</p>
                <p className="mt-1 text-sm text-slate-600">Itens ativos da loja agora.</p>
              </div>
              {store?.activeCoupons?.length ? <div className="rounded-[1.2rem] border border-amber-200 bg-amber-50 px-4 py-3"><p className="text-sm font-black text-amber-800">Cupom em destaque: {store.activeCoupons[0].code}</p></div> : null}
            </div>
            <div className="mt-5 flex flex-col gap-3">
              <Link href="/public-order/discover" className="inline-flex min-h-[3rem] items-center justify-center rounded-full border border-slate-200 bg-white px-4 text-xs font-black uppercase tracking-[0.18em] text-slate-800">
                Escolher outra loja
              </Link>
              <Link href="/public-order/cart" className="inline-flex min-h-[3rem] items-center justify-center rounded-full bg-slate-950 px-4 text-xs font-black uppercase tracking-[0.18em] text-white">
                Revisar carrinho
              </Link>
            </div>
          </aside>
        </section>
      </div>
    </main>
  );
}

export default function PublicOrderPage() {
  return (
    <Suspense fallback={<main className="min-h-screen px-4 py-6">Carregando vitrine...</main>}>
      <PublicOrderPageContent />
    </Suspense>
  );
}
