import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TextInput,
  Modal,
  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 { useAuthStore } from '../../stores/auth.store';
import type { FunnelStage, FunnelHistoryItem } from '../../types/funnel';
import type { UserRole } from '../../types/auth';

const STAGE_LABELS: Record<FunnelStage, string> = {
  NEW: 'Новый',
  ASSIGNED: 'Назначен',
  APPOINTMENT_SET: 'Запланирован',
  COMPLETED: 'Проведён',
  REGULAR: 'Постоянный',
  REFUSED: 'Отказ',
  TRANSFERRED: 'Перенесён',
};

const STAGE_COLORS: Record<FunnelStage, { bg: string; text: string; dot: string }> = {
  NEW: { bg: '#E3F2FD', text: '#1565C0', dot: '#1565C0' },
  ASSIGNED: { bg: '#FFF3E0', text: '#E65100', dot: '#E65100' },
  APPOINTMENT_SET: { bg: '#FFF8E1', text: '#F57F17', dot: '#F57F17' },
  COMPLETED: { bg: '#E8F5E9', text: '#2E7D32', dot: '#2E7D32' },
  REGULAR: { bg: '#E8F5E9', text: '#2E7D32', dot: '#2E7D32' },
  REFUSED: { bg: '#FFEBEE', text: '#C62828', dot: '#C62828' },
  TRANSFERRED: { bg: '#FFF3E0', text: '#E65100', dot: '#E65100' },
};

const NEXT_STAGES: Partial<Record<FunnelStage, FunnelStage>> = {
  NEW: 'ASSIGNED',
  ASSIGNED: 'APPOINTMENT_SET',
  APPOINTMENT_SET: 'COMPLETED',
  COMPLETED: 'REGULAR',
};

