import React, { useState, useMemo } from 'react';
import { View, Text, StyleSheet, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRoute, useNavigation } from '@react-navigation/native';
import { useApp } from '../context/AppContext';
import { Card } from '../components/ui/Card';
import { Button } from '../components/ui/Button';
import { currency } from '../lib/format';

export default function Booking() {
  const route = useRoute();
  const navigation = useNavigation();
  const { shopId, serviceId: initialServiceId } = route.params as { shopId: string; serviceId?: string };
  const { shops, createAppointment, user, appointments, joinWaitlist } = useApp();

  const shop = useMemo(() => shops.find((s) => s.id === shopId), [shops, shopId]);

  const [step, setStep] = useState(initialServiceId ? 2 : 1);
  const [serviceId, setService] = useState(initialServiceId || '');
  const [barberId, setBarber] = useState('');
  const [date, setDate] = useState(new Date().toISOString().split('T')[0]);
  const [slot, setSlot] = useState('');
  const [reminderMinutes, setReminderMinutes] = useState(60);

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

  const availableDates = useMemo(() => {
    const dates = [];
    const today = new Date();
    for (let i = 0; i < 14; i++) {
      const d = new Date();
      d.setDate(today.getDate() + i);
      dates.push({
        full: d.toISOString().split('T')[0],
        day: d.getDate(),
        weekday: d.toLocaleDateString('pt-PT', { weekday: 'short' }).replace('.', '').toUpperCase(),
      });
    }
    return dates;
  }, []);

  const processedSlots = useMemo(() => {
    if (!selectedBarber || !date) return [];
    const slots = ["09:00", "09:30", "10:00", "10:30", "11:00", "11:30", "12:00", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"];
    const booked = appointments
      .filter(a => a.barberId === barberId && a.status !== 'cancelado' && a.date.startsWith(date))
      .map(a => a.date.split(' ')[1]);
    
    return slots.map(t => ({ time: t, isBooked: booked.includes(t) }));
  }, [selectedBarber, date, barberId, appointments]);

  const submit = async () => {
    if (!user) { navigation.navigate('Login' as never); return; }
    const appt = await createAppointment({
      shopId: shop!.id,
      serviceId,
      barberId,
      customerId: user.id,
      date: `${date} ${slot}`,
      reminderMinutes
    });
    if (appt) {
      Alert.alert('Sucesso', 'O seu agendamento foi confirmado.');
      navigation.navigate('ProfileTab' as never);
    }
  };

  if (!shop) return null;

  return (
    <SafeAreaView style={styles.container}>
      {/* Header Estilizado */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => step > 1 ? setStep(s => s - 1) : navigation.goBack()} style={styles.backBtn}>
          <Text style={styles.backIcon}>←</Text>
        </TouchableOpacity>
        <View style={styles.headerTitleBox}>
          <Text style={styles.headerTitle}>Agendamento</Text>
          <Text style={styles.headerSubtitle}>Etapa {step} de 4</Text>
        </View>
        <View style={{ width: 40 }} />
      </View>

      <ScrollView contentContainerStyle={styles.scrollContent}>
        {step === 1 && (
          <View style={styles.stepBox}>
            <Text style={styles.stepLabel}>Escolha o serviço</Text>
            {shop.services.map(s => (
              <TouchableOpacity key={s.id} onPress={() => { setService(s.id); setStep(2); }}>
                <Card style={[styles.choiceCard, serviceId === s.id && styles.choiceCardActive]}>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.choiceName}>{s.name}</Text>
                    <Text style={styles.choiceMeta}>{s.duration} min</Text>
                  </View>
                  <Text style={styles.choicePrice}>{currency(s.price)}</Text>
                </Card>
              </TouchableOpacity>
            ))}
          </View>
        )}

        {step === 2 && (
          <View style={styles.stepBox}>
            <Text style={styles.stepLabel}>Com quem prefere?</Text>
            {shop.barbers.map(b => (
              <TouchableOpacity key={b.id} onPress={() => { setBarber(b.id); setStep(3); }}>
                <Card style={[styles.choiceCard, barberId === b.id && styles.choiceCardActive]}>
                  <View style={styles.avatarMini}><Text style={styles.avatarTxt}>{b.name.charAt(0)}</Text></View>
                  <View style={{ flex: 1 }}>
                    <Text style={styles.choiceName}>{b.name}</Text>
                    <Text style={styles.choiceMeta}>{b.specialties[0] || 'Profissional'}</Text>
                  </View>
                </Card>
              </TouchableOpacity>
            ))}
          </View>
        )}

        {step === 3 && (
          <View style={styles.stepBox}>
            <Text style={styles.stepLabel}>Escolha o dia</Text>
            <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.dateList}>
              {availableDates.map(d => (
                <TouchableOpacity key={d.full} onPress={() => setDate(d.full)} style={[styles.dateItem, date === d.full && styles.dateItemActive]}>
                  <Text style={[styles.dateWeek, date === d.full && styles.dateTextActive]}>{d.weekday}</Text>
                  <Text style={[styles.dateDay, date === d.full && styles.dateTextActive]}>{d.day}</Text>
                </TouchableOpacity>
              ))}
            </ScrollView>

            <Text style={[styles.stepLabel, { marginTop: 20 }]}>Horários disponíveis</Text>
            <View style={styles.slotsGrid}>
              {processedSlots.map(s => (
                <TouchableOpacity 
                  key={s.time} 
                  disabled={s.isBooked}
                  onPress={() => setSlot(s.time)}
                  style={[styles.slotItem, slot === s.time && styles.slotActive, s.isBooked && styles.slotBooked]}
                >
                  <Text style={[styles.slotText, slot === s.time && styles.slotTextActive, s.isBooked && styles.slotTextBooked]}>
                    {s.time}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>
            
            {slot !== '' && (
              <Button style={{ marginTop: 24 }} onPress={() => setStep(4)}>Continuar</Button>
            )}
          </View>
        )}

        {step === 4 && (
          <View style={styles.stepBox}>
            <Text style={styles.stepLabel}>Confirmar detalhes</Text>
            <Card style={styles.summaryCard}>
              <View style={styles.summaryRow}><Text style={styles.summaryLabel}>Serviço</Text><Text style={styles.summaryValue}>{selectedService?.name}</Text></View>
              <View style={styles.summaryRow}><Text style={styles.summaryLabel}>Barbeiro</Text><Text style={styles.summaryValue}>{selectedBarber?.name}</Text></View>
              <View style={styles.summaryRow}><Text style={styles.summaryLabel}>Data</Text><Text style={styles.summaryValue}>{date}</Text></View>
              <View style={styles.summaryRow}><Text style={styles.summaryLabel}>Hora</Text><Text style={styles.summaryValue}>{slot}</Text></View>
              <View style={styles.divider} />
              <View style={styles.summaryRow}><Text style={styles.summaryLabel}>Total</Text><Text style={styles.summaryTotal}>{currency(selectedService?.price || 0)}</Text></View>
            </Card>

            <Text style={[styles.stepLabel, { marginTop: 24 }]}>Lembrete</Text>
            <View style={styles.notifOptions}>
              {[15, 30, 60, 120].map(m => (
                <TouchableOpacity key={m} onPress={() => setReminderMinutes(m)} style={[styles.notifBtn, reminderMinutes === m && styles.notifBtnActive]}>
                  <Text style={[styles.notifBtnTxt, reminderMinutes === m && styles.notifBtnTxtActive]}>
                    {m >= 60 ? `${m/60}h antes` : `${m}m antes`}
                  </Text>
                </TouchableOpacity>
              ))}
            </View>

            <Button style={{ marginTop: 32 }} onPress={submit}>Confirmar Agendamento</Button>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#0a0a0f',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
    paddingVertical: 10,
  },
  backBtn: {
    width: 40,
    height: 40,
    borderRadius: 12,
    backgroundColor: '#141420',
    alignItems: 'center',
    justifyContent: 'center',
  },
  backIcon: {
    color: '#f8fafc',
    fontSize: 20,
    fontWeight: '700',
  },
  headerTitleBox: {
    alignItems: 'center',
  },
  headerTitle: {
    color: '#f8fafc',
    fontSize: 18,
    fontWeight: '800',
  },
  headerSubtitle: {
    color: '#64748b',
    fontSize: 12,
    fontWeight: '600',
  },
  scrollContent: {
    padding: 20,
    paddingBottom: 40,
  },
  stepBox: {
    gap: 12,
  },
  stepLabel: {
    color: '#94a3b8',
    fontSize: 12,
    fontWeight: '800',
    textTransform: 'uppercase',
    letterSpacing: 1,
    marginBottom: 8,
  },
  choiceCard: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    gap: 14,
    borderWidth: 1.5,
    borderColor: 'transparent',
  },
  choiceCardActive: {
    borderColor: '#6366f1',
    backgroundColor: 'rgba(99,102,241,0.05)',
  },
  choiceName: {
    color: '#f8fafc',
    fontSize: 16,
    fontWeight: '700',
  },
  choiceMeta: {
    color: '#64748b',
    fontSize: 13,
  },
  choicePrice: {
    color: '#f8fafc',
    fontSize: 16,
    fontWeight: '800',
  },
  avatarMini: {
    width: 44,
    height: 44,
    borderRadius: 14,
    backgroundColor: '#1c1c2e',
    alignItems: 'center',
    justifyContent: 'center',
  },
  avatarTxt: {
    color: '#6366f1',
    fontSize: 18,
    fontWeight: '900',
  },
  dateList: {
    gap: 10,
  },
  dateItem: {
    width: 64,
    height: 80,
    borderRadius: 16,
    backgroundColor: '#141420',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.06)',
  },
  dateItemActive: {
    backgroundColor: '#6366f1',
    borderColor: '#6366f1',
  },
  dateWeek: {
    color: '#475569',
    fontSize: 10,
    fontWeight: '800',
  },
  dateDay: {
    color: '#f8fafc',
    fontSize: 20,
    fontWeight: '900',
    marginTop: 4,
  },
  dateTextActive: {
    color: '#fff',
  },
  slotsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 10,
  },
  slotItem: {
    width: '22.5%',
    height: 44,
    borderRadius: 12,
    backgroundColor: '#141420',
    alignItems: 'center',
    justifyContent: 'center',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.06)',
  },
  slotActive: {
    backgroundColor: '#6366f1',
    borderColor: '#6366f1',
  },
  slotBooked: {
    opacity: 0.2,
  },
  slotText: {
    color: '#94a3b8',
    fontSize: 14,
    fontWeight: '700',
  },
  slotTextActive: {
    color: '#fff',
  },
  slotTextBooked: {
    textDecorationLine: 'line-through',
  },
  summaryCard: {
    padding: 20,
    gap: 12,
  },
  summaryRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  summaryLabel: {
    color: '#64748b',
    fontSize: 14,
  },
  summaryValue: {
    color: '#f8fafc',
    fontSize: 14,
    fontWeight: '700',
  },
  divider: {
    height: 1,
    backgroundColor: 'rgba(255,255,255,0.06)',
    marginVertical: 4,
  },
  summaryTotal: {
    color: '#a5b4fc',
    fontSize: 22,
    fontWeight: '900',
  },
  notifOptions: {
    flexDirection: 'row',
    gap: 10,
  },
  notifBtn: {
    flex: 1,
    paddingVertical: 12,
    borderRadius: 12,
    backgroundColor: '#141420',
    alignItems: 'center',
    borderWidth: 1,
    borderColor: 'rgba(255,255,255,0.06)',
  },
  notifBtnActive: {
    backgroundColor: 'rgba(99,102,241,0.15)',
    borderColor: '#6366f1',
  },
  notifBtnTxt: {
    color: '#64748b',
    fontSize: 12,
    fontWeight: '700',
  },
  notifBtnTxtActive: {
    color: '#a5b4fc',
  },
});
