import { useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import {
  RUBROS,
  ESTADOS_VE,
  precioDual,
  estadoTienda,
  type DirectorioNegocio,
  type Restaurante,
} from '@gustito/shared';
import { Icono } from '@gustito/shared/iconos';
import { supabase } from '../lib/supabase';
import Entrar from './Entrar';

// Sitio principal de la marca (landing de gustitoxpress.app).
const SITIO_PRINCIPAL = import.meta.env.PROD ? 'https://gustitoxpress.app' : 'http://localhost:5174';

type Coord = { lat: number; lng: number };

function distanciaKm(a: Coord, b: Coord): number {
  const R = 6371;
  const toRad = (d: number) => (d * Math.PI) / 180;
  const dLat = toRad(b.lat - a.lat);
  const dLng = toRad(b.lng - a.lng);
  const x =
    Math.sin(dLat / 2) ** 2 +
    Math.cos(toRad(a.lat)) * Math.cos(toRad(b.lat)) * Math.sin(dLng / 2) ** 2;
  return 2 * R * Math.asin(Math.sqrt(x));
}

function Glifo({ className = 'h-5 w-5' }: { className?: string }) {
  return (
    <svg viewBox="0 0 512 512" className={className} aria-hidden>
      <circle cx="256" cy="256" r="150" fill="none" stroke="currentColor" strokeWidth="34" />
      <g fill="currentColor" transform="rotate(-32 256 256)">
        <rect x="245" y="214" width="22" height="150" rx="11" />
        <rect x="236" y="152" width="8" height="66" rx="4" />
        <rect x="252" y="152" width="8" height="66" rx="4" />
        <rect x="268" y="152" width="8" height="66" rx="4" />
        <rect x="236" y="208" width="40" height="14" rx="7" />
      </g>
      <g fill="currentColor" transform="rotate(32 256 256)">
        <rect x="245" y="202" width="22" height="162" rx="11" />
        <ellipse cx="256" cy="174" rx="27" ry="38" />
      </g>
    </svg>
  );
}

export default function Directorio() {
  const [rubro, setRubro] = useState<string | null>(null);
  const [estado, setEstado] = useState('');
  const [municipio, setMunicipio] = useState('');
  const [q, setQ] = useState('');
  const [pos, setPos] = useState<Coord | null>(null);
  const [buscandoPos, setBuscandoPos] = useState(false);
  const [mostrarEntrar, setMostrarEntrar] = useState(false);

  const { data, isLoading, error } = useQuery({
    queryKey: ['directorio'],
    queryFn: async () => {
      const { data, error } = await supabase.rpc('directorio');
      if (error) throw error;
      const negocios = (data as unknown as DirectorioNegocio[]) ?? [];
      // El RPC devuelve el switch manual; sobre-escribimos con el estado real
      // segun el horario (misma logica que la tienda) para que la vitrina no
      // muestre "Abierto" fuera de hora.
      if (negocios.length) {
        const slugs = negocios.map((n) => n.slug);
        const { data: hs } = await supabase
          .from('restaurantes')
          .select('slug,abierto,horarios')
          .in('slug', slugs);
        const filas = (hs ?? []) as unknown as Pick<Restaurante, 'slug' | 'abierto' | 'horarios'>[];
        const mapa = new Map(filas.map((r) => [r.slug, r]));
        for (const n of negocios) {
          const r = mapa.get(n.slug);
          if (r) n.abierto = estadoTienda(r).abierto;
        }
      }
      return negocios;
    },
  });

  function cercaDeMi() {
    if (!('geolocation' in navigator)) return;
    setBuscandoPos(true);
    navigator.geolocation.getCurrentPosition(
      (p) => {
        setPos({ lat: p.coords.latitude, lng: p.coords.longitude });
        setBuscandoPos(false);
      },
      () => setBuscandoPos(false),
      { enableHighAccuracy: true, timeout: 10000 },
    );
  }

  const negocios = useMemo(() => {
    let list = (data ?? []).map((n) => ({
      ...n,
      _d:
        pos && n.latitud != null && n.longitud != null
          ? distanciaKm(pos, { lat: n.latitud, lng: n.longitud })
          : null,
    }));
    if (rubro) list = list.filter((n) => (n.rubros ?? []).includes(rubro));
    if (estado) list = list.filter((n) => n.estado_ve === estado);
    if (municipio) list = list.filter((n) => n.municipio === municipio);
    if (q.trim()) {
      const t = q.trim().toLowerCase();
      list = list.filter((n) =>
        `${n.nombre} ${n.municipio ?? ''} ${(n.rubros ?? []).join(' ')} ${n.estado_ve ?? ''}`.toLowerCase().includes(t),
      );
    }
    if (pos) list.sort((a, b) => (a._d ?? Infinity) - (b._d ?? Infinity));
    return list;
  }, [data, rubro, estado, municipio, q, pos]);

  const rubrosDisponibles = useMemo(() => {
    const s = new Set((data ?? []).flatMap((n) => n.rubros ?? []));
    return RUBROS.filter((r) => s.has(r));
  }, [data]);

  const municipiosDisponibles = useMemo(() => {
    const s = new Set(
      (data ?? [])
        .filter((n) => !estado || n.estado_ve === estado)
        .map((n) => n.municipio)
        .filter(Boolean) as string[],
    );
    return [...s].sort((a, b) => a.localeCompare(b));
  }, [data, estado]);

  const selectCls =
    'w-full rounded-xl border border-white/10 bg-superficie-2 px-3 py-3 text-sm font-semibold text-white outline-none focus:border-dorado disabled:opacity-50';

  return (
    <div className="min-h-screen overflow-x-hidden bg-noche pb-20 text-white">
      {/* Barra de marca */}
      <div className="sticky top-0 z-40 border-b border-white/10 bg-noche/85 backdrop-blur">
        <div className="mx-auto flex max-w-6xl items-center justify-between px-4 py-3">
          <a href={SITIO_PRINCIPAL} className="flex items-center gap-2" aria-label="Ir a Gustito Xpress">
            <span className="grid h-8 w-8 place-items-center rounded-lg bg-dorado text-noche">
              <Glifo className="h-4 w-4" />
            </span>
            <span className="text-base font-extrabold tracking-tight text-white">
              Gustito <span className="text-dorado">Xpress</span>
            </span>
          </a>
          <button
            onClick={() => setMostrarEntrar(true)}
            className="text-sm font-semibold text-niebla hover:text-dorado"
          >
            Iniciar sesión
          </button>
        </div>
      </div>

      {/* Hero */}
      <header className="relative overflow-hidden bg-superficie-2 px-4 pb-12 pt-9">
        <div className="pointer-events-none absolute -top-10 right-0 h-56 w-56 rounded-full bg-dorado/15 blur-3xl" />
        <div className="relative mx-auto max-w-6xl">
          <span className="inline-flex items-center gap-2 rounded-full bg-dorado/15 px-3 py-1 text-xs font-bold text-dorado ring-1 ring-dorado/25">
            <Icono nombre="chispa" className="h-3.5 w-3.5" />
            Pide ya
          </span>
          <h1 className="mt-4 max-w-2xl text-2xl font-extrabold leading-tight tracking-tight text-white sm:text-4xl">
            Ubica el <span className="text-dorado">gustito</span> que te quieras dar hoy
          </h1>
          <p className="mt-1.5 max-w-lg text-sm text-niebla sm:text-base">
            Elige que comer y descubre los negocios cerca de ti.
          </p>
        </div>
      </header>

      {/* Buscador flotante */}
      <div className="mx-auto -mt-6 max-w-6xl px-4">
        <div className="rounded-2xl bg-superficie p-3 shadow-2xl ring-1 ring-white/10">
          <div className="flex flex-col gap-2 sm:flex-row sm:items-stretch">
            <div className="relative sm:min-w-0 sm:flex-1">
              <svg
                className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-niebla"
                viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"
              >
                <circle cx="11" cy="11" r="7" />
                <path d="M21 21l-4-4" />
              </svg>
              <input
                className="w-full rounded-xl border border-white/10 bg-superficie-2 py-3 pl-9 pr-3 text-sm text-white placeholder:text-white/40 outline-none focus:border-dorado"
                placeholder="Busca un negocio o comida"
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
            </div>
            <div className="grid grid-cols-2 gap-2 sm:flex sm:shrink-0">
              <select
                className={`${selectCls} sm:w-40`}
                value={estado}
                onChange={(e) => {
                  setEstado(e.target.value);
                  setMunicipio('');
                }}
              >
                <option value="">Estado</option>
                {ESTADOS_VE.map((e) => (
                  <option key={e} value={e}>
                    {e}
                  </option>
                ))}
              </select>
              <select
                className={`${selectCls} sm:w-40`}
                value={municipio}
                disabled={municipiosDisponibles.length === 0}
                onChange={(e) => setMunicipio(e.target.value)}
              >
                <option value="">Municipio</option>
                {municipiosDisponibles.map((m) => (
                  <option key={m} value={m}>
                    {m}
                  </option>
                ))}
              </select>
            </div>
            <button
              onClick={cercaDeMi}
              className="flex items-center justify-center gap-2 whitespace-nowrap rounded-xl bg-dorado px-5 py-2.5 text-sm font-bold text-noche sm:shrink-0"
            >
              <Icono nombre={pos ? 'check' : 'pin'} className="h-4 w-4" />
              {buscandoPos ? 'Ubicando...' : pos ? 'Cerca' : 'Cerca de mi'}
            </button>
          </div>
        </div>
      </div>

      {/* Chips de rubro */}
      {rubrosDisponibles.length > 0 && (
        <div className="mx-auto max-w-6xl px-4">
          <div className="no-scrollbar mt-4 flex gap-2 overflow-x-auto pb-1">
            <Chip activo={rubro === null} onClick={() => setRubro(null)}>
              Todos
            </Chip>
            {rubrosDisponibles.map((r) => (
              <Chip key={r} activo={rubro === r} onClick={() => setRubro(r)}>
                {r}
              </Chip>
            ))}
          </div>
        </div>
      )}

      {/* Resultados */}
      <main className="mx-auto max-w-6xl px-4 pt-6">
        {isLoading && <p className="py-12 text-center text-niebla">Cargando negocios...</p>}
        {error && <p className="py-12 text-center text-red-400">{(error as Error).message}</p>}
        {!isLoading && !error && negocios.length === 0 && (
          <p className="py-16 text-center text-niebla">
            {(data ?? []).length === 0
              ? 'Pronto veras aqui los negocios de tu zona.'
              : 'No hay negocios que coincidan. Prueba con otro filtro.'}
          </p>
        )}
        {!isLoading && negocios.length > 0 && (
          <p className="mb-4 text-sm font-semibold text-niebla">
            {negocios.length} negocio{negocios.length === 1 ? '' : 's'}
            {estado ? ` en ${municipio ? municipio + ', ' : ''}${estado}` : ''}
          </p>
        )}
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {negocios.map((n) => (
            <Link
              key={n.slug}
              to={`/${n.slug}`}
              className="flex flex-col overflow-hidden rounded-2xl bg-superficie ring-1 ring-white/10 transition hover:-translate-y-0.5 hover:ring-dorado/30"
            >
              <div className="relative grid h-28 place-items-center overflow-hidden bg-gradient-to-br from-superficie-2 to-noche">
                {n.portada_url ? (
                  <img src={n.portada_url} alt="" className="absolute inset-0 h-full w-full object-cover" />
                ) : (
                  <div className="grid h-14 w-14 place-items-center overflow-hidden rounded-2xl bg-dorado/10 text-3xl text-dorado ring-1 ring-dorado/25">
                    {n.logo_url ? (
                      <img src={n.logo_url} alt="" className="h-full w-full object-cover" />
                    ) : (
                      <Icono nombre="plato" className="h-7 w-7" />
                    )}
                  </div>
                )}
                <span
                  className={`absolute right-2 top-2 rounded-full px-2 py-0.5 text-[11px] font-bold ${
                    n.abierto ? 'bg-verde text-white' : 'bg-white/10 text-niebla'
                  }`}
                >
                  {n.abierto ? 'Abierto' : 'Cerrado'}
                </span>
              </div>
              <div className="flex flex-1 items-start gap-3 p-4">
                {n.portada_url && (
                  <div className="-mt-9 grid h-14 w-14 shrink-0 place-items-center overflow-hidden rounded-2xl bg-superficie text-2xl ring-2 ring-superficie">
                    {n.logo_url ? (
                      <img src={n.logo_url} alt="" className="h-full w-full object-cover" />
                    ) : (
                      <Icono nombre="plato" className="h-7 w-7" />
                    )}
                  </div>
                )}
                <div className="min-w-0 flex-1">
                  <p className="truncate font-extrabold text-white">{n.nombre}</p>
                  <p className="truncate text-xs text-niebla">
                    {[(n.rubros ?? []).slice(0, 2).join(', '), n.municipio, n.estado_ve].filter(Boolean).join(' · ') || 'Comida'}
                  </p>
                  <div className="mt-2 flex flex-wrap items-center gap-2 text-xs">
                    {n.precio_desde != null && (
                      <span className="font-bold text-dorado">Desde {precioDual(n.precio_desde, n.tasa_bs)}</span>
                    )}
                    {n._d != null && (
                      <span className="rounded-full bg-white/8 px-2 py-0.5 font-semibold text-niebla">
                        {n._d < 1 ? `${Math.round(n._d * 1000)} m` : `${n._d.toFixed(1)} km`}
                      </span>
                    )}
                    {n.hace_delivery && (
                      <span
                        className={`rounded-full px-2 py-0.5 font-semibold ${
                          n.costo_delivery_usd === 0 ? 'bg-verde/15 text-verde' : 'bg-dorado/15 text-dorado'
                        }`}
                      >
                        {n.costo_delivery_usd === 0 ? 'Delivery gratis' : 'Delivery'}
                      </span>
                    )}
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </main>

      {mostrarEntrar && <Entrar onCerrar={() => setMostrarEntrar(false)} />}
    </div>
  );
}

function Chip({ activo, onClick, children }: { activo: boolean; onClick: () => void; children: React.ReactNode }) {
  return (
    <button
      onClick={onClick}
      className={`shrink-0 whitespace-nowrap rounded-full px-3.5 py-1.5 text-sm font-semibold transition ${
        activo ? 'bg-dorado text-noche shadow-glow' : 'bg-superficie-2 text-niebla ring-1 ring-white/10'
      }`}
    >
      {children}
    </button>
  );
}
