import React, { useState, useEffect } from 'react';
import { 
  View, 
  Text, 
  StyleSheet, 
  ScrollView, 
  TouchableOpacity, 
  ActivityIndicator, 
  Alert,
  TextInput,
  Dimensions,
  KeyboardAvoidingView,
  Platform,
  Image,
  Modal
} from 'react-native';
import { useLocalSearchParams, useRouter, Stack } from 'expo-router';
import { Colors } from '../../../constants/theme';
import api from '../../../services/api';
import { Ionicons } from '@expo/vector-icons';
import { Calendar, LocaleConfig } from 'react-native-calendars';
import { LinearGradient } from 'expo-linear-gradient';
import Animated, { FadeInDown, FadeInUp, FadeInRight } from 'react-native-reanimated';
import GlassCard from '@/components/common/GlassCard';
import * as ImagePicker from 'expo-image-picker';
import { BlurView } from 'expo-blur';
import * as Haptics from 'expo-haptics';

// Configure Portuguese for the calendar
LocaleConfig.locales['pt'] = {
  monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
  monthNamesShort: ['Jan.','Fev.','Mar.','Abr.','Mai.','Jun.','Jul.','Ago.','Set.','Out.','Nov.','Dez.'],
  dayNames: ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'],
  dayNamesShort: ['Dom.','Seg.','Ter.','Qua.','Qui.','Sex.','Sáb.'],
  today: 'Hoje'
};
LocaleConfig.defaultLocale = 'pt';

const { width } = Dimensions.get('window');

export default function BookingScreen() {
  const { serviceId } = useLocalSearchParams();
  const router = useRouter();
  
  const [step, setStep] = useState(1);
  const [loading, setLoading] = useState(false);
  const [serviceInfo, setServiceInfo] = useState<any>(null);
  const [showImageModal, setShowImageModal] = useState(false);

  // Hooks de Permissão Oficiais (Ativos e Suaves)
  const [cameraPermission, requestCameraPermission] = ImagePicker.useCameraPermissions();
  const [libraryPermission, requestLibraryPermission] = ImagePicker.useMediaLibraryPermissions();
  
  // Step 1 Data
  const [formData, setFormData] = useState({
    note: '',
    first_name: '',
    last_name: '',
    email: '',
    phone: '',
    address: '',
    city: '',
    state: '',
    postal: ''
  });

  // Step 2 Data
  const [selectedDate, setSelectedDate] = useState('');
  const [selectedSlotTime, setSelectedSlotTime] = useState<string | null>(null);

  // Images Data
  const [images, setImages] = useState<string[]>([]);

  const STATIC_SLOTS = [
    { id: '1', slot: '08:00' },
    { id: '2', slot: '09:00' },
    { id: '3', slot: '10:00' },
    { id: '4', slot: '11:00' },
    { id: '5', slot: '12:00' },
    { id: '6', slot: '13:00' },
    { id: '7', slot: '14:00' },
    { id: '8', slot: '15:00' },
    { id: '9', slot: '16:00' },
    { id: '10', slot: '17:00' },
    { id: '11', slot: '18:00' },
  ];

  // Success State
  const [isSuccess, setIsSuccess] = useState(false);

  // Fetch Service Basic Info and User Profile
  useEffect(() => {
    const fetchInitialData = async () => {
      setLoading(true);
      try {
        // 1. Fetch Service Info
        const serviceResponse = await api.get(`/servicedetail/${serviceId}?is_mobile=yes`);
        const data = serviceResponse.data.data;
        setServiceInfo(data);
        
        // 2. Fetch User Profile for pre-filling
        const userResponse = await api.get('/Userdetail');
        if (userResponse.data?.user) {
          const u = userResponse.data.user;
          // Split name if first_name/last_name not directly available
          const nameParts = u.name ? u.name.split(' ') : ['', ''];
          
          setFormData(prev => ({
            ...prev,
            first_name: u.first_name || nameParts[0] || '',
            last_name: u.last_name || nameParts.slice(1).join(' ') || '',
            email: u.email || '',
            phone: u.mobile_number || '',
            address: u.address || '',
            city: u.city || '',
            state: u.state || '',
            postal: u.postal_code || ''
          }));
        }
      } catch (error) {
        console.error('Error fetching initial data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchInitialData();
  }, [serviceId]);

  const pickImages = async () => {
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
    setShowImageModal(true);
  };

  const handleSelectImageSource = async (source: 'camera' | 'library') => {
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
    
    try {
      let isGranted = false;
      
      // Verificamos e pedimos permissão se necessário
      if (source === 'camera') {
        if (cameraPermission?.status !== 'granted') {
          const result = await requestCameraPermission();
          isGranted = result.granted;
        } else {
          isGranted = true;
        }
      } else {
        if (libraryPermission?.status !== 'granted') {
          const result = await requestLibraryPermission();
          isGranted = result.granted;
        } else {
          isGranted = true;
        }
      }

      // 1. Fechamos a aba IMEDIATAMENTE após a escolha/permissão
      setShowImageModal(false);

      // 2. Se temos permissão, abrimos o seletor com um pequeno delay suave
      if (isGranted) {
        setTimeout(async () => {
          const options: ImagePicker.ImagePickerOptions = {
            quality: 0.7,
            allowsEditing: true,
            mediaTypes: ImagePicker.MediaTypeOptions.Images,
            allowsMultipleSelection: source === 'library',
          };

          const result = source === 'camera'
            ? await ImagePicker.launchCameraAsync(options)
            : await ImagePicker.launchImageLibraryAsync(options);

          if (!result.canceled) {
            const newUris = result.assets.map(a => a.uri);
            setImages(prev => [...prev, ...newUris]);
          }
        }, 500);
      }
      // Se NÃO for permitido, a função termina aqui. Não há alertas de erro.
    } catch (error) {
      console.error('Erro na seleção:', error);
      setShowImageModal(false);
    }
  };

  const removeImage = (uri: string) => {
    setImages(prev => prev.filter(img => img !== uri));
  };

  const handleDateSelect = (date: any) => {
    setSelectedDate(date.dateString);
    setSelectedSlotTime(null);
  };

  const handleRequestQuote = async () => {
    if (!selectedDate || !selectedSlotTime) {
      Alert.alert('Atenção', 'Por favor selecione uma data e um horário.');
      return;
    }

    setLoading(true);
    try {
      const [year, month, day] = selectedDate.split('-');
      const formattedDate = `${day}-${month}-${year}`;

      const payload = {
        ...formData,
        phone_number: formData.phone || '000000000', // Ensure phone is not null
        postal: formData.postal || '0000',
        service_id: serviceId,
        booking_date: formattedDate,
        from_time: selectedSlotTime,
        to_time: selectedSlotTime ? `${(parseInt(selectedSlotTime.split(':')[0]) + 1).toString().padStart(2, '0')}:${selectedSlotTime.split(':')[1]}` : null,
        slot_id: 0,
        payment_type: 'quote',
        is_mobile: 'yes',
        tax_amount: 0,
        sub_amount: 0,
        total_amount: 0
      };

      const formDataToSend = new FormData();
      
      // Append basic fields
      Object.keys(payload).forEach(key => {
        const value = (payload as any)[key];
        if (value !== null && value !== undefined) {
          formDataToSend.append(key, typeof value === 'object' ? JSON.stringify(value) : value.toString());
        }
      });

      // Append images
      images.forEach((uri, index) => {
        const fileName = uri.split('/').pop() || `image_${index}.jpg`;
        const match = /\.(\w+)$/.exec(fileName);
        const type = match ? `image/${match[1]}` : `image`;
        
        formDataToSend.append('images[]', {
          uri: Platform.OS === 'ios' ? uri.replace('file://', '') : uri,
          name: fileName,
          type,
        } as any);
      });

      const response = await api.post('/user/payment', formDataToSend, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });
      
      if (response.data) {
        setIsSuccess(true);
      }
    } catch (error: any) {
      console.error('Booking Error:', error);
      if (error.response) {
        console.error('Data:', error.response.data);
        console.error('Status:', error.response.status);
        Alert.alert('Erro do Servidor', `Falha (${error.response.status}): ${JSON.stringify(error.response.data)}`);
      } else if (error.request) {
        console.error('Request:', error.request);
        Alert.alert('Erro de Rede', 'Não foi possível contactar o servidor. Verifique a sua ligação.');
      } else {
        console.error('Error Message:', error.message);
        Alert.alert('Erro', error.message);
      }
    } finally {
      setLoading(false);
    }
  };

  if (isSuccess) {
    const [year, month, day] = selectedDate.split('-');
    const displayDate = `${day}/${month}/${year}`;

    return (
      <View style={styles.successContainer}>
        <Stack.Screen options={{ headerShown: false }} />
        <LinearGradient
          colors={[Colors.light.primary, '#1a1a1a']}
          style={StyleSheet.absoluteFill}
        />
        
        <Animated.View 
          entering={FadeInDown.springify().damping(15)} 
          style={styles.successCard}
        >
          <View style={styles.successIconWrapper}>
            <View style={styles.successIconOuter}>
              <View style={styles.successIconInner}>
                <Ionicons name="checkmark" size={50} color="#FFF" />
              </View>
            </View>
          </View>

          <Text style={styles.successTitle}>Pedido Enviado!</Text>
          <Text style={styles.successSubtitle}>
            O seu pedido de orçamento para <Text style={{ fontWeight: '800', color: '#1a1a1a' }}>{serviceInfo?.title}</Text> foi enviado com sucesso.
          </Text>

          <View style={styles.summaryCard}>
             <View style={styles.summaryRow}>
                <Ionicons name="calendar-outline" size={18} color={Colors.light.primary} />
                <Text style={styles.summaryLabel}>Data:</Text>
                <Text style={styles.summaryValue}>{displayDate}</Text>
             </View>
             <View style={[styles.summaryRow, { borderBottomWidth: 0 }]}>
                <Ionicons name="time-outline" size={18} color={Colors.light.primary} />
                <Text style={styles.summaryLabel}>Horário:</Text>
                <Text style={styles.summaryValue}>{selectedSlotTime}h</Text>
             </View>
          </View>

          <Text style={styles.infoText}>
            O profissional irá analisar o seu pedido e responder em breve com um orçamento detalhado.
          </Text>
          
          <View style={styles.successActions}>
            <TouchableOpacity 
              style={styles.doneButton}
              onPress={() => router.replace('/(drawer)/(tabs)/bookings')}
            >
              <LinearGradient
                colors={Colors.light.gradients.primary as [string, string]}
                start={{x: 0, y: 0}}
                end={{x: 1, y: 0}}
                style={styles.doneButtonGradient}
              >
                <Text style={styles.doneButtonText}>Ver Meus Pedidos</Text>
                <Ionicons name="arrow-forward" size={18} color="#FFF" />
              </LinearGradient>
            </TouchableOpacity>

            <TouchableOpacity 
              style={styles.homeButton}
              onPress={() => router.replace('/(drawer)/(tabs)')}
            >
              <Text style={styles.homeButtonText}>Voltar ao Início</Text>
            </TouchableOpacity>
          </View>
        </Animated.View>
      </View>
    );
  }

  return (
    <KeyboardAvoidingView 
      style={{ flex: 1 }} 
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
      keyboardVerticalOffset={100}
    >
      <View style={styles.container}>
        <Stack.Screen options={{ title: step === 1 ? 'Pedido de Orçamento' : (step === 2 ? 'Dados de Contacto' : 'Agendar Data') }} />
        
        {/* Step Indicator */}
        <View style={styles.stepHeader}>
          <View style={styles.stepTrack}>
            <View style={[styles.stepProgress, { width: step === 1 ? '33%' : (step === 2 ? '66%' : '100%') }]} />
          </View>
          <View style={styles.stepLabels}>
            <Text style={[styles.stepLabel, step >= 1 && styles.activeStepLabel]}>Descrição</Text>
            <Text style={[styles.stepLabel, step >= 2 && styles.activeStepLabel]}>Contacto</Text>
            <Text style={[styles.stepLabel, step >= 3 && styles.activeStepLabel]}>Agendamento</Text>
          </View>
        </View>

        <ScrollView contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
          {step === 1 && (
            <Animated.View entering={FadeInDown} style={styles.formContainer}>
               <Text style={styles.sectionTitle}>Explique o problema</Text>
               <Text style={styles.sectionSubtitle}>Dê o máximo de detalhes para um orçamento preciso.</Text>
               
               <TextInput
                 style={styles.noteInput}
                 placeholder="Descreva aqui o que precisa de reparação..."
                 multiline
                 numberOfLines={6}
                 textAlignVertical="top"
                 value={formData.note}
                 onChangeText={(txt) => setFormData({...formData, note: txt})}
               />

               <Text style={[styles.sectionTitle, { marginTop: 24 }]}>Imagens do Serviço (Opcional)</Text>
               <Text style={styles.sectionSubtitle}>Adicione fotos do problema para ajudar no orçamento.</Text>
               
               <View style={styles.imageSelectorContainer}>
                  <TouchableOpacity style={styles.addImageButton} onPress={() => setShowImageModal(true)}>
                    <Ionicons name="camera-outline" size={30} color={Colors.light.primary} />
                    <Text style={styles.addImageText}>Adicionar</Text>
                  </TouchableOpacity>
                  
                  {images.map((uri, index) => (
                    <View key={index} style={styles.imageWrapper}>
                      <Image source={{ uri }} style={styles.selectedImage} />
                      <TouchableOpacity 
                        style={styles.removeImageButton}
                        onPress={() => removeImage(uri)}
                      >
                        <Ionicons name="close-circle" size={24} color={Colors.light.error || '#FF5252'} />
                      </TouchableOpacity>
                    </View>
                  ))}
               </View>
               <View style={{ height: 100 }} />
            </Animated.View>
          )}

          {step === 2 && (
            <Animated.View entering={FadeInRight} style={styles.formContainer}>
               <Text style={styles.sectionTitle}>Dados de Contacto</Text>
               <Text style={styles.sectionSubtitle}>Confirme os seus dados para podermos contactá-lo.</Text>
               <View style={styles.inputGroup}>
                 <View style={styles.inputHalf}>
                   <Text style={styles.inputLabel}>Nome</Text>
                   <TextInput 
                     style={styles.textInput} 
                     placeholder="Nome"
                     value={formData.first_name}
                     onChangeText={(t) => setFormData({...formData, first_name: t})}
                   />
                 </View>
                 <View style={styles.inputHalf}>
                   <Text style={styles.inputLabel}>Apelido</Text>
                   <TextInput 
                     style={styles.textInput} 
                     placeholder="Apelido"
                     value={formData.last_name}
                     onChangeText={(t) => setFormData({...formData, last_name: t})}
                   />
                 </View>
               </View>

               <Text style={styles.inputLabel}>Email</Text>
               <TextInput 
                 style={styles.textInput} 
                 placeholder="seu@email.com"
                 keyboardType="email-address"
                 autoCapitalize="none"
                 value={formData.email}
                 onChangeText={(t) => setFormData({...formData, email: t})}
               />

               <Text style={styles.inputLabel}>Telefone</Text>
               <TextInput 
                 style={styles.textInput} 
                 placeholder="+244 ..."
                 keyboardType="phone-pad"
                 value={formData.phone}
                 onChangeText={(t) => setFormData({...formData, phone: t})}
               />

               <Text style={styles.inputLabel}>Morada</Text>
               <TextInput 
                 style={styles.textInput} 
                 placeholder="Rua, Número..."
                 value={formData.address}
                 onChangeText={(t) => setFormData({...formData, address: t})}
               />

               <View style={styles.inputGroup}>
                 <View style={styles.inputHalf}>
                   <Text style={styles.inputLabel}>Cidade</Text>
                   <TextInput 
                     style={styles.textInput} 
                     placeholder="Cidade"
                     value={formData.city}
                     onChangeText={(t) => setFormData({...formData, city: t})}
                   />
                 </View>
                 <View style={styles.inputHalf}>
                   <Text style={styles.inputLabel}>Província</Text>
                   <TextInput 
                     style={styles.textInput} 
                     placeholder="Luanda"
                     value={formData.state}
                     onChangeText={(t) => setFormData({...formData, state: t})}
                   />
                 </View>
               </View>
               <View style={{ height: 100 }} />
            </Animated.View>
          )}

          {step === 3 && (
            <Animated.View entering={FadeInRight} style={styles.formContainer}>
               <Text style={styles.sectionTitle}>Quando deseja o serviço?</Text>
               <Text style={styles.sectionSubtitle}>Selecione um dia no calendário.</Text>
               
               <View style={styles.calendarWrapper}>
                  <Calendar 
                    onDayPress={handleDateSelect}
                    markedDates={{ [selectedDate]: { selected: true, selectedColor: Colors.light.primary } }}
                    theme={{
                      todayTextColor: Colors.light.primary,
                      arrowColor: Colors.light.primary,
                      selectedDayBackgroundColor: Colors.light.primary,
                      textDayFontSize: 14,
                      textMonthFontSize: 16,
                      textDayHeaderFontSize: 12
                    }}
                    minDate={new Date().toISOString().split('T')[0]}
                  />
                </View>

                {selectedDate ? (
                  <View style={{ marginTop: 24 }}>
                    <Text style={styles.sectionTitle}>Escolha o Horário</Text>
                    <View style={styles.slotsGrid}>
                      {STATIC_SLOTS.map((item) => (
                        <TouchableOpacity 
                          key={item.id} 
                          style={[
                            styles.slotCard, 
                            selectedSlotTime === item.slot && styles.activeSlotCard
                          ]}
                          onPress={() => setSelectedSlotTime(item.slot)}
                        >
                          <Ionicons 
                            name="time-outline" 
                            size={18} 
                            color={selectedSlotTime === item.slot ? '#FFF' : Colors.light.primary} 
                          />
                          <Text style={[
                            styles.slotText,
                            selectedSlotTime === item.slot && styles.activeSlotText
                          ]}>
                            {item.slot}
                          </Text>
                        </TouchableOpacity>
                      ))}
                    </View>
                  </View>
                ) : null}
               
               <View style={{ height: 120 }} />
            </Animated.View>
          )}
        </ScrollView>

        <View style={styles.footer}>
          {step > 1 && (
            <TouchableOpacity 
              style={styles.backButton} 
              onPress={() => setStep(step - 1)}
              disabled={loading}
            >
              <Ionicons name="chevron-back" size={24} color={Colors.light.textMuted} />
            </TouchableOpacity>
          )}
          
          <TouchableOpacity 
            style={[styles.primaryButton, { flex: 1 }]} 
            onPress={step < 3 ? () => setStep(step + 1) : handleRequestQuote}
            disabled={loading || (step === 1 && !formData.note)}
          >
            <LinearGradient
              colors={Colors.light.gradients.primary as [string, string]}
              style={[styles.gradientButton, (step === 1 && !formData.note) && { opacity: 0.6 }]}
            >
              <Text style={styles.buttonText}>
                {loading ? 'Processando...' : (step === 3 ? 'Solicitar Orçamento' : 'Próximo Passo')}
              </Text>
              {!loading && <Ionicons name="arrow-forward" size={18} color="#FFF" />}
            </LinearGradient>
          </TouchableOpacity>
        </View>

        </View>

        {/* Premium Image Source Bottom Sheet (Nativo e Estável) */}
        <Modal
          visible={showImageModal}
          transparent={true}
          animationType="slide"
          onRequestClose={() => setShowImageModal(false)}
        >
          <TouchableOpacity 
            style={styles.modalOverlay} 
            activeOpacity={1} 
            onPress={() => setShowImageModal(false)}
          >
            <BlurView intensity={20} tint="dark" style={StyleSheet.absoluteFill} />
            <View style={styles.bottomSheetContainer}>
              <Animated.View entering={FadeInUp.duration(300)} style={styles.bottomSheet}>
                <View style={styles.sheetHandle} />
                <Text style={styles.sheetTitle}>Adicionar Imagem</Text>
                
                <TouchableOpacity 
                   style={styles.sourceButton} 
                   onPress={() => handleSelectImageSource('camera')}
                >
                  <View style={[styles.sourceIcon, { backgroundColor: Colors.light.primary + '15' }]}>
                    <Ionicons name="camera" size={30} color={Colors.light.primary} />
                  </View>
                  <View style={styles.sourceTextContent}>
                    <Text style={styles.sourceTitle}>Tirar Foto</Text>
                    <Text style={styles.sourceSubtitle}>Use a câmera para captar o problema agora</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color="#CCC" />
                </TouchableOpacity>

                <TouchableOpacity 
                   style={styles.sourceButton} 
                   onPress={() => handleSelectImageSource('library')}
                >
                  <View style={[styles.sourceIcon, { backgroundColor: '#4CAF5015' }]}>
                    <Ionicons name="images" size={30} color="#4CAF50" />
                  </View>
                  <View style={styles.sourceTextContent}>
                    <Text style={styles.sourceTitle}>Escolher da Galeria</Text>
                    <Text style={styles.sourceSubtitle}>Selecione fotos que já tirou anteriormente</Text>
                  </View>
                  <Ionicons name="chevron-forward" size={20} color="#CCC" />
                </TouchableOpacity>

                <TouchableOpacity 
                  style={styles.sheetCancelBtn}
                  onPress={() => setShowImageModal(false)}
                >
                  <Text style={styles.sheetCancelLabel}>Cancelar</Text>
                </TouchableOpacity>
              </Animated.View>
            </View>
          </TouchableOpacity>
        </Modal>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: '#F8F9FA' },
  scrollContent: { padding: 20 },
  stepHeader: { paddingHorizontal: 20, paddingTop: 10, marginBottom: 20 },
  stepTrack: { height: 4, backgroundColor: '#E0E0E0', borderRadius: 2, overflow: 'hidden' },
  stepProgress: { height: '100%', backgroundColor: Colors.light.primary },
  stepLabels: { flexDirection: 'row', justifyContent: 'space-between', marginTop: 8 },
  stepLabel: { fontSize: 12, color: '#999', fontWeight: '600' },
  activeStepLabel: { color: Colors.light.primary },
  formContainer: { flex: 1 },
  sectionTitle: { fontSize: 20, fontWeight: '800', color: Colors.light.text, marginBottom: 6 },
  sectionSubtitle: { fontSize: 14, color: Colors.light.textMuted, marginBottom: 16 },
  imageSelectorContainer: {
    marginTop: 16,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-between',
    gap: 16,
  },
  addImageButton: {
    width: (width - 56) / 2,
    height: (width - 56) / 2,
    borderRadius: 24,
    borderWidth: 2,
    borderColor: Colors.light.primary,
    borderStyle: 'dashed',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(23, 102, 175, 0.05)',
  },
  addImageText: {
    fontSize: 14,
    fontWeight: '800',
    color: Colors.light.primary,
    marginTop: 8,
  },
  imageWrapper: {
    width: (width - 56) / 2,
    height: (width - 56) / 2,
    borderRadius: 24,
    backgroundColor: '#FFF',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 8,
    elevation: 3,
    position: 'relative',
  },
  selectedImage: {
    width: '100%',
    height: '100%',
    borderRadius: 24,
  },
  removeImageButton: {
    position: 'absolute',
    top: -10,
    right: -10,
    backgroundColor: '#FFF',
    borderRadius: 14,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.2,
    shadowRadius: 4,
    elevation: 5,
    zIndex: 10,
    padding: 2,
  },
  noteInput: {
    backgroundColor: '#FFF',
    borderWidth: 1.5,
    borderColor: '#E8E8E8',
    borderRadius: 16,
    padding: 16,
    fontSize: 16,
    color: '#333',
    minHeight: 120,
  },
  inputGroup: { flexDirection: 'row', gap: 12, marginBottom: 16 },
  inputHalf: { flex: 1 },
  inputLabel: { fontSize: 14, fontWeight: '700', color: Colors.light.text, marginBottom: 8, marginTop: 12 },
  textInput: {
    backgroundColor: '#FFF',
    borderWidth: 1.5,
    borderColor: '#E8E8E8',
    borderRadius: 12,
    padding: 12,
    fontSize: 15,
  },
  calendarWrapper: {
    backgroundColor: '#FFF',
    borderRadius: 20,
    overflow: 'hidden',
    borderWidth: 1,
    borderColor: '#EEE',
    marginTop: 10,
  },
  slotsGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 10, marginTop: 12 },
  slotCard: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 6,
    paddingVertical: 12,
    paddingHorizontal: 16,
    borderRadius: 12,
    backgroundColor: '#FFF',
    borderWidth: 1.5,
    borderColor: '#E8E8E8',
    width: (width - 60) / 2,
  },
  activeSlotCard: {
    backgroundColor: Colors.light.primary,
    borderColor: Colors.light.primary,
  },
  slotText: { fontSize: 14, fontWeight: '700', color: '#555' },
  activeSlotText: { color: '#FFF' },
  emptyText: { color: '#999', fontStyle: 'italic', marginTop: 10 },
  footer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    padding: 20,
    paddingBottom: Platform.OS === 'ios' ? 40 : 20,
    backgroundColor: '#FFF',
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    borderTopWidth: 1,
    borderTopColor: '#EEE',
  },
  backButton: {
    width: 56,
    height: 56,
    borderRadius: 18,
    borderWidth: 1.5,
    borderColor: '#EEE',
    justifyContent: 'center',
    alignItems: 'center',
  },
  primaryButton: { height: 56 },
  gradientButton: {
    flex: 1,
    borderRadius: 18,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 10,
  },
  buttonText: { color: '#FFF', fontSize: 16, fontWeight: '800' },
  successContainer: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    padding: 24 
  },
  successCard: {
    backgroundColor: 'rgba(255, 255, 255, 0.95)',
    borderRadius: 36,
    padding: 32,
    width: '100%',
    alignItems: 'center',
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 20 },
    shadowOpacity: 0.15,
    shadowRadius: 30,
    elevation: 15,
  },
  successIconWrapper: {
    marginBottom: 24,
  },
  successIconOuter: {
    width: 100,
    height: 100,
    borderRadius: 50,
    backgroundColor: 'rgba(76, 175, 80, 0.15)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  successIconInner: {
    width: 76,
    height: 76,
    borderRadius: 38,
    backgroundColor: '#4CAF50',
    justifyContent: 'center',
    alignItems: 'center',
    shadowColor: '#4CAF50',
    shadowOffset: { width: 0, height: 8 },
    shadowOpacity: 0.4,
    shadowRadius: 12,
  },
  successTitle: { 
    fontSize: 28, 
    fontWeight: '900', 
    color: '#1a1a1a', 
    marginBottom: 12,
    textAlign: 'center'
  },
  successSubtitle: { 
    fontSize: 15, 
    color: '#666', 
    textAlign: 'center', 
    lineHeight: 22, 
    marginBottom: 24 
  },
  summaryCard: {
    backgroundColor: '#F8F9FA',
    borderRadius: 20,
    padding: 16,
    width: '100%',
    marginBottom: 24,
    borderWidth: 1,
    borderColor: '#F0F1F2',
  },
  summaryRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#EEE',
    gap: 10,
  },
  summaryLabel: {
    fontSize: 14,
    color: '#888',
    fontWeight: '600',
    flex: 1,
  },
  summaryValue: {
    fontSize: 14,
    color: '#1a1a1a',
    fontWeight: '800',
  },
  infoText: {
    fontSize: 13,
    color: '#999',
    textAlign: 'center',
    lineHeight: 18,
    marginBottom: 32,
    paddingHorizontal: 10,
  },
  successActions: {
    width: '100%',
    gap: 12,
  },
  doneButton: {
    width: '100%',
    height: 60,
    borderRadius: 20,
    overflow: 'hidden',
  },
  doneButtonGradient: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    gap: 10,
  },
  doneButtonText: { 
    color: '#FFF', 
    fontSize: 16, 
    fontWeight: '800' 
  },
  homeButton: {
    width: '100%',
    height: 60,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent',
  },
  homeButtonText: {
    color: '#888',
    fontSize: 15,
    fontWeight: '700',
  },
  modalOverlay: {
    flex: 1,
    justifyContent: 'flex-end',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  bottomSheetContainer: {
    width: '100%',
    alignItems: 'center',
  },
  bottomSheet: {
    width: '100%',
    backgroundColor: '#FFF',
    borderTopLeftRadius: 32,
    borderTopRightRadius: 32,
    padding: 24,
    paddingBottom: Platform.OS === 'ios' ? 50 : 30,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: -10 },
    shadowOpacity: 0.1,
    shadowRadius: 20,
    elevation: 25,
  },
  sheetHandle: {
    width: 40,
    height: 5,
    backgroundColor: '#E8E8E8',
    borderRadius: 3,
    alignSelf: 'center',
    marginBottom: 20,
  },
  sheetTitle: {
    fontSize: 20,
    fontWeight: '800',
    color: '#1a1a1a',
    marginBottom: 24,
    textAlign: 'center',
  },
  sourceButton: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 16,
    backgroundColor: '#F8F9FA',
    borderRadius: 20,
    marginBottom: 12,
    borderWidth: 1,
    borderColor: '#F0F1F2',
  },
  sourceIcon: {
    width: 56,
    height: 56,
    borderRadius: 18,
    justifyContent: 'center',
    alignItems: 'center',
  },
  sourceTextContent: {
    flex: 1,
    marginLeft: 16,
  },
  sourceTitle: {
    fontSize: 16,
    fontWeight: '700',
    color: '#1a1a1a',
    marginBottom: 2,
  },
  sourceSubtitle: {
    fontSize: 12,
    color: '#888',
  },
  sheetCancelBtn: {
    marginTop: 12,
    height: 56,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 20,
  },
  sheetCancelLabel: {
    fontSize: 16,
    fontWeight: '700',
    color: '#FF5252',
  },
});
