import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  FlatList,
  TextInput,
  StyleSheet,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Button } from '../../components/ui';
import { useFunnelStore } from '../../stores/funnel.store';
import { funnelService } from '../../services/funnel';
import type { TrainerOption } from '../../types/funnel';

interface AssignClientScreenProps {
  navigation: {
    goBack: () => void;
  };
  route: {
    params: {
      clientId: string;
      isTransfer?: boolean;
    };
  };
}

function getInitials(firstName: string, lastName: string): string {
  return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
}

export function AssignClientScreen({
  navigation,
  route,
}: AssignClientScreenProps): React.JSX.Element {
  const styles = createStyles();
  const { clientId, isTransfer = false } = route.params;

  const clientDetail = useFunnelStore((state) => state.clientDetail);
  const isSubmitting = useFunnelStore((state) => state.isSubmitting);
  const assignClient = useFunnelStore((state) => state.assignClient);
  const transferClient = useFunnelStore((state) => state.transferClient);
  const fetchClientDetail = useFunnelStore((state) => state.fetchClientDetail);

  const [trainers, setTrainers] = useState<TrainerOption[]>([]);
  const [isLoadingTrainers, setIsLoadingTrainers] = useState(true);
  const [selectedTrainerId, setSelectedTrainerId] = useState<string | null>(null);
  const [comment, setComment] = useState('');

  useEffect(() => {
    void loadTrainers();
  }, []);

  const loadTrainers = async () => {
    setIsLoadingTrainers(true);
    try {
      const data = await funnelService.getTrainers();
      setTrainers(data);
    } catch {
      Alert.alert('Ошибка', 'Не удалось загрузить список тренеров');
    } finally {
      setIsLoadingTrainers(false);
    }
  };

  const handleSubmit = useCallback(async () => {
    if (!selectedTrainerId) {
      Alert.alert('Ошибка', 'Выберите тренера');
      return;
    }

    try {
      if (isTransfer) {
        await transferClient(clientId, {
          trainerId: selectedTrainerId,
          comment: comment.trim() || undefined,
        });
      } else {
        await assignClient({
          clientId,
          trainerId: selectedTrainerId,
          comment: comment.trim() || undefined,
        });
      }
      await fetchClientDetail(clientId);
      navigation.goBack();
    } catch {
      Alert.alert(
        'Ошибка',
        isTransfer ? 'Не удалось передать клиента' : 'Не удалось назначить тренера',
      );
    }
  }, [
    selectedTrainerId,
    clientId,
    comment,
    isTransfer,
    assignClient,
    transferClient,
    fetchClientDetail,
    navigation,
  ]);

  const client = clientDetail?.entry.client;
  const screenTitle = isTransfer ? 'Передать тренеру' : 'Назначить тренера';

  const renderTrainer = useCallback(
    ({ item }: { item: TrainerOption }) => {
      const isSelected = item.id === selectedTrainerId;
      return (
        <TouchableOpacity
          style={[styles.trainerItem, isSelected && styles.trainerItemSelected]}
          onPress={() => setSelectedTrainerId(item.id)}
          activeOpacity={0.7}
        >
          <View style={[styles.trainerAvatar, isSelected && styles.trainerAvatarSelected]}>
            <Text
              style={[styles.trainerAvatarText, isSelected && styles.trainerAvatarTextSelected]}
            >
              {getInitials(item.firstName, item.lastName)}
            </Text>
          </View>
          <View style={styles.trainerInfo}>
            <Text style={[styles.trainerName, isSelected && styles.trainerNameSelected]}>
              {item.lastName} {item.firstName}
            </Text>
            {item.departmentName && (
              <Text style={styles.trainerDepartment}>{item.departmentName}</Text>
            )}
          </View>
          {isSelected && (
            <View style={styles.checkmark}>
              <Text style={styles.checkmarkText}>V</Text>
            </View>
          )}
        </TouchableOpacity>
      );
    },
    [selectedTrainerId],
  );

  return (
    <View style={styles.container}>
      {/* Client Info */}
      {client && (
        <View style={styles.clientCard}>
          <View style={styles.clientAvatar}>
            <Text style={styles.clientAvatarText}>
              {getInitials(client.firstName, client.lastName)}
            </Text>
          </View>
          <View style={styles.clientInfo}>
            <Text style={styles.clientName}>
              {client.lastName} {client.firstName}
            </Text>
            <Text style={styles.clientPhone}>{client.phone}</Text>
          </View>
        </View>
      )}

      {/* Trainer List */}
      <Text style={styles.sectionTitle}>{screenTitle}</Text>

      {isLoadingTrainers ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={colors.primary} />
        </View>
      ) : (
        <FlatList
          data={trainers}
          keyExtractor={(item) => item.id}
          renderItem={renderTrainer}
          contentContainerStyle={styles.trainerList}
          ListEmptyComponent={<Text style={styles.emptyText}>Нет доступных тренеров</Text>}
        />
      )}

      {/* Comment + Submit */}
      <View style={styles.bottomSection}>
        <TextInput
          style={styles.commentInput}
          placeholder="Комментарий (необязательно)"
          placeholderTextColor={colors.textMuted}
          value={comment}
          onChangeText={setComment}
          multiline
          numberOfLines={2}
          textAlignVertical="top"
        />
        <Button
          title={isTransfer ? 'Передать' : 'Назначить'}
          onPress={() => void handleSubmit()}
          loading={isSubmitting}
          disabled={!selectedTrainerId}
          variant="primary"
        />
      </View>
    </View>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },

    // Client Card
    clientCard: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.card,
      padding: spacing.lg,
      marginHorizontal: spacing.lg,
      marginTop: spacing.lg,
      borderRadius: 12,
      shadowColor: colors.black,
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.08,
      shadowRadius: 8,
      elevation: 3,
    },
    clientAvatar: {
      width: 44,
      height: 44,
      borderRadius: 22,
      backgroundColor: colors.primary,
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: spacing.md,
    },
    clientAvatarText: {
      ...typography.bodySmall,
      fontWeight: '700',
      color: colors.white,
    },
    clientInfo: {
      flex: 1,
    },
    clientName: {
      ...typography.body,
      fontWeight: '600',
      color: colors.text,
    },
    clientPhone: {
      ...typography.caption,
      color: colors.textSecondary,
      marginTop: 2,
    },

    // Section
    sectionTitle: {
      ...typography.subtitle,
      color: colors.text,
      marginHorizontal: spacing.lg,
      marginTop: spacing.xl,
      marginBottom: spacing.md,
    },

    // Trainer List
    trainerList: {
      paddingHorizontal: spacing.lg,
    },
    trainerItem: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.card,
      padding: spacing.lg,
      borderRadius: 12,
      marginBottom: spacing.sm,
      borderWidth: 2,
      borderColor: 'transparent',
    },
    trainerItemSelected: {
      borderColor: colors.primary,
      backgroundColor: '#FFF8F3',
    },
    trainerAvatar: {
      width: 40,
      height: 40,
      borderRadius: 20,
      backgroundColor: colors.background,
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: spacing.md,
    },
    trainerAvatarSelected: {
      backgroundColor: colors.primary,
    },
    trainerAvatarText: {
      ...typography.caption,
      fontWeight: '700',
      color: colors.textSecondary,
    },
    trainerAvatarTextSelected: {
      color: colors.white,
    },
    trainerInfo: {
      flex: 1,
    },
    trainerName: {
      ...typography.body,
      color: colors.text,
    },
    trainerNameSelected: {
      fontWeight: '600',
      color: colors.primary,
    },
    trainerDepartment: {
      ...typography.caption,
      color: colors.textMuted,
      marginTop: 2,
    },
    checkmark: {
      width: 24,
      height: 24,
      borderRadius: 12,
      backgroundColor: colors.primary,
      alignItems: 'center',
      justifyContent: 'center',
    },
    checkmarkText: {
      color: colors.white,
      fontWeight: '700',
      fontSize: 12,
    },

    // Loading / Empty
    loadingContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
    },
    emptyText: {
      ...typography.body,
      color: colors.textMuted,
      textAlign: 'center',
      paddingVertical: spacing.xxxl,
    },

    // Bottom Section
    bottomSection: {
      backgroundColor: colors.white,
      borderTopWidth: 1,
      borderTopColor: colors.border,
      padding: spacing.lg,
      paddingBottom: spacing.xxxl,
    },
    commentInput: {
      borderWidth: 1,
      borderColor: colors.border,
      borderRadius: 12,
      padding: spacing.md,
      minHeight: 60,
      fontSize: 14,
      color: colors.text,
      backgroundColor: colors.background,
      marginBottom: spacing.md,
    },
  });