function formatDateTime(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('ru-RU', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

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

function canPerformActions(
  role: UserRole,
  stage: FunnelStage,
): {
  canMove: boolean;
  canAssign: boolean;
  canTransfer: boolean;
  canRefuse: boolean;
} {
  const r = role.toLowerCase();
  if (r === 'coordinator' || r === 'manager') {
    return {
      canMove: stage !== 'REFUSED' && stage !== 'REGULAR',
      canAssign: stage === 'NEW',
      canTransfer: stage !== 'REFUSED' && stage !== 'REGULAR',
      canRefuse: stage !== 'REFUSED' && stage !== 'REGULAR',
    };
  }
  if (r === 'trainer') {
    return {
      canMove: stage !== 'NEW' && stage !== 'REFUSED' && stage !== 'REGULAR',
      canAssign: false,
      canTransfer: false,
      canRefuse: stage !== 'NEW' && stage !== 'REFUSED' && stage !== 'REGULAR',
    };
  }
  return {
    canMove: false,
    canAssign: false,
    canTransfer: false,
    canRefuse: false,
  };
}

interface FunnelActionScreenProps {
  navigation: {
    navigate: (screen: string, params?: Record<string, unknown>) => void;
    goBack: () => void;
  };
  route: {
    params: {
      clientId: string;
    };
  };
}

export function FunnelActionScreen({
  navigation,
  route,
}: FunnelActionScreenProps): React.JSX.Element {
  const styles = createStyles();
  const { clientId } = route.params;

  const user = useAuthStore((state) => state.user);
  const clientDetail = useFunnelStore((state) => state.clientDetail);
  const isLoadingDetail = useFunnelStore((state) => state.isLoadingDetail);
  const isSubmitting = useFunnelStore((state) => state.isSubmitting);
  const fetchClientDetail = useFunnelStore((state) => state.fetchClientDetail);
  const moveStage = useFunnelStore((state) => state.moveStage);
  const refuseClient = useFunnelStore((state) => state.refuseClient);

  const [refuseModalVisible, setRefuseModalVisible] = useState(false);
  const [refuseComment, setRefuseComment] = useState('');

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

  const actions = user
    ? canPerformActions(user.role, clientDetail?.entry.stage ?? 'NEW')
    : { canMove: false, canAssign: false, canTransfer: false, canRefuse: false };

  const handleMoveNext = useCallback(async () => {
    if (!clientDetail) return;
    const nextStage = NEXT_STAGES[clientDetail.entry.stage];
    if (!nextStage) return;

    try {
      await moveStage(clientId, { toStage: nextStage });
      await fetchClientDetail(clientId);
    } catch {
      Alert.alert('Ошибка', 'Не удалось переместить клиента');
    }
  }, [clientDetail, clientId, moveStage, fetchClientDetail]);

  const handleAssign = useCallback(() => {
    navigation.navigate('AssignClient', { clientId });
  }, [navigation, clientId]);

  const handleTransfer = useCallback(() => {
    navigation.navigate('AssignClient', { clientId, isTransfer: true });
  }, [navigation, clientId]);

  const handleRefuseSubmit = useCallback(async () => {
    if (!refuseComment.trim()) {
      Alert.alert('Ошибка', 'Укажите причину отказа');
      return;
    }

    try {
      await refuseClient(clientId, {
        reason: 'Отказ клиента',
        comment: refuseComment.trim(),
      });
      setRefuseModalVisible(false);
      setRefuseComment('');
      await fetchClientDetail(clientId);
    } catch {
      Alert.alert('Ошибка', 'Не удалось отклонить клиента');
    }
  }, [clientId, refuseComment, refuseClient, fetchClientDetail]);

  if (isLoadingDetail || !clientDetail) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  const { entry, history } = clientDetail;
  const client = entry.client;
  const stageColor = STAGE_COLORS[entry.stage];
  const nextStage = NEXT_STAGES[entry.stage];

  return (
    <View style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        {/* Client Info */}
        <View style={styles.clientHeader}>
          <View style={styles.avatar}>
            <Text style={styles.avatarText}>{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>
            {entry.trainer && (
              <Text style={styles.trainerLabel}>
                Тренер: {entry.trainer.firstName} {entry.trainer.lastName}
              </Text>
            )}
          </View>
        </View>

        {/* Current Stage */}
        <View style={styles.stageSection}>
          <Text style={styles.sectionTitle}>Текущий этап</Text>
          <View style={[styles.stageBadgeLarge, { backgroundColor: stageColor.bg }]}>
            <Text style={[styles.stageBadgeText, { color: stageColor.text }]}>
              {STAGE_LABELS[entry.stage]}
            </Text>
          </View>
        </View>

        {/* History Timeline */}
        <View style={styles.historySection}>
          <Text style={styles.sectionTitle}>История</Text>
          {history.length === 0 ? (
            <Text style={styles.emptyHistory}>Нет записей в истории</Text>
          ) : (
            history.map((item, index) => (
              <HistoryTimelineItem
                key={item.id}
                item={item}
                isLast={index === history.length - 1}
              />
            ))
          )}
        </View>
      </ScrollView>

      {/* Action Buttons */}
      <View style={styles.actionsContainer}>
        {actions.canAssign && (
          <Button
            title="Назначить тренера"
            onPress={handleAssign}
            variant="primary"
            style={styles.actionButton}
          />
        )}
        {actions.canMove && nextStage && (
          <Button
            title={`Перевести в "${STAGE_LABELS[nextStage]}"`}
            onPress={() => void handleMoveNext()}
            loading={isSubmitting}
            variant="primary"
            style={styles.actionButton}
          />
        )}
        {actions.canTransfer && (
          <Button
            title="Передать тренеру"
            onPress={handleTransfer}
            variant="outline"
            style={styles.actionButton}
          />
        )}
        {actions.canRefuse && (
          <Button
            title="Отказ"
            onPress={() => setRefuseModalVisible(true)}
            variant="secondary"
            style={styles.actionButtonRefuse}
            textColor="#FFFFFF"
          />
        )}
      </View>

      {/* Refuse Modal */}
      <Modal
        visible={refuseModalVisible}
        transparent
        animationType="slide"
        onRequestClose={() => setRefuseModalVisible(false)}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>Причина отказа</Text>
            <Text style={styles.modalSubtitle}>Укажите комментарий для закрытия клиента</Text>
            <TextInput
              style={styles.modalTextInput}
              placeholder="Опишите причину отказа..."
              placeholderTextColor={colors.textMuted}
              multiline
              numberOfLines={4}
              textAlignVertical="top"
              value={refuseComment}
              onChangeText={setRefuseComment}
            />
            <View style={styles.modalActions}>
              <Button
                title="Отмена"
                onPress={() => {
                  setRefuseModalVisible(false);
                  setRefuseComment('');
                }}
                variant="outline"
                style={styles.modalButton}
              />
              <Button
                title="Подтвердить отказ"
                onPress={() => void handleRefuseSubmit()}
                loading={isSubmitting}
                variant="primary"
                style={styles.modalButton}
              />
            </View>
          </View>
        </View>
      </Modal>
    </View>
  );
}

interface HistoryTimelineItemProps {
  item: FunnelHistoryItem;
  isLast: boolean;
}

function HistoryTimelineItem({ item, isLast }: HistoryTimelineItemProps): React.JSX.Element {
  const styles = createStyles();
  const stageColor = STAGE_COLORS[item.toStage];

  return (
    <View style={styles.timelineItem}>
      <View style={styles.timelineDotColumn}>
        <View style={[styles.timelineDot, { backgroundColor: stageColor.dot }]} />
        {!isLast && <View style={styles.timelineLine} />}
      </View>
      <View style={styles.timelineContent}>
        <View style={styles.timelineHeader}>
          <View style={[styles.timelineBadge, { backgroundColor: stageColor.bg }]}>
            <Text style={[styles.timelineBadgeText, { color: stageColor.text }]}>
              {STAGE_LABELS[item.toStage]}
            </Text>
          </View>
          <Text style={styles.timelineDate}>{formatDateTime(item.createdAt)}</Text>
        </View>
        <Text style={styles.timelinePerformer}>{item.performedByName}</Text>
        {item.comment && <Text style={styles.timelineComment}>{item.comment}</Text>}
      </View>
    </View>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },
    content: {
      padding: spacing.lg,
      paddingBottom: spacing.xxxl * 3,
    },
    loadingContainer: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: colors.background,
    },

    // Client Header
    clientHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: colors.card,
      borderRadius: 12,
      padding: spacing.lg,
      marginBottom: spacing.lg,
      shadowColor: colors.black,
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.08,
      shadowRadius: 8,
      elevation: 3,
    },
    avatar: {
      width: 56,
      height: 56,
      borderRadius: 28,
      backgroundColor: colors.primary,
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: spacing.lg,
    },
    avatarText: {
      ...typography.subtitle,
      fontWeight: '700',
      color: colors.white,
    },
    clientInfo: {
      flex: 1,
    },
    clientName: {
      ...typography.subtitle,
      color: colors.text,
    },
    clientPhone: {
      ...typography.bodySmall,
      color: colors.textSecondary,
      marginTop: 2,
    },
    trainerLabel: {
      ...typography.caption,
      color: colors.textMuted,
      marginTop: spacing.xs,
    },

    // Stage Section
    stageSection: {
      marginBottom: spacing.lg,
    },
    sectionTitle: {
      ...typography.subtitle,
      color: colors.text,
      marginBottom: spacing.md,
    },
    stageBadgeLarge: {
      alignSelf: 'flex-start',
      paddingHorizontal: spacing.lg,
      paddingVertical: spacing.sm,
      borderRadius: 12,
    },
    stageBadgeText: {
      ...typography.body,
      fontWeight: '600',
    },

    // History Section
    historySection: {
      marginBottom: spacing.lg,
    },
    emptyHistory: {
      ...typography.body,
      color: colors.textMuted,
      textAlign: 'center',
      paddingVertical: spacing.xl,
    },

    // Timeline
    timelineItem: {
      flexDirection: 'row',
      minHeight: 60,
    },
    timelineDotColumn: {
      width: 24,
      alignItems: 'center',
    },
    timelineDot: {
      width: 12,
      height: 12,
      borderRadius: 6,
      marginTop: 4,
    },
    timelineLine: {
      width: 2,
      flex: 1,
      backgroundColor: colors.border,
      marginTop: 4,
    },
    timelineContent: {
      flex: 1,
      marginLeft: spacing.md,
      paddingBottom: spacing.lg,
    },
    timelineHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'space-between',
      marginBottom: spacing.xs,
    },
    timelineBadge: {
      paddingHorizontal: spacing.sm,
      paddingVertical: 2,
      borderRadius: 6,
    },
    timelineBadgeText: {
      ...typography.caption,
      fontWeight: '600',
    },
    timelineDate: {
      ...typography.caption,
      color: colors.textMuted,
    },
    timelinePerformer: {
      ...typography.bodySmall,
      color: colors.textSecondary,
      marginTop: 2,
    },
    timelineComment: {
      ...typography.caption,
      color: colors.textMuted,
      fontStyle: 'italic',
      marginTop: spacing.xs,
    },

    // Actions
    actionsContainer: {
      position: 'absolute',
      bottom: 0,
      left: 0,
      right: 0,
      backgroundColor: colors.white,
      borderTopWidth: 1,
      borderTopColor: colors.border,
      padding: spacing.lg,
      paddingBottom: spacing.xxxl,
      shadowColor: colors.black,
      shadowOffset: { width: 0, height: -2 },
      shadowOpacity: 0.05,
      shadowRadius: 4,
      elevation: 5,
    },
    actionButton: {
      marginBottom: spacing.sm,
    },
    actionButtonRefuse: {
      marginBottom: spacing.sm,
      backgroundColor: colors.error,
    },

    // Modal
    modalOverlay: {
      flex: 1,
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      justifyContent: 'flex-end',
    },
    modalContent: {
      backgroundColor: colors.white,
      borderTopLeftRadius: 20,
      borderTopRightRadius: 20,
      padding: spacing.xl,
      paddingBottom: spacing.xxxl,
    },
    modalTitle: {
      ...typography.h3,
      color: colors.text,
      marginBottom: spacing.xs,
    },
    modalSubtitle: {
      ...typography.bodySmall,
      color: colors.textSecondary,
      marginBottom: spacing.lg,
    },
    modalTextInput: {
      borderWidth: 1,
      borderColor: colors.border,
      borderRadius: 12,
      padding: spacing.lg,
      minHeight: 100,
      fontSize: 14,
      color: colors.text,
      backgroundColor: colors.background,
      marginBottom: spacing.lg,
    },
    modalActions: {
      flexDirection: 'row',
      gap: spacing.md,
    },
    modalButton: {
      flex: 1,
    },
  });
