import { useNavigate, useParams, useSearchParams, Link } from 'react-router-dom';
import { useMemo, useState, useEffect } from 'react';
import { Card } from '../components/ui/card';
import { Button } from '../components/ui/button';
import { Input } from '../components/ui/input';
import { useApp } from '../context/AppContext';
import { Calendar, Clock, Scissors, User, CheckCircle2, MapPin, ArrowLeft, ArrowRight } from 'lucide-react';
import { currency } from '../lib/format';

export default function Booking() {
  const { id } = useParams<{ id: string }>();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();

  // Extração das ferramentas vitais do Context global da aplicação
  const { shops, shopsReady, createAppointment, user, appointments, waitlists, joinWaitlist } = useApp();

  // Procura a barbearia acedida (com base no URL parameter ':id')
  const shop = useMemo(() => shops.find((s) => s.id === id), [shops, id]);


  // Estados para as escolhas parciais do utilizador
  const [serviceId, setService] = useState(searchParams.get('service') || '');
  const [barberId, setBarber] = useState('');
  const [date, setDate] = useState('');
  const [slot, setSlot] = useState('');
  const [step, setStep] = useState(searchParams.get('service') ? 2 : 1);

  // Sincroniza o serviceId se o parâmetro mudar (ex: navegação interna)
  useEffect(() => {
    const s = searchParams.get('service');
    if (s) {
      setService(s);
      setStep(2);
    }
  }, [searchParams]);

  const selectedService = shop?.services.find((s) => s.id === serviceId);
  const selectedBarber = shop?.barbers.find((b) => b.id === barberId);

  const generateDefaultSlots = (): string[] => {
    const slots: string[] = [];
    for (let hour = 9; hour <= 18; hour++) {
      slots.push(`${hour.toString().padStart(2, '0')}:00`);
    }
    return slots;
  };

  const isShopClosedOnDate = useMemo(() => {
    if (!date || !shop) return false;
    const dateObj = new Date(date + 'T00:00:00');
    const dayOfWeekIndex = dateObj.getDay();
    const ptDays = ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'];
    const dayName = ptDays[dayOfWeekIndex];

    const exception = shop.schedule?.find(s => s.isException && s.date === date);
    if (exception) {
      return exception.closed;
    }

    const defaultDay = shop.schedule?.find(s => s.day === dayName && !s.isException);
    if (defaultDay) {
      return defaultDay.closed;
    }
    
    if (dayName === 'Domingo') return true;
    return false;
  }, [shop?.schedule, date]);

  const processedSlots = useMemo(() => {
    if (!selectedBarber || !date || isShopClosedOnDate) return [];
    const specificSchedule = selectedBarber.schedule?.find((s) => s.day === date);
    let slots = specificSchedule && specificSchedule.slots.length > 0
      ? [...specificSchedule.slots]
      : generateDefaultSlots();

    const bookedSlots = appointments
      .filter((apt) =>
        apt.barberId === barberId &&
        apt.status !== 'cancelado' &&
        apt.date.startsWith(date)
      )
      .map((apt) => {
        const parts = apt.date.split(' ');
        return parts.length > 1 ? parts[1] : '';
      })
      .filter(Boolean);

    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const todayStr = `${year}-${month}-${day}`;
    const isToday = date === todayStr;
    const currentHour = today.getHours();
    const currentMinute = today.getMinutes();

    return slots.map(time => {
      let isPast = false;
      if (isToday) {
        const [h, m] = time.split(':').map(Number);
        if (h < currentHour || (h === currentHour && m <= currentMinute)) {
          isPast = true;
        }
      }
      
      const isBooked = bookedSlots.includes(time) || isPast;
      const waitlistedByMe = user ? waitlists.some(w => w.barberId === barberId && w.date === `${date} ${time}` && w.customerId === user.id && w.status === 'pending') : false;
      return { time, isBooked, waitlistedByMe };
    });
  }, [selectedBarber, date, barberId, appointments, user, waitlists]);

  if (!shopsReady || (shops.length === 0 && !shop)) {
    return (
      <div className="py-32 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 preparar reserva...</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">
          <Calendar size={40} />
        </div>
        <div className="space-y-2">
          <h2 className="text-2xl font-black text-slate-900 uppercase italic tracking-tighter">Espaço não encontrado</h2>
          <p className="text-slate-500 font-medium italic">Não foi possível iniciar o agendamento para este estabelecimento.</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">Voltar ao Explorar</Link>
        </Button>
      </div>
    );
  }

  // Avanço automático por efeito colateral (opcional, mas vamos fazer por clique para ser mais explícito)
  const nextStep = () => setStep((s) => Math.min(s + 1, 4));
  const prevStep = () => setStep((s) => Math.max(s - 1, 1));

  const canSubmit = serviceId && barberId && date && slot && !isShopClosedOnDate;

  const submit = async () => {
    if (!user) {
      navigate('/login');
      return;
    }
    if (!canSubmit) return;
    const appt = await createAppointment({ shopId: shop.id, serviceId, barberId, customerId: user.id, date: `${date} ${slot}` });
    if (appt) {
      navigate('/explorar');
    } else {
      alert('Horário indisponível ou ocorreu um erro a comunicar com o servidor.');
    }
  };

  const steps = [
    { id: 1, label: 'Serviço', icon: Scissors, completed: !!serviceId, active: step === 1 },
    { id: 2, label: 'Barbeiro', icon: User, completed: !!barberId, active: step === 2 },
    { id: 3, label: 'Data', icon: Calendar, completed: !!date, active: step === 3 },
    { id: 4, label: 'Horário', icon: Clock, completed: !!slot, active: step === 4 },
  ];

  return (
    <div className="max-w-4xl mx-auto space-y-6 sm:space-y-10 py-2 sm:py-4 pb-12 sm:pb-20">
      <header className="space-y-4 text-center">
        <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">
          <Calendar size={10} fill="currentColor" />
          <span>Reserva Exclusiva</span>
        </div>
        <div className="space-y-1">
          <h1 className="text-2xl sm:text-4xl md:text-5xl font-black text-slate-900 tracking-tighter uppercase italic">
            Reservar em <span className="text-indigo-600 block md:inline">{shop.name}</span>
          </h1>
          <div className="flex items-center justify-center gap-2 text-slate-500 font-medium">
             <MapPin size={14} className="text-indigo-600" />
             <p className="text-sm">{shop.address}</p>
          </div>
        </div>
      </header>

      {/* Progress Steps - Premium Stepper */}
      <div className="relative">
        <div className="absolute top-1/2 left-0 w-full h-px bg-slate-200 -translate-y-1/2 z-0" />
        <div className="relative flex items-center justify-between z-10 px-4">
          {steps.map((s) => (
            <div key={s.id} className="flex flex-col items-center">
              <button
                onClick={() => {
                  if (s.completed || s.id < step) setStep(s.id);
                }}
                disabled={!s.completed && s.id > step}
                className={`w-10 h-10 sm:w-12 sm:h-12 rounded-xl sm:rounded-2xl flex items-center justify-center border-2 transition-all duration-500 scale-100 active:scale-90 ${
                  s.active
                    ? 'bg-slate-900 border-slate-900 text-indigo-400 shadow-2xl shadow-slate-300 -translate-y-2'
                    : s.completed
                    ? 'bg-indigo-600 border-indigo-600 text-white'
                    : 'bg-white border-slate-200 text-slate-400'
                }`}
              >
                {s.completed && !s.active ? <CheckCircle2 size={20} /> : <s.icon size={20} />}
              </button>
              <div className={`mt-2 sm:mt-3 text-[8px] sm:text-[10px] font-black uppercase tracking-widest ${s.active ? 'text-slate-900' : 'text-slate-400'}`}>
                {s.label}
              </div>
            </div>
          ))}
        </div>
      </div>

      <Card className="p-1.5 sm:p-2 border-none glass-card rounded-2xl sm:rounded-[3rem] shadow-2xl shadow-slate-200/50 overflow-hidden">
        {/* Dynamic Step Content */}
        <div className="p-4 sm:p-8 md:p-12 space-y-6 sm:space-y-10">
          
          {/* Step Back Button */}
          {step > 1 && (
            <Button 
              variant="ghost" 
              onClick={prevStep} 
              className="px-0 h-auto font-black text-[10px] uppercase tracking-[0.2em] text-slate-400 hover:text-slate-900 transition-colors flex items-center gap-2"
            >
              <ArrowLeft size={12} />
              Voltar ao passo anterior
            </Button>
          )}

          {step === 1 && (
            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="space-y-2 text-center md:text-left">
                <h3 className="text-xl sm:text-3xl font-black text-slate-900 tracking-tighter uppercase italic">1. Selecione o <span className="text-indigo-600">Serviço</span></h3>
              </div>
              <div className="grid md:grid-cols-2 gap-6">
                {shop.services.map((s) => (
                  <button
                    key={s.id}
                    onClick={() => {
                      setService(s.id);
                      setStep(2);
                    }}
                    className={`group p-4 sm:p-6 rounded-2xl sm:rounded-[2rem] border-2 text-left transition-all duration-300 flex flex-col gap-3 sm:gap-4 ${
                      serviceId === s.id
                        ? 'border-slate-900 bg-slate-900 text-white shadow-2xl translate-y-[-4px]'
                        : 'border-slate-50 bg-slate-50 hover:border-indigo-200 hover:bg-indigo-50/50'
                    }`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="space-y-1">
                        <div className={`font-black text-xl tracking-tight uppercase italic ${serviceId === s.id ? 'text-indigo-500' : 'text-slate-900 group-hover:text-indigo-600'}`}>
                          {s.name}
                        </div>
                        <div className={`flex items-center gap-2 text-xs font-bold uppercase tracking-widest ${serviceId === s.id ? 'text-slate-400' : 'text-slate-500'}`}>
                          <Clock size={12} />
                          {s.duration} MIN
                        </div>
                      </div>
                      <div className={`text-2xl font-black tracking-tighter px-3 py-1 rounded-xl ${serviceId === s.id ? 'bg-white/10 text-white' : 'bg-white text-slate-900 shadow-sm'}`}>
                        {currency(s.price)}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 2 && (
            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="space-y-2 text-center md:text-left">
                <h3 className="text-xl sm:text-3xl font-black text-slate-900 tracking-tighter uppercase italic">2. Escolha o <span className="text-indigo-600">Barbeiro</span></h3>
              </div>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-6">
                {shop.barbers.map((b) => (
                  <button
                    key={b.id}
                    onClick={() => {
                      setBarber(b.id);
                      setStep(3);
                    }}
                    className={`group p-4 sm:p-6 rounded-2xl sm:rounded-[2.5rem] border-2 text-center transition-all duration-300 flex flex-col items-center gap-3 sm:gap-5 ${
                      barberId === b.id
                        ? 'border-slate-900 bg-slate-900 text-white shadow-2xl translate-y-[-4px]'
                        : 'border-slate-50 bg-slate-50 hover:border-indigo-200 hover:bg-indigo-50/50'
                    }`}
                  >
                    <div className={`w-20 h-20 sm:w-32 sm:h-32 rounded-2xl sm:rounded-[2rem] overflow-hidden border-4 transition-all duration-500 ${barberId === b.id ? 'border-indigo-500 rotate-3' : 'border-white group-hover:border-indigo-100'}`}>
                      {b.imageUrl ? (
                        <img src={b.imageUrl} alt={b.name} className="w-full h-full object-cover" />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center bg-slate-100 text-slate-300">
                          <User size={48} />
                        </div>
                      )}
                    </div>
                    <div className="space-y-1">
                      <p className={`font-black text-lg uppercase italic tracking-tight ${barberId === b.id ? 'text-indigo-500' : 'text-slate-900 group-hover:text-indigo-600'}`}>{b.name}</p>
                      <p className={`text-[10px] font-black uppercase tracking-[0.2em] ${barberId === b.id ? 'text-slate-400' : 'text-slate-400'}`}>
                        {b.specialties[0] || 'Barbeiro'}
                      </p>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          )}

          {step === 3 && (
            <div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="space-y-2 text-center md:text-left">
                <h3 className="text-xl sm:text-3xl font-black text-slate-900 tracking-tighter uppercase italic">3. Escolha a <span className="text-indigo-600">Data</span></h3>
              </div>
              <div className="max-w-md mx-auto space-y-6">
                <div className="flex items-center h-16 bg-slate-50 border-none rounded-2xl px-6 focus-within:ring-2 focus-within:ring-indigo-500/20 transition-all shadow-inner relative overflow-hidden">
                   <Calendar size={20} className="text-indigo-600 mr-4 shrink-0 pointer-events-none" />
                   <span className={`text-base sm:text-lg font-black uppercase tracking-widest pointer-events-none ${date ? 'text-slate-900' : 'text-slate-400'}`}>
                     {date ? new Date(date).toLocaleDateString('pt-PT', { day: 'numeric', month: 'long', year: 'numeric' }) : 'SELECIONAR DATA'}
                   </span>
                   <input
                     type="date"
                     value={date}
                     onChange={(e) => setDate(e.target.value)}
                     min={new Date().toISOString().split('T')[0]}
                     className="absolute inset-0 w-full h-full opacity-0 cursor-pointer m-0 p-0"
                   />
                </div>
                
                {date && (
                   <Button 
                     onClick={() => setStep(4)} 
                     className="w-full h-14 bg-slate-900 text-indigo-400 hover:bg-slate-800 font-black rounded-2xl shadow-xl transition-all uppercase tracking-widest text-xs italic animate-in fade-in slide-in-from-bottom-2"
                   >
                     Continuar <ArrowRight size={14} className="ml-2" />
                   </Button>
                )}
              </div>
            </div>
          )}

          {step === 4 && (
            <div className="space-y-10 animate-in fade-in slide-in-from-bottom-4 duration-500">
              <div className="space-y-2 text-center md:text-left">
                <h3 className="text-xl sm:text-3xl font-black text-slate-900 tracking-tighter uppercase italic">4. Escolha o <span className="text-indigo-600">Horário</span></h3>
              </div>

              <div className="flex flex-col md:flex-row gap-6">
                {/* Left Side: Summary Sidebar */}
                <div className="w-full md:w-80 space-y-4">
                   <div className="p-4 sm:p-6 bg-slate-900 text-white rounded-2xl sm:rounded-[2rem] space-y-4 sm:space-y-6 shadow-xl relative overflow-hidden">
                      <div className="absolute top-0 right-0 w-32 h-32 bg-indigo-500/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
                      <div className="space-y-4 relative z-10">
                         <div className="space-y-1 border-b border-white/10 pb-4">
                            <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Serviço</p>
                            <p className="text-lg font-black uppercase italic tracking-tight">{selectedService?.name}</p>
                            <p className="text-xl font-black text-indigo-500 tracking-tighter">{currency(selectedService?.price || 0)}</p>
                         </div>
                         <div className="space-y-1 border-b border-white/10 pb-4">
                            <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Barbeiro</p>
                            <p className="font-black uppercase italic text-sm">{selectedBarber?.name}</p>
                         </div>
                         <div className="space-y-1 flex items-end justify-between">
                            <div>
                               <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Data</p>
                               <p className="font-black uppercase italic text-sm">
                                  {new Date(date).toLocaleDateString('pt-PT', { day: 'numeric', month: 'long' })}
                               </p>
                            </div>
                            <button onClick={() => setStep(3)} className="text-[10px] font-bold text-indigo-400 hover:text-indigo-300 underline uppercase tracking-widest">
                               Alterar
                            </button>
                         </div>
                      </div>
                   </div>
                </div>

                {/* Right Side: Slots Grid */}
                <div className="flex-1 space-y-6">
                  <div className="space-y-6">
                    {isShopClosedOnDate ? (
                      <div className="py-12 px-6 text-center bg-rose-50 rounded-[2rem] border border-rose-100 flex flex-col items-center gap-4 animate-in fade-in">
                        <p className="text-sm text-rose-600 font-black uppercase tracking-widest italic">
                          O estabelecimento está fechado neste dia.
                        </p>
                        <p className="text-xs text-rose-500 font-medium">
                          Por favor, volte atrás e selecione outra data.
                        </p>
                      </div>
                    ) : processedSlots.some(s => !s.isBooked) ? (
                      <div className="grid grid-cols-3 sm:grid-cols-4 gap-3">
                        {processedSlots.filter(s => !s.isBooked).map((s) => (
                          <button
                            key={s.time}
                            onClick={() => setSlot(s.time)}
                            className={`h-14 rounded-2xl border-2 text-sm font-black tracking-widest transition-all duration-300 ${
                              slot === s.time
                                ? 'border-slate-900 bg-slate-900 text-indigo-400 shadow-xl scale-105 z-10'
                                : 'border-slate-50 bg-slate-50 text-slate-600 hover:border-indigo-200 hover:bg-indigo-50'
                            }`}
                          >
                            {s.time}
                          </button>
                        ))}
                      </div>
                    ) : processedSlots.length > 0 ? (
                      <div className="py-8 px-6 text-center bg-rose-50 rounded-[2rem] border border-rose-100 flex flex-col items-center gap-4">
                        <p className="text-sm text-rose-600 font-black uppercase tracking-widest italic">
                          Todos os horários estão preenchidos para este dia.
                        </p>
                        {user && waitlists.some(w => w.barberId === barberId && w.date === date && w.customerId === user.id && w.status === 'pending') ? (
                          <div className="px-4 py-2 bg-indigo-100 text-indigo-700 rounded-xl text-xs font-bold uppercase tracking-widest">
                            Já estás na lista de espera deste dia!
                          </div>
                        ) : (
                          <Button 
                            onClick={async () => {
                              if (!user) { navigate('/login'); return; }
                              if (!serviceId) { alert('Selecione primeiro o serviço que pretende.'); return; }
                              const ok = await joinWaitlist(shop.id, serviceId, barberId, date);
                              if (ok) alert('Entraste na lista de espera! Serás notificado se houver desistências.');
                            }}
                            disabled={!serviceId}
                            className={`${serviceId ? 'bg-rose-600 hover:bg-rose-700' : 'bg-slate-300 cursor-not-allowed'} text-white font-black rounded-xl uppercase tracking-widest text-[10px] italic h-10 px-6`}
                          >
                            Entrar na Lista de Espera
                          </Button>
                        )}
                      </div>
                    ) : (
                      <div className="col-span-full py-12 text-center bg-indigo-50 rounded-[2rem] border border-indigo-100">
                        <p className="text-sm text-indigo-600 font-black uppercase tracking-widest italic">Selecione primeiro o mestre e a data</p>
                      </div>
                    )}
                  </div>

                  {canSubmit && (
                    <div className="pt-6 animate-in slide-in-from-right-4 duration-500">
                      <Button 
                        onClick={submit} 
                        size="lg" 
                        className="w-full h-16 bg-slate-900 hover:bg-slate-800 text-indigo-400 font-black rounded-2xl shadow-2xl transition-all active:scale-95 uppercase tracking-[0.2em] text-sm italic"
                      >
                        Confirmar Agendamento
                      </Button>
                      <p className="text-center mt-4 text-[10px] font-bold text-slate-400 uppercase tracking-widest">
                         Pagamento realizado após o serviço
                      </p>
                    </div>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      </Card>
    </div>
  );
}
