import { useQuery } from '@tanstack/react-query';
import { precioDual, type Restaurante, type Categoria, type Producto } from '@gustito/shared';
import { supabase } from '../lib/supabase';

// Vista de solo lectura de la tienda tal como la vera el cliente.
// Comparte la query ['menu', id] con el editor, asi se actualiza al instante.
export default function TiendaPreview({ restaurante: rest }: { restaurante: Restaurante }) {
  const q = useQuery({
    queryKey: ['menu', rest.id],
    queryFn: async () => {
      const [cats, prods] = await Promise.all([
        supabase.from('categorias').select('*').eq('restaurante_id', rest.id).order('orden'),
        supabase.from('productos').select('*').eq('restaurante_id', rest.id).order('orden'),
      ]);
      return {
        cats: (cats.data ?? []) as unknown as Categoria[],
        prods: (prods.data ?? []) as unknown as Producto[],
      };
    },
  });
  const cats = q.data?.cats ?? [];
  const prods = q.data?.prods ?? [];
  const catsConItems = cats.filter((c) => prods.some((p) => p.categoria_id === c.id));

  return (
    <div className="bg-noche h-full overflow-y-auto no-scrollbar text-left">
      <div className="h-24 relative bg-gradient-to-br from-marca to-marca-oscuro">
        {rest.portada_url && (
          <img src={rest.portada_url} className="absolute inset-0 h-full w-full object-cover" alt="" />
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-black/40 to-transparent" />
      </div>
      <div className="px-3 -mt-7 relative">
        <div className="w-14 h-14 rounded-xl ring-4 ring-crema bg-superficie shadow-tarjeta overflow-hidden grid place-items-center text-xl">
          {rest.logo_url ? (
            <img src={rest.logo_url} className="w-full h-full object-cover" alt="" />
          ) : (
            '🍽️'
          )}
        </div>
        <h1 className="text-base font-extrabold mt-1.5 leading-tight">{rest.nombre}</h1>
        {rest.descripcion && <p className="text-[11px] text-niebla line-clamp-2">{rest.descripcion}</p>}
        <div className="flex flex-wrap gap-1.5 mt-2">
          <span
            className={`text-[10px] font-bold px-2 py-0.5 rounded-full ${
              rest.abierto ? 'bg-green-100 text-green-700' : 'bg-white/10 text-niebla'
            }`}
          >
            {rest.abierto ? '● Abierto' : 'Cerrado'}
          </span>
          {rest.hace_delivery && (
            <span className="text-[10px] font-semibold px-2 py-0.5 rounded-full bg-dorado/15 text-dorado">
              Delivery
            </span>
          )}
        </div>
      </div>

      <div className="px-3 pb-6">
        {catsConItems.length === 0 && (
          <p className="text-center text-niebla text-xs py-12">Tu menu aparecera aqui</p>
        )}
        {catsConItems.map((cat) => (
          <section key={cat.id} className="mt-4">
            <h2 className="text-sm font-extrabold text-white mb-1.5">{cat.nombre}</h2>
            <div className="space-y-1.5">
              {prods
                .filter((p) => p.categoria_id === cat.id)
                .map((p) => (
                  <div
                    key={p.id}
                    className={`flex gap-2 bg-superficie rounded-xl p-2 shadow-tarjeta ${p.disponible ? '' : 'opacity-60'}`}
                  >
                    <div className="w-11 h-11 rounded-lg bg-dorado/15 overflow-hidden grid place-items-center text-base shrink-0">
                      {p.foto_url ? (
                        <img src={p.foto_url} className="w-full h-full object-cover" alt="" />
                      ) : (
                        '🍽️'
                      )}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-bold text-white leading-tight truncate">{p.nombre}</p>
                      <p className="text-[11px] font-extrabold text-dorado mt-0.5">
                        {precioDual(p.precio_usd, rest.tasa_bs)}
                      </p>
                    </div>
                    {p.disponible ? (
                      <div className="w-6 h-6 rounded-full bg-dorado text-noche grid place-items-center text-sm self-end">
                        +
                      </div>
                    ) : (
                      <span className="text-[10px] text-niebla self-end">Agotado</span>
                    )}
                  </div>
                ))}
            </div>
          </section>
        ))}
      </div>
    </div>
  );
}

export function PhoneFrame({ children }: { children: React.ReactNode }) {
  return (
    <div className="w-[300px] h-[600px] rounded-[2.2rem] bg-stone-900 p-2.5 shadow-2xl mx-auto">
      <div className="relative w-full h-full rounded-[1.7rem] overflow-hidden bg-noche">
        <div className="absolute top-0 inset-x-0 z-10 flex justify-center pointer-events-none">
          <div className="w-20 h-4 bg-stone-900 rounded-b-xl" />
        </div>
        {children}
      </div>
    </div>
  );
}
