/**
 * @file Explore.tsx
 * @description View de Exploração de barbearias na versão Web.
 * Consome do estado global (`useApp`) a lista consolidada das "shops" populadas
 * pela base de dados e aplica filtros do lado do cliente baseados na query, tipo e ordenação.
 */
import { useMemo, useState } from 'react';
import { ShopCard } from '../components/ShopCard';
import { Card } from '../components/ui/card';
import { Chip } from '../components/ui/chip';
import { Input } from '../components/ui/input';
import { useApp } from '../context/AppContext';
import { Search, Star, ListFilter, ChevronDown } from 'lucide-react';
import { Button } from '../components/ui/button';

export default function Explore() {
  const { shops } = useApp();

  // Estados para manter as seleções de filtragem
  const [query, setQuery] = useState('');
  const [filter, setFilter] = useState<'todas' | 'top'>('todas');
  const [sortBy, setSortBy] = useState<'avaliacao' | 'servicos'>('avaliacao');

  /**
   * Deriva a lista de Shops tratada a partir do conjunto mestre global.
   * Só recalcula quando os raw `shops` ou os critérios de pesquisa se alteram.
   */
  const filtered = useMemo(() => {
    const normalized = query.trim().toLowerCase();

    // Regra 1: Combinação livre por correspondência parcial textual (Nome/Morada)
    const matchesQuery = (name: string, address: string) =>
      !normalized || name.toLowerCase().includes(normalized) || address.toLowerCase().includes(normalized);

    // Regra 2: Restrições de Chip
    const passesFilter = (shop: (typeof shops)[number]) => {
      if (filter === 'top') return (shop.rating || 0) >= 4.7;
      return true;
    };

    const sorted = [...shops]
      .filter((shop) => matchesQuery(shop.name, shop.address || ''))
      .filter(passesFilter)
      .sort((a, b) => {
        if (sortBy === 'avaliacao') return (b.rating || 0) - (a.rating || 0);

        // Critério por defeito ou quebra de empate: Avaliação descendente
        if (b.rating !== a.rating) return (b.rating || 0) - (a.rating || 0);
        return (b.services || []).length - (a.services || []).length;
      });

    return sorted;
  }, [shops, query, filter, sortBy]);

  return (
    <div className="max-w-6xl mx-auto space-y-6 sm:space-y-10 py-4 sm:py-6">
      <section className="space-y-4 text-center md:text-left">
        <div className="flex flex-col gap-4 md:flex-row md:items-end md:justify-between">
          <div className="space-y-1">
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-100 text-indigo-700 text-[10px] font-black uppercase tracking-widest mb-2">
              <Star size={10} fill="currentColor" />
              <span>As Nossas Barbearias</span>
            </div>
            <h1 className="text-2xl sm:text-4xl md:text-5xl font-black text-slate-900 tracking-tighter uppercase italic">
              Ver <span className="text-indigo-600">Barbearias</span>
            </h1>
            <p className="text-slate-500 font-medium max-w-md">Descubra barbearias exclusivas e reserve o seu próximo corte em segundos.</p>
          </div>
          <div className="hidden md:block text-sm font-bold text-slate-400 uppercase tracking-widest">
             <span className="text-slate-900">{filtered.length}</span> Espaços Disponíveis
          </div>
        </div>
      </section>

      <div className="grid gap-8">
        <Card className="p-1.5 sm:p-2 border-none glass-card rounded-2xl sm:rounded-[2.5rem] shadow-2xl shadow-slate-200/50">
          <div className="flex flex-col md:flex-row items-center gap-2 p-1">
            <div className="relative flex-1 w-full">
              <Search size={20} className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-400" />
              <Input
                value={query}
                onChange={(e) => setQuery(e.target.value)}
                placeholder="Pesquisar por nome ou endereço..."
                className="h-12 sm:h-14 pl-12 sm:pl-14 pr-4 sm:pr-6 bg-transparent border-none text-base sm:text-lg font-medium focus:ring-0 placeholder:text-slate-400"
              />
            </div>
            
            <div className="h-10 w-px bg-slate-200 hidden md:block" />

            <div className="px-2 sm:px-4 py-2 w-full md:w-auto flex-shrink-0">
              <div className="relative group flex items-center h-10 sm:h-12 w-full md:w-auto rounded-xl sm:rounded-2xl bg-slate-100 hover:bg-slate-200/80 px-3 sm:px-4 transition-all focus-within:ring-2 focus-within:ring-indigo-500/30 shadow-sm cursor-pointer">
                <ListFilter size={18} className="text-slate-400 group-hover:text-indigo-500 transition-colors pointer-events-none shrink-0" />
                
                <span className="flex-1 text-center px-2 text-xs sm:text-sm font-bold text-slate-700 pointer-events-none whitespace-nowrap">
                  {filter === 'top' ? 'Top Avaliadas' : sortBy === 'servicos' ? 'Mais Serviços' : 'Todas (Melhor avaliação)'}
                </span>

                <ChevronDown size={16} className="text-slate-400 group-hover:text-indigo-500 transition-colors pointer-events-none shrink-0" />

                <select
                  value={`${filter}-${sortBy}`}
                  onChange={(e) => {
                    const [newFilter, newSort] = e.target.value.split('-');
                    setFilter(newFilter as 'todas' | 'top');
                    setSortBy(newSort as 'avaliacao' | 'servicos');
                  }}
                  className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                >
                  <option value="todas-avaliacao">Todas (Melhor avaliação)</option>
                  <option value="top-avaliacao">Top Avaliadas</option>
                  <option value="todas-servicos">Mais Serviços</option>
                </select>
              </div>
            </div>
          </div>
        </Card>

        {!useApp().shopsReady ? (
          <div className="py-24 text-center">
            <div className="inline-block w-12 h-12 border-4 border-slate-200 border-t-indigo-600 rounded-full animate-spin mb-4" />
            <p className="text-slate-500 font-bold uppercase tracking-widest text-xs">A carregar espaços...</p>
          </div>
        ) : filtered.length === 0 ? (
          <Card className="p-16 text-center space-y-4 border-none glass-card rounded-[2rem]">
            <div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto text-slate-400">
               <Search size={32} />
            </div>
            <div className="space-y-1">
              <p className="text-2xl font-black text-slate-900 tracking-tight">Nenhuma barbearia encontrada</p>
              <p className="text-slate-500 font-medium">Tente ajustar o termo de pesquisa ou os filtros ativos.</p>
            </div>
            <Button variant="ghost" onClick={() => {setQuery(''); setFilter('todas');}} className="font-bold text-indigo-600 hover:text-indigo-700">
              Limpar Tudo
            </Button>
          </Card>
        ) : (
          <div className="grid sm:grid-cols-2 lg:grid-cols-2 gap-4 sm:gap-8 lg:gap-10">
            {filtered.map((shop) => (
              <ShopCard key={shop.id} shop={shop} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}


