/**
 * @file ShopDetails.tsx
 * @description Vista de Detalhes de uma Barbearia na Web.
 * Apresenta informações do estabelecimento (foto, avaliação, mapa),
 * listagens de Serviços e Produtos disponíveis em Tabs.
 */
import { Link, useParams } from 'react-router-dom';
import { useMemo, useState } from 'react';
import { Tabs } from '../components/ui/tabs';
import { ServiceList } from '../components/ServiceList';
import { ProductList } from '../components/ProductList';
import { BarberList } from '../components/BarberList';
import { ShopDetailsTab } from '../components/ShopDetailsTab';
import { Button } from '../components/ui/button';
import { useApp } from '../context/AppContext';
import { Dialog } from '../components/ui/dialog';
import { Heart, MapPin, Maximize2, Star } from 'lucide-react';

export default function ShopDetails() {
  const { id } = useParams<{ id: string }>();
  const { shops, shopsReady, addToCart, toggleFavorite, isFavorite } = useApp();
  const shop = useMemo(() => shops.find((s) => s.id === id), [shops, id]);
  const [tab, setTab] = useState<'servicos' | 'produtos' | 'barbeiros' | 'detalhes'>('servicos');
  const [imageOpen, setImageOpen] = useState(false);

  if (!shopsReady || (shops.length === 0 && !shop)) {
    return (
      <div className="py-20 text-center animate-pulse">
        <div className="inline-block w-10 h-10 border-4 border-slate-200 border-t-indigo-600 rounded-full animate-spin mb-4" />
        <p className="text-sm font-black text-slate-500 uppercase tracking-widest italic">A carregar detalhes...</p>
      </div>
    );
  }

  if (!shop) {
    return (
      <div className="py-32 text-center space-y-6">
        <div className="w-20 h-20 bg-slate-100 rounded-[2rem] flex items-center justify-center mx-auto text-slate-300">
          <Star size={40} />
        </div>
        <div className="space-y-2">
          <h2 className="text-2xl font-black text-slate-900 uppercase italic tracking-tighter">Barbearia não encontrada</h2>
          <p className="text-slate-500 font-medium italic">O espaço que procura pode ter sido removido ou o link está incorreto.</p>
        </div>
        <Button asChild className="h-12 px-8 bg-slate-900 text-indigo-400 font-black rounded-2xl uppercase tracking-widest text-[10px] italic">
          <Link to="/explorar">Explorar outros espaços</Link>
        </Button>
      </div>
    );
  }
  const mapUrl = `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(
    `${shop.name} ${shop.address}`
  )}`;

  return (
    <div className="max-w-6xl mx-auto space-y-6 sm:space-y-8 py-2 sm:py-4">
      <div className="relative overflow-hidden rounded-2xl sm:rounded-[2.5rem] border-none shadow-2xl shadow-slate-200/50">
        {shop.imageUrl ? (
          <img src={shop.imageUrl} alt={`Foto de ${shop.name}`} className="h-48 sm:h-64 w-full object-cover md:h-96 transition-transform duration-1000 hover:scale-105" />
        ) : (
          <div className="h-48 sm:h-64 w-full obsidian-gradient md:h-96" />
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-slate-950/80 via-slate-950/20 to-transparent" />
        
        <div className="absolute right-3 top-3 sm:right-6 sm:top-6 flex gap-2 sm:gap-3">
          <a
            href={mapUrl}
            target="_blank"
            rel="noreferrer"
            className="w-10 h-10 sm:w-12 sm:h-12 flex items-center justify-center rounded-xl sm:rounded-2xl bg-white/90 backdrop-blur-md text-slate-900 shadow-xl hover:bg-white hover:scale-110 transition-all"
            title="Ver no Mapa"
          >
            <MapPin size={18} className="sm:hidden" />
            <MapPin size={22} className="hidden sm:block" />
          </a>
          <button
            onClick={() => toggleFavorite(shop.id)}
            className="w-10 h-10 sm:w-12 sm:h-12 flex items-center justify-center rounded-xl sm:rounded-2xl bg-white/90 backdrop-blur-md text-slate-900 shadow-xl hover:bg-white hover:scale-110 transition-all font-bold"
            type="button"
          >
            <Heart
              size={18}
              className={`sm:hidden ${isFavorite(shop.id) ? 'fill-rose-500 text-rose-500' : 'text-slate-900'}`}
            />
            <Heart
              size={22}
              className={`hidden sm:block ${isFavorite(shop.id) ? 'fill-rose-500 text-rose-500' : 'text-slate-900'}`}
            />
          </button>
          <button
            onClick={() => setImageOpen(true)}
            className="w-10 h-10 sm:w-12 sm:h-12 flex items-center justify-center rounded-xl sm:rounded-2xl bg-white/90 backdrop-blur-md text-slate-900 shadow-xl hover:bg-white hover:scale-110 transition-all"
            type="button"
          >
            <Maximize2 size={18} className="sm:hidden" />
            <Maximize2 size={22} className="hidden sm:block" />
          </button>
        </div>

        <div className="absolute bottom-4 left-4 sm:bottom-10 sm:left-10 space-y-2 sm:space-y-3 max-w-[calc(100%-2rem)]">
          <div className="flex items-center gap-2 bg-slate-900/40 backdrop-blur-md border border-white/20 w-fit px-2 sm:px-3 py-1 rounded-full">
            <Star size={12} className="fill-indigo-500 text-indigo-500 sm:hidden" />
            <Star size={14} className="fill-indigo-500 text-indigo-500 hidden sm:block" />
            <span className="text-white text-[10px] sm:text-xs font-black tracking-widest">{(shop.rating || 0).toFixed(1)} EXCELENTE</span>
          </div>
          <h1 className="text-2xl sm:text-4xl md:text-5xl font-black text-white tracking-tighter truncate">{shop.name}</h1>
          <div className="flex items-center gap-2 text-white/90">
             <MapPin size={14} className="text-indigo-600 shrink-0" />
             <p className="text-sm sm:text-base font-medium truncate">{shop.address}</p>
          </div>
        </div>
      </div>

      <div className="grid gap-4 sm:gap-8">
        <div className="flex flex-col gap-3 sm:gap-4 bg-white/50 backdrop-blur-sm p-1.5 sm:p-2 rounded-2xl sm:rounded-[2rem] border border-white/50">
          <div className="w-full max-w-[100vw] overflow-hidden">
            <Tabs
              tabs={[
                { id: 'servicos', label: 'Serviços' },
                { id: 'barbeiros', label: 'Barbeiros' },
                { id: 'produtos', label: 'Produtos' },
                { id: 'detalhes', label: 'Detalhes' },
              ]}
              active={tab}
              onChange={(v) => setTab(v as typeof tab)}
              className="border-none bg-transparent"
            />
          </div>
          <div className="px-3 sm:px-6 py-2 text-[9px] sm:text-xs font-black text-slate-400 uppercase tracking-widest bg-white rounded-xl sm:rounded-2xl border border-slate-100 shadow-sm text-center sm:text-left">
            {(shop.services || []).length} SERVIÇOS · {(shop.barbers || []).length} BARBEIROS
          </div>
        </div>

        <div className="animate-in fade-in slide-in-from-bottom-4 duration-500">
          {tab === 'servicos' ? (
            <ServiceList
              services={shop.services}
              onSelect={(sid) => {
                window.location.href = `/agendar/${shop.id}?service=${sid}`;
              }}
            />
          ) : tab === 'barbeiros' ? (
            <div className="bg-white/30 backdrop-blur-md p-4 sm:p-8 rounded-2xl sm:rounded-[3rem] border border-white/50">
              <BarberList barbers={shop.barbers} />
            </div>
          ) : tab === 'detalhes' ? (
            <div className="bg-white/30 backdrop-blur-md p-4 sm:p-8 rounded-2xl sm:rounded-[3rem] border border-white/50">
              <ShopDetailsTab shop={shop} />
            </div>
          ) : (
            <ProductList products={shop.products} onAdd={(pid) => addToCart({ shopId: shop.id, type: 'product', refId: pid, qty: 1 })} />
          )}
        </div>
      </div>

      <Dialog open={imageOpen} title={shop.name} onClose={() => setImageOpen(false)}>
        {shop.imageUrl ? (
          <img src={shop.imageUrl} alt={`Foto de ${shop.name}`} className="w-full rounded-2xl sm:rounded-[2rem] object-cover shadow-2xl" />
        ) : (
          <div className="h-96 w-full rounded-2xl sm:rounded-[2rem] obsidian-gradient" />
        )}
      </Dialog>
    </div>
  );
}
