'use client';

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

function PublicOrderProductPageContent() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [product, setProduct] = useState<StoreProduct | null>(null);
  const [quantity, setQuantity] = useState(1);
  const [notes, setNotes] = useState('');
  const [selectedVariationId, setSelectedVariationId] = useState('');
  const [selectedAdditionalIds, setSelectedAdditionalIds] = useState<string[]>([]);
  const [error, setError] = useState('');

  useEffect(() => {
    const state = readOrderState();
    const productId = searchParams.get('id');
    void fetchStorefront(state.restaurantSlug)
      .then((store) => {
        const allProducts = store.productCategories.flatMap((category) => category.products);
        const selected = allProducts.find((item) => item.id === productId) ?? allProducts[0] ?? null;
        setProduct(selected);
      })
      .catch((err) => setError(err instanceof Error ? err.message : 'Falha ao carregar produto.'));
  }, [searchParams]);

  const selectedVariation =
    product?.variations?.find((variation) => variation.id === selectedVariationId) ?? null;
  const selectedAdditionals = useMemo(
    () =>
      (product?.additionals ?? []).filter((additional) =>
        selectedAdditionalIds.includes(additional.id),
      ),
    [product, selectedAdditionalIds],
  );
  const unitPrice = useMemo(
    () => (product ? calculateUnitPrice(product, selectedVariation, selectedAdditionals) : 0),
    [product, selectedVariation, selectedAdditionals],
  );
  const lineTotal = Number((unitPrice * quantity).toFixed(2));

  const toggleAdditional = (additional: StoreProductAdditional) => {
    setSelectedAdditionalIds((current) =>
      current.includes(additional.id)
        ? current.filter((id) => id !== additional.id)
        : [...current, additional.id],
    );
  };

  const addToCart = () => {
    if (!product) return;
    const state = readOrderState();
    const normalizedAdditionalIds = selectedAdditionals.map((additional) => additional.id);
    const cartItemId = buildCartItemId({
      productId: product.id,
      selectedVariationId: selectedVariation?.id ?? null,
      selectedAdditionalIds: normalizedAdditionalIds,
      notes,
    });
    const next = state.cart.slice();
    const existing = next.find((item) => item.id === cartItemId);
    if (existing) {
      existing.quantity += quantity;
    } else {
      next.push({
        id: cartItemId,
        productId: product.id,
        name: product.name,
        basePrice: Number(product.price),
        unitPrice,
        quantity,
        notes: notes.trim() || undefined,
        selectedVariation,
        selectedAdditionals,
      });
    }
    writeOrderState({ ...defaultOrderState, ...state, cart: next });
    router.push('/public-order/cart');
  };

  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-6xl space-y-5">
        <PublicFlowNav />

        {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}

        <div className="grid gap-5 xl:grid-cols-[1.05fr_0.95fr]">
          <section className="rounded-[2rem] bg-white p-5 shadow-[0_14px_40px_rgba(15,23,42,0.06)]">
            <div className="flex items-start justify-between gap-4">
              <div>
                <p className="text-xs font-black uppercase tracking-[0.2em] text-slate-400">Produto</p>
                <h1 className="mt-2 text-3xl font-black tracking-tight text-slate-950">
                  {product?.name ?? 'Carregando...'}
                </h1>
                <p className="mt-3 text-sm leading-6 text-slate-600">
                  {product?.description ?? 'Escolha os complementos e envie direto para o carrinho.'}
                </p>
              </div>
              <div className="rounded-full bg-emerald-50 px-4 py-2 text-sm font-black text-emerald-700">
                {formatCurrency(unitPrice || product?.price)}
              </div>
            </div>

            {product?.variations?.length ? (
              <section className="mt-6">
                <h2 className="text-base font-black text-slate-950">Tamanho ou versao</h2>
                <div className="mt-3 grid gap-3">
                  {product.variations.map((variation) => {
                    const active = selectedVariationId === variation.id;
                    return (
                      <button
                        key={variation.id}
                        type="button"
                        onClick={() => setSelectedVariationId(active ? '' : variation.id)}
                        className={[
                          'flex items-center justify-between rounded-[1.2rem] border px-4 py-4 text-left transition',
                          active ? 'border-slate-950 bg-slate-950 text-white' : 'border-slate-200 bg-slate-50 text-slate-900',
                        ].join(' ')}
                      >
                        <span className="text-sm font-bold">{variation.name}</span>
                        <span className="text-sm font-black">
                          {Number(variation.price) > 0 ? `+ ${formatCurrency(variation.price)}` : 'Sem acrescimo'}
                        </span>
                      </button>
                    );
                  })}
                </div>
              </section>
            ) : null}

            {product?.additionals?.length ? (
              <section className="mt-6">
                <h2 className="text-base font-black text-slate-950">Adicionais</h2>
                <div className="mt-3 grid gap-3">
                  {product.additionals.map((additional) => {
                    const active = selectedAdditionalIds.includes(additional.id);
                    return (
                      <button
                        key={additional.id}
                        type="button"
                        onClick={() => toggleAdditional(additional)}
                        className={[
                          'flex items-center justify-between rounded-[1.2rem] border px-4 py-4 text-left transition',
                          active ? 'border-amber-400 bg-amber-50 text-slate-950' : 'border-slate-200 bg-slate-50 text-slate-900',
                        ].join(' ')}
                      >
                        <span className="text-sm font-bold">{additional.name}</span>
                        <span className="text-sm font-black">+ {formatCurrency(additional.price)}</span>
                      </button>
                    );
                  })}
                </div>
              </section>
            ) : null}

            <section className="mt-6 rounded-[1.4rem] border border-slate-200 p-4">
              <label className="grid gap-2">
                <span className="text-sm font-black text-slate-900">Observacao</span>
                <textarea
                  value={notes}
                  onChange={(event) => setNotes(event.target.value)}
                  placeholder="Ex.: sem cebola"
                  className="min-h-24 rounded-[1rem] border border-slate-200 bg-slate-50 px-4 py-3 text-sm outline-none"
                />
              </label>
            </section>
          </section>

          <aside className="rounded-[2rem] bg-white p-5 shadow-[0_14px_40px_rgba(15,23,42,0.06)]">
            <p className="text-xs font-black uppercase tracking-[0.2em] text-slate-400">Seu item</p>
            <div className="mt-4 rounded-[1.4rem] bg-slate-50 p-4">
              <p className="text-lg font-black text-slate-950">{product?.name ?? 'Produto'}</p>
              {selectedVariation ? (
                <p className="mt-2 text-sm text-slate-600">Variacao: {selectedVariation.name}</p>
              ) : null}
              {selectedAdditionals.length ? (
                <p className="mt-2 text-sm text-slate-600">
                  Adicionais: {selectedAdditionals.map((additional) => additional.name).join(', ')}
                </p>
              ) : null}
            </div>

            <div className="mt-4 rounded-[1.4rem] bg-slate-50 p-4">
              <p className="text-sm font-black text-slate-900">Quantidade</p>
              <div className="mt-3 flex items-center gap-3">
                <button
                  type="button"
                  onClick={() => setQuantity((current) => Math.max(1, current - 1))}
                  className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-slate-200 bg-white text-lg font-black"
                >
                  -
                </button>
                <span className="min-w-10 text-center text-lg font-black">{quantity}</span>
                <button
                  type="button"
                  onClick={() => setQuantity((current) => current + 1)}
                  className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-slate-200 bg-white text-lg font-black"
                >
                  +
                </button>
              </div>
            </div>

            <div className="mt-4 rounded-[1.4rem] bg-slate-950 p-4 text-white">
              <div className="flex items-center justify-between text-sm">
                <span>Unitario</span>
                <strong>{formatCurrency(unitPrice || product?.price)}</strong>
              </div>
              <div className="mt-3 flex items-center justify-between text-base font-black">
                <span>Total do item</span>
                <strong>{formatCurrency(lineTotal)}</strong>
              </div>
            </div>

            <div className="mt-5 flex flex-col gap-3">
              <button
                type="button"
                onClick={addToCart}
                className="inline-flex min-h-[3.2rem] items-center justify-center rounded-full bg-slate-950 px-4 text-xs font-black uppercase tracking-[0.18em] text-white"
              >
                Adicionar ao carrinho
              </button>
              <Link
                href="/public-order"
                className="inline-flex min-h-[3.2rem] 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"
              >
                Voltar ao cardapio
              </Link>
            </div>
          </aside>
        </div>
      </div>
    </main>
  );
}

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