import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Switch,
  FlatList,
  Modal,
  Pressable,
} from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import type { RouteProp } from '@react-navigation/native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card, Button, Input } from '../../components/ui';
import { useScheduleStore } from '../../stores/schedule.store';
import { clientsService } from '../../services/clients';
import { scheduleService } from '../../services/schedule';
import type { Client } from '../../types/client';
import type {
  CreateTrainingDto,
  ServiceSummary,
  RoomSummary,
  TimeSlot,
} from '../../types/training';
import type { ScheduleStackParamList } from './types';

type CreateRouteProp = RouteProp<ScheduleStackParamList, 'CreateTraining'>;

const DURATION_OPTIONS = [30, 45, 60, 90, 120];
const REPEAT_WEEKS_OPTIONS = Array.from({ length: 11 }, (_, i) => i + 2);

function formatDateDisplay(dateStr: string): string {
  const date = new Date(dateStr + 'T00:00:00');
  const day = date.getDate();
  const months = [
    'января', 'февраля', 'марта', 'апреля', 'мая', 'июня',
    'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря',
  ];
  return `${day} ${months[date.getMonth()]} ${date.getFullYear()}`;
}

function generateDateOptions(): { label: string; value: string }[] {
  const options: { label: string; value: string }[] = [];
  const today = new Date();

  for (let i = 0; i < 30; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() + i);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const value = `${year}-${month}-${day}`;
    const label = i === 0 ? `Сегодня, ${formatDateDisplay(value)}` : formatDateDisplay(value);
    options.push({ label, value });
  }

  return options;
}

export function CreateTrainingScreen(): React.JSX.Element {
  const styles = createStyles();
  const route = useRoute<CreateRouteProp>();
  const navigation = useNavigation();
  const { createTraining, isLoading } = useScheduleStore();

  const initialDate = route.params?.date || '';

  const [selectedClient, setSelectedClient] = useState<Client | null>(null);
  const [clientSearch, setClientSearch] = useState('');
  const [clientResults, setClientResults] = useState<Client[]>([]);
  const [showClientSearch, setShowClientSearch] = useState(false);
  const [isSearching, setIsSearching] = useState(false);

  const [selectedService, setSelectedService] = useState<ServiceSummary | null>(
    null,
  );
  const [services, setServices] = useState<ServiceSummary[]>([]);
  const [showServicePicker, setShowServicePicker] = useState(false);

  const [selectedDate, setSelectedDate] = useState(initialDate);
  const [showDatePicker, setShowDatePicker] = useState(false);

  const [selectedTime, setSelectedTime] = useState<string | null>(null);
  const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
  const [showTimePicker, setShowTimePicker] = useState(false);

  const [duration, setDuration] = useState(60);
  const [showDurationPicker, setShowDurationPicker] = useState(false);

  const [selectedRoom, setSelectedRoom] = useState<RoomSummary | null>(null);
  const [rooms, setRooms] = useState<RoomSummary[]>([]);
  const [showRoomPicker, setShowRoomPicker] = useState(false);

  const [repeatEnabled, setRepeatEnabled] = useState(false);
  const [repeatWeeks, setRepeatWeeks] = useState(4);

  const dateOptions = useMemo(() => generateDateOptions(), []);

  useEffect(() => {
    loadServices();
    loadRooms();
  }, []);

  useEffect(() => {
    if (selectedDate) {
      loadTimeSlots();
    }
  }, [selectedDate]);

  useEffect(() => {
    if (route.params?.clientId) {
      loadClientById(route.params.clientId);
    }
  }, [route.params?.clientId]);

  const loadServices = async () => {
    try {
      const data = await scheduleService.getTrainings({ limit: 0 });
      // Services are loaded from a separate endpoint in production;
      // here we use a placeholder approach
      setServices([]);
    } catch {
      // Services will be loaded when available
    }
  };

  const loadRooms = async () => {
    try {
      // Rooms are loaded from a separate endpoint
      setRooms([]);
    } catch {
      // Rooms will be loaded when available
    }
  };

  const loadTimeSlots = async () => {
    try {
      const slots = await scheduleService.getTrainerSlots('me', selectedDate);
      setTimeSlots(slots);
    } catch {
      setTimeSlots([]);
    }
  };

  const loadClientById = async (clientId: string) => {
    try {
      const client = await clientsService.getClient(clientId);
      setSelectedClient(client);
    } catch {
      // Client not found
    }
  };

  const handleClientSearch = useCallback(async (query: string) => {
    setClientSearch(query);
    if (query.length < 2) {
      setClientResults([]);
      return;
    }
    setIsSearching(true);
    try {
      const results = await clientsService.searchClients(query);
      setClientResults(results);
    } catch {
      setClientResults([]);
    } finally {
      setIsSearching(false);
    }
  }, []);

  const handleSelectClient = useCallback((client: Client) => {
    setSelectedClient(client);
    setShowClientSearch(false);
    setClientSearch('');
    setClientResults([]);
  }, []);

  const handleSubmit = useCallback(async () => {
    if (!selectedClient) {
      Alert.alert('Ошибка', 'Выберите клиента');
      return;
    }
    if (!selectedDate) {
      Alert.alert('Ошибка', 'Выберите дату');
      return;
    }
    if (!selectedTime) {
      Alert.alert('Ошибка', 'Выберите время');
      return;
    }

    const dto: CreateTrainingDto = {
      clientId: selectedClient.id,
      serviceId: selectedService?.id || '',
      date: selectedDate,
      startTime: selectedTime,
      duration,
      roomId: selectedRoom?.id,
      repeat: repeatEnabled,
      repeatWeeks: repeatEnabled ? repeatWeeks : undefined,
    };

    try {
      await createTraining(dto);
      Alert.alert('Готово', 'Тренировка создана', [
        { text: 'OK', onPress: () => navigation.goBack() },
      ]);
    } catch {
      Alert.alert('Ошибка', 'Не удалось создать тренировку');
    }
  }, [
    selectedClient,
    selectedService,
    selectedDate,
    selectedTime,
    duration,
    selectedRoom,
    repeatEnabled,
    repeatWeeks,
    createTraining,
    navigation,
  ]);

  const renderClientItem = useCallback(
    ({ item }: { item: Client }) => (
      <TouchableOpacity
        style={styles.searchResultItem}
        onPress={() => handleSelectClient(item)}
        activeOpacity={0.7}
      >
        <View style={styles.searchResultAvatar}>
          <Text style={styles.searchResultAvatarText}>
            {item.firstName[0]}
            {item.lastName[0]}
          </Text>
        </View>
        <View style={styles.searchResultInfo}>
          <Text style={styles.searchResultName}>
            {item.lastName} {item.firstName}
          </Text>
          <Text style={styles.searchResultPhone}>{item.phone}</Text>
        </View>
      </TouchableOpacity>
    ),
    [handleSelectClient],
  );

  return (
    <View style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        {/* Client selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Клиент</Text>
          {selectedClient ? (
            <View style={styles.selectedRow}>
              <View style={styles.selectedAvatar}>
                <Text style={styles.selectedAvatarText}>
                  {selectedClient.firstName[0]}
                  {selectedClient.lastName[0]}
                </Text>
              </View>
              <View style={styles.selectedInfo}>
                <Text style={styles.selectedName}>
                  {selectedClient.lastName} {selectedClient.firstName}
                </Text>
                <Text style={styles.selectedPhone}>
                  {selectedClient.phone}
                </Text>
              </View>
              <TouchableOpacity
                onPress={() => {
                  setSelectedClient(null);
                  setShowClientSearch(true);
                }}
              >
                <Text style={styles.changeLink}>Изменить</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <TouchableOpacity
              style={styles.selectorButton}
              onPress={() => setShowClientSearch(true)}
              activeOpacity={0.7}
            >
              <Text style={styles.selectorPlaceholder}>Выбрать клиента</Text>
            </TouchableOpacity>
          )}
        </Card>

        {/* Service selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Услуга</Text>
          <TouchableOpacity
            style={styles.selectorButton}
            onPress={() => setShowServicePicker(true)}
            activeOpacity={0.7}
          >
            <Text
              style={
                selectedService
                  ? styles.selectorValue
                  : styles.selectorPlaceholder
              }
            >
              {selectedService?.name || 'Выбрать услугу'}
            </Text>
          </TouchableOpacity>
        </Card>

        {/* Date selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Дата</Text>
          <TouchableOpacity
            style={styles.selectorButton}
            onPress={() => setShowDatePicker(true)}
            activeOpacity={0.7}
          >
            <Text
              style={
                selectedDate
                  ? styles.selectorValue
                  : styles.selectorPlaceholder
              }
            >
              {selectedDate
                ? formatDateDisplay(selectedDate)
                : 'Выбрать дату'}
            </Text>
          </TouchableOpacity>
        </Card>

        {/* Time selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Время</Text>
          {timeSlots.length > 0 ? (
            <View style={styles.timeSlotsGrid}>
              {timeSlots.map((slot) => {
                const timeLabel = slot.startTime.substring(0, 5);
                const isSelected = selectedTime === slot.startTime;
                return (
                  <TouchableOpacity
                    key={slot.startTime}
                    style={[
                      styles.timeSlot,
                      isSelected && styles.timeSlotSelected,
                      !slot.available && styles.timeSlotDisabled,
                    ]}
                    onPress={() => {
                      if (slot.available) setSelectedTime(slot.startTime);
                    }}
                    disabled={!slot.available}
                    activeOpacity={0.7}
                  >
                    <Text
                      style={[
                        styles.timeSlotText,
                        isSelected && styles.timeSlotTextSelected,
                        !slot.available && styles.timeSlotTextDisabled,
                      ]}
                    >
                      {timeLabel}
                    </Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          ) : (
            <TouchableOpacity
              style={styles.selectorButton}
              onPress={() => setShowTimePicker(true)}
              activeOpacity={0.7}
            >
              <Text
                style={
                  selectedTime
                    ? styles.selectorValue
                    : styles.selectorPlaceholder
                }
              >
                {selectedTime
                  ? selectedTime.substring(0, 5)
                  : 'Выбрать время'}
              </Text>
            </TouchableOpacity>
          )}
        </Card>

        {/* Duration selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Длительность</Text>
          <View style={styles.durationRow}>
            {DURATION_OPTIONS.map((opt) => (
              <TouchableOpacity
                key={opt}
                style={[
                  styles.durationChip,
                  duration === opt && styles.durationChipSelected,
                ]}
                onPress={() => setDuration(opt)}
                activeOpacity={0.7}
              >
                <Text
                  style={[
                    styles.durationChipText,
                    duration === opt && styles.durationChipTextSelected,
                  ]}
                >
                  {opt} мин
                </Text>
              </TouchableOpacity>
            ))}
          </View>
        </Card>

        {/* Room selector */}
        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Зал (опционально)</Text>
          <TouchableOpacity
            style={styles.selectorButton}
            onPress={() => setShowRoomPicker(true)}
            activeOpacity={0.7}
          >
            <Text
              style={
                selectedRoom
                  ? styles.selectorValue
                  : styles.selectorPlaceholder
              }
            >
              {selectedRoom?.name || 'Выбрать зал'}
            </Text>
          </TouchableOpacity>
        </Card>

        {/* Repeat toggle */}
        <Card style={styles.card}>
          <View style={styles.repeatRow}>
            <Text style={styles.sectionTitle}>Повторять</Text>
            <Switch
              value={repeatEnabled}
              onValueChange={setRepeatEnabled}
              trackColor={{
                false: colors.border,
                true: colors.primaryLight,
              }}
              thumbColor={repeatEnabled ? colors.primary : colors.white}
            />
          </View>
          {repeatEnabled && (
            <View style={styles.repeatWeeksRow}>
              <Text style={styles.repeatLabel}>Количество недель:</Text>
              <ScrollView
                horizontal
                showsHorizontalScrollIndicator={false}
                style={styles.repeatWeeksScroll}
              >
                {REPEAT_WEEKS_OPTIONS.map((w) => (
                  <TouchableOpacity
                    key={w}
                    style={[
                      styles.weekChip,
                      repeatWeeks === w && styles.weekChipSelected,
                    ]}
                    onPress={() => setRepeatWeeks(w)}
                    activeOpacity={0.7}
                  >
                    <Text
                      style={[
                        styles.weekChipText,
                        repeatWeeks === w && styles.weekChipTextSelected,
                      ]}
                    >
                      {w}
                    </Text>
                  </TouchableOpacity>
                ))}
              </ScrollView>
            </View>
          )}
        </Card>

        <Button
          title="Создать тренировку"
          onPress={handleSubmit}
          loading={isLoading}
          disabled={!selectedClient || !selectedDate || !selectedTime}
          style={styles.submitButton}
        />
      </ScrollView>

      {/* Client search modal */}
      <Modal
        visible={showClientSearch}
        transparent
        animationType="slide"
        onRequestClose={() => setShowClientSearch(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowClientSearch(false)}
        >
          <Pressable style={styles.searchSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.sheetTitle}>Поиск клиента</Text>
            <Input
              placeholder="Имя или телефон"
              value={clientSearch}
              onChangeText={handleClientSearch}
              autoFocus
            />
            <FlatList
              data={clientResults}
              renderItem={renderClientItem}
              keyExtractor={(item) => item.id}
              style={styles.searchResultsList}
              ListEmptyComponent={
                clientSearch.length >= 2 && !isSearching ? (
                  <Text style={styles.noResults}>Ничего не найдено</Text>
                ) : null
              }
            />
          </Pressable>
        </Pressable>
      </Modal>

      {/* Date picker modal */}
      <Modal
        visible={showDatePicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowDatePicker(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowDatePicker(false)}
        >
          <Pressable style={styles.pickerSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.sheetTitle}>Выберите дату</Text>
            <FlatList
              data={dateOptions}
              keyExtractor={(item) => item.value}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[
                    styles.pickerItem,
                    selectedDate === item.value && styles.pickerItemSelected,
                  ]}
                  onPress={() => {
                    setSelectedDate(item.value);
                    setSelectedTime(null);
                    setShowDatePicker(false);
                  }}
                  activeOpacity={0.7}
                >
                  <Text
                    style={[
                      styles.pickerItemText,
                      selectedDate === item.value &&
                        styles.pickerItemTextSelected,
                    ]}
                  >
                    {item.label}
                  </Text>
                </TouchableOpacity>
              )}
              style={styles.pickerList}
            />
          </Pressable>
        </Pressable>
      </Modal>

      {/* Time picker modal (fallback when no slots) */}
      <Modal
        visible={showTimePicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowTimePicker(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowTimePicker(false)}
        >
          <Pressable style={styles.pickerSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.sheetTitle}>Выберите время</Text>
            <FlatList
              data={generateTimeOptions()}
              keyExtractor={(item) => item}
              renderItem={({ item }) => (
                <TouchableOpacity
                  style={[
                    styles.pickerItem,
                    selectedTime === item && styles.pickerItemSelected,
                  ]}
                  onPress={() => {
                    setSelectedTime(item);
                    setShowTimePicker(false);
                  }}
                  activeOpacity={0.7}
                >
                  <Text
                    style={[
                      styles.pickerItemText,
                      selectedTime === item && styles.pickerItemTextSelected,
                    ]}
                  >
                    {item.substring(0, 5)}
                  </Text>
                </TouchableOpacity>
              )}
              style={styles.pickerList}
            />
          </Pressable>
        </Pressable>
      </Modal>

      {/* Service picker modal */}
      <Modal
        visible={showServicePicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowServicePicker(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowServicePicker(false)}
        >
          <Pressable style={styles.pickerSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.sheetTitle}>Выберите услугу</Text>
            {services.length > 0 ? (
              <FlatList
                data={services}
                keyExtractor={(item) => item.id}
                renderItem={({ item }) => (
                  <TouchableOpacity
                    style={[
                      styles.pickerItem,
                      selectedService?.id === item.id &&
                        styles.pickerItemSelected,
                    ]}
                    onPress={() => {
                      setSelectedService(item);
                      setDuration(item.duration);
                      setShowServicePicker(false);
                    }}
                    activeOpacity={0.7}
                  >
                    <Text
                      style={[
                        styles.pickerItemText,
                        selectedService?.id === item.id &&
                          styles.pickerItemTextSelected,
                      ]}
                    >
                      {item.name}
                    </Text>
                    <Text style={styles.pickerItemMeta}>
                      {item.duration} мин
                    </Text>
                  </TouchableOpacity>
                )}
                style={styles.pickerList}
              />
            ) : (
              <Text style={styles.noResults}>Нет доступных услуг</Text>
            )}
          </Pressable>
        </Pressable>
      </Modal>

      {/* Room picker modal */}
      <Modal
        visible={showRoomPicker}
        transparent
        animationType="slide"
        onRequestClose={() => setShowRoomPicker(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowRoomPicker(false)}
        >
          <Pressable style={styles.pickerSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.sheetTitle}>Выберите зал</Text>
            {rooms.length > 0 ? (
              <FlatList
                data={rooms}
                keyExtractor={(item) => item.id}
                renderItem={({ item }) => (
                  <TouchableOpacity
                    style={[
                      styles.pickerItem,
                      selectedRoom?.id === item.id &&
                        styles.pickerItemSelected,
                    ]}
                    onPress={() => {
                      setSelectedRoom(item);
                      setShowRoomPicker(false);
                    }}
                    activeOpacity={0.7}
                  >
                    <Text
                      style={[
                        styles.pickerItemText,
                        selectedRoom?.id === item.id &&
                          styles.pickerItemTextSelected,
                      ]}
                    >
                      {item.name}
                    </Text>
                  </TouchableOpacity>
                )}
                style={styles.pickerList}
              />
            ) : (
              <Text style={styles.noResults}>Нет доступных залов</Text>
            )}
          </Pressable>
        </Pressable>
      </Modal>
    </View>
  );
}

function generateTimeOptions(): string[] {
  const options: string[] = [];
  for (let h = 7; h <= 22; h++) {
    for (let m = 0; m < 60; m += 30) {
      const hour = String(h).padStart(2, '0');
      const min = String(m).padStart(2, '0');
      options.push(`${hour}:${min}:00`);
    }
  }
  return options;
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: spacing.lg,
    paddingBottom: spacing.xxxl * 2,
  },
  card: {
    marginBottom: spacing.lg,
  },
  sectionTitle: {
    ...typography.subtitle,
    color: colors.text,
    marginBottom: spacing.md,
  },
  selectorButton: {
    height: 48,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: 12,
    justifyContent: 'center',
    paddingHorizontal: spacing.lg,
    backgroundColor: colors.white,
  },
  selectorPlaceholder: {
    ...typography.body,
    color: colors.textMuted,
  },
  selectorValue: {
    ...typography.body,
    color: colors.text,
  },
  selectedRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  selectedAvatar: {
    width: 44,
    height: 44,
    borderRadius: 22,
    backgroundColor: colors.primaryLight,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  selectedAvatarText: {
    ...typography.bodySmall,
    color: colors.white,
    fontWeight: '700',
  },
  selectedInfo: {
    flex: 1,
  },
  selectedName: {
    ...typography.body,
    fontWeight: '600',
    color: colors.text,
  },
  selectedPhone: {
    ...typography.bodySmall,
    color: colors.textSecondary,
    marginTop: 2,
  },
  changeLink: {
    ...typography.bodySmall,
    color: colors.primary,
    fontWeight: '600',
  },
  timeSlotsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  timeSlot: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: 8,
    margin: spacing.xs,
    minWidth: 72,
    alignItems: 'center',
  },
  timeSlotSelected: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  timeSlotDisabled: {
    opacity: 0.4,
  },
  timeSlotText: {
    ...typography.bodySmall,
    fontWeight: '500',
    color: colors.text,
  },
  timeSlotTextSelected: {
    color: colors.white,
  },
  timeSlotTextDisabled: {
    color: colors.textMuted,
  },
  durationRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  durationChip: {
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.sm,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: 20,
    margin: spacing.xs,
  },
  durationChipSelected: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  durationChipText: {
    ...typography.bodySmall,
    fontWeight: '500',
    color: colors.text,
  },
  durationChipTextSelected: {
    color: colors.white,
  },
  repeatRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  repeatWeeksRow: {
    marginTop: spacing.md,
  },
  repeatLabel: {
    ...typography.bodySmall,
    color: colors.textSecondary,
    marginBottom: spacing.sm,
  },
  repeatWeeksScroll: {
    flexDirection: 'row',
  },
  weekChip: {
    width: 40,
    height: 40,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.sm,
  },
  weekChipSelected: {
    backgroundColor: colors.primary,
    borderColor: colors.primary,
  },
  weekChipText: {
    ...typography.bodySmall,
    fontWeight: '600',
    color: colors.text,
  },
  weekChipTextSelected: {
    color: colors.white,
  },
  submitButton: {
    marginTop: spacing.lg,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  searchSheet: {
    backgroundColor: colors.white,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: spacing.xl,
    paddingBottom: spacing.xxxl,
    maxHeight: '80%',
  },
  pickerSheet: {
    backgroundColor: colors.white,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: spacing.xl,
    paddingBottom: spacing.xxxl,
    maxHeight: '60%',
  },
  bottomSheetHandle: {
    width: 40,
    height: 4,
    borderRadius: 2,
    backgroundColor: colors.border,
    alignSelf: 'center',
    marginBottom: spacing.xl,
  },
  sheetTitle: {
    ...typography.h3,
    color: colors.text,
    marginBottom: spacing.lg,
  },
  searchResultsList: {
    maxHeight: 300,
  },
  searchResultItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  searchResultAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: colors.primaryLight,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  searchResultAvatarText: {
    ...typography.caption,
    color: colors.white,
    fontWeight: '700',
  },
  searchResultInfo: {
    flex: 1,
  },
  searchResultName: {
    ...typography.body,
    fontWeight: '500',
    color: colors.text,
  },
  searchResultPhone: {
    ...typography.caption,
    color: colors.textSecondary,
    marginTop: 2,
  },
  noResults: {
    ...typography.body,
    color: colors.textMuted,
    textAlign: 'center',
    paddingVertical: spacing.xl,
  },
  pickerList: {
    maxHeight: 300,
  },
  pickerItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.md,
    borderRadius: 8,
    marginBottom: spacing.xs,
  },
  pickerItemSelected: {
    backgroundColor: colors.background,
  },
  pickerItemText: {
    ...typography.body,
    color: colors.text,
  },
  pickerItemTextSelected: {
    color: colors.primary,
    fontWeight: '600',
  },
  pickerItemMeta: {
    ...typography.caption,
    color: colors.textSecondary,
  },
});
