import React, { useCallback, useEffect, useState } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  Modal,
  Pressable,
  Alert,
} from 'react-native';
import { useRoute, useNavigation } from '@react-navigation/native';
import type { RouteProp } from '@react-navigation/native';
import type { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { Card, Button } from '../../components/ui';
import { scheduleService } from '../../services/schedule';
import { useScheduleStore } from '../../stores/schedule.store';
import type { Training, TrainingStatus, CancelReason } from '../../types/training';
import {
  STATUS_LABELS,
  CANCEL_REASON_LABELS,
} from '../../types/training';
import type { ScheduleStackParamList } from './types';

type DetailRouteProp = RouteProp<ScheduleStackParamList, 'TrainingDetail'>;

function getStatusColor(status: TrainingStatus): string {
  switch (status) {
    case 'PLANNED':
      return colors.warning;
    case 'CONFIRMED':
      return colors.success;
    case 'COMPLETED':
      return colors.success;
    case 'CANCELLED':
      return colors.error;
    case 'NO_SHOW':
      return colors.error;
    default:
      return colors.textMuted;
  }
}

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

function formatTimeRange(startTime: string, endTime: string): string {
  return `${startTime.substring(0, 5)} - ${endTime.substring(0, 5)}`;
}

const CANCEL_REASONS: CancelReason[] = [
  'CLIENT_CANCEL',
  'NO_CHARGE',
  'SALE_RETURN',
  'ILLNESS',
];

export function TrainingDetailScreen(): React.JSX.Element {
  const styles = createStyles();
  const route = useRoute<DetailRouteProp>();
  const navigation = useNavigation<NativeStackNavigationProp<ScheduleStackParamList>>();
  const { trainingId } = route.params;

  const [training, setTraining] = useState<Training | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [showCancelModal, setShowCancelModal] = useState(false);
  const [selectedReason, setSelectedReason] = useState<CancelReason | null>(
    null,
  );
  const [isActionLoading, setIsActionLoading] = useState(false);

  const { cancelTraining, confirmTraining, completeTraining } =
    useScheduleStore();

  const loadTraining = useCallback(async () => {
    setIsLoading(true);
    try {
      const data = await scheduleService.getTraining(trainingId);
      setTraining(data);
    } catch (err) {
      const message =
        err instanceof Error ? err.message : 'Ошибка загрузки тренировки';
      Alert.alert('Ошибка', message);
    } finally {
      setIsLoading(false);
    }
  }, [trainingId]);

  useEffect(() => {
    loadTraining();
  }, [loadTraining]);

  const handleConfirm = useCallback(async () => {
    if (!training) return;
    setIsActionLoading(true);
    try {
      await confirmTraining(training.id);
      await loadTraining();
    } catch {
      Alert.alert('Ошибка', 'Не удалось подтвердить тренировку');
    } finally {
      setIsActionLoading(false);
    }
  }, [training, confirmTraining, loadTraining]);

  const handleComplete = useCallback(async () => {
    if (!training) return;
    Alert.alert(
      'Завершить тренировку',
      'Подтвердить завершение тренировки?',
      [
        { text: 'Отмена', style: 'cancel' },
        {
          text: 'Завершить',
          onPress: async () => {
            setIsActionLoading(true);
            try {
              await completeTraining(training.id);
              await loadTraining();
            } catch {
              Alert.alert('Ошибка', 'Не удалось завершить тренировку');
            } finally {
              setIsActionLoading(false);
            }
          },
        },
      ],
    );
  }, [training, completeTraining, loadTraining]);

  const handleCancelSubmit = useCallback(async () => {
    if (!training || !selectedReason) return;
    setIsActionLoading(true);
    try {
      await cancelTraining(training.id, { reason: selectedReason });
      setShowCancelModal(false);
      setSelectedReason(null);
      await loadTraining();
    } catch {
      Alert.alert('Ошибка', 'Не удалось отменить тренировку');
    } finally {
      setIsActionLoading(false);
    }
  }, [training, selectedReason, cancelTraining, loadTraining]);

  const handleReschedule = useCallback(() => {
    if (!training) return;
    navigation.navigate('CreateTraining', {
      date: training.date,
      clientId: training.clientId,
    });
  }, [training, navigation]);

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

  if (!training) {
    return (
      <View style={styles.loadingContainer}>
        <Text style={styles.errorText}>Тренировка не найдена</Text>
      </View>
    );
  }

  const statusColor = getStatusColor(training.status);
  const statusLabel = STATUS_LABELS[training.status];
  const isActive =
    training.status === 'PLANNED' || training.status === 'CONFIRMED';
  const canConfirm = training.status === 'PLANNED';
  const canComplete = training.status === 'CONFIRMED';

  return (
    <View style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        <Card style={styles.card}>
          <View style={styles.statusRow}>
            <View
              style={[styles.statusBadge, { backgroundColor: statusColor }]}
            >
              <Text style={styles.statusText}>{statusLabel}</Text>
            </View>
          </View>

          <View style={styles.clientSection}>
            <View style={styles.avatar}>
              <Text style={styles.avatarText}>
                {training.client
                  ? `${training.client.firstName[0]}${training.client.lastName[0]}`
                  : '?'}
              </Text>
            </View>
            <View style={styles.clientInfo}>
              <Text style={styles.clientName}>
                {training.client
                  ? `${training.client.lastName} ${training.client.firstName}`
                  : 'Клиент'}
              </Text>
              {training.client?.phone && (
                <Text style={styles.clientPhone}>
                  {training.client.phone}
                </Text>
              )}
            </View>
          </View>
        </Card>

        <Card style={styles.card}>
          <Text style={styles.sectionTitle}>Информация о тренировке</Text>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Дата</Text>
            <Text style={styles.infoValue}>{formatDate(training.date)}</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Время</Text>
            <Text style={styles.infoValue}>
              {formatTimeRange(training.startTime, training.endTime)}
            </Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Длительность</Text>
            <Text style={styles.infoValue}>{training.duration} мин</Text>
          </View>

          <View style={styles.infoRow}>
            <Text style={styles.infoLabel}>Услуга</Text>
            <Text style={styles.infoValue}>
              {training.service?.name || '-'}
            </Text>
          </View>

          {training.room && (
            <View style={styles.infoRow}>
              <Text style={styles.infoLabel}>Зал</Text>
              <Text style={styles.infoValue}>{training.room.name}</Text>
            </View>
          )}
        </Card>

        {training.cancelReason && (
          <Card style={styles.card}>
            <Text style={styles.sectionTitle}>Причина отмены</Text>
            <Text style={styles.cancelReasonText}>
              {CANCEL_REASON_LABELS[training.cancelReason]}
            </Text>
            {training.cancelComment && (
              <Text style={styles.cancelComment}>
                {training.cancelComment}
              </Text>
            )}
          </Card>
        )}

        {isActive && (
          <View style={styles.actionsSection}>
            {canConfirm && (
              <Button
                title="Подтвердить"
                onPress={handleConfirm}
                loading={isActionLoading}
                style={styles.actionButton}
              />
            )}
            {canComplete && (
              <Button
                title="Завершить"
                onPress={handleComplete}
                loading={isActionLoading}
                style={styles.actionButton}
              />
            )}
            <Button
              title="Перенести"
              onPress={handleReschedule}
              variant="outline"
              disabled={isActionLoading}
              style={styles.actionButton}
            />
            <Button
              title="Отменить"
              onPress={() => setShowCancelModal(true)}
              variant="secondary"
              disabled={isActionLoading}
              style={styles.cancelButton}
            />
          </View>
        )}
      </ScrollView>

      <Modal
        visible={showCancelModal}
        transparent
        animationType="slide"
        onRequestClose={() => setShowCancelModal(false)}
      >
        <Pressable
          style={styles.modalOverlay}
          onPress={() => setShowCancelModal(false)}
        >
          <Pressable style={styles.bottomSheet} onPress={() => {}}>
            <View style={styles.bottomSheetHandle} />
            <Text style={styles.bottomSheetTitle}>Причина отмены</Text>

            {CANCEL_REASONS.map((reason) => (
              <TouchableOpacity
                key={reason}
                style={[
                  styles.reasonItem,
                  selectedReason === reason && styles.reasonItemSelected,
                ]}
                onPress={() => setSelectedReason(reason)}
                activeOpacity={0.7}
              >
                <View
                  style={[
                    styles.reasonRadio,
                    selectedReason === reason && styles.reasonRadioSelected,
                  ]}
                >
                  {selectedReason === reason && (
                    <View style={styles.reasonRadioDot} />
                  )}
                </View>
                <Text style={styles.reasonText}>
                  {CANCEL_REASON_LABELS[reason]}
                </Text>
              </TouchableOpacity>
            ))}

            <Button
              title="Подтвердить отмену"
              onPress={handleCancelSubmit}
              loading={isActionLoading}
              disabled={!selectedReason}
              style={styles.confirmCancelButton}
            />
          </Pressable>
        </Pressable>
      </Modal>
    </View>
  );
}

const createStyles = () => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  content: {
    padding: spacing.lg,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: colors.background,
  },
  errorText: {
    ...typography.body,
    color: colors.textMuted,
  },
  card: {
    marginBottom: spacing.lg,
  },
  statusRow: {
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginBottom: spacing.md,
  },
  statusBadge: {
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
    borderRadius: 8,
  },
  statusText: {
    ...typography.caption,
    color: colors.white,
    fontWeight: '600',
  },
  clientSection: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  avatar: {
    width: 56,
    height: 56,
    borderRadius: 28,
    backgroundColor: colors.primaryLight,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  avatarText: {
    ...typography.subtitle,
    color: colors.white,
    fontWeight: '700',
  },
  clientInfo: {
    flex: 1,
  },
  clientName: {
    ...typography.subtitle,
    color: colors.text,
  },
  clientPhone: {
    ...typography.bodySmall,
    color: colors.textSecondary,
    marginTop: 2,
  },
  sectionTitle: {
    ...typography.subtitle,
    color: colors.text,
    marginBottom: spacing.lg,
  },
  infoRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: spacing.sm,
    borderBottomWidth: 1,
    borderBottomColor: colors.border,
  },
  infoLabel: {
    ...typography.body,
    color: colors.textSecondary,
  },
  infoValue: {
    ...typography.body,
    color: colors.text,
    fontWeight: '500',
  },
  cancelReasonText: {
    ...typography.body,
    color: colors.error,
  },
  cancelComment: {
    ...typography.bodySmall,
    color: colors.textSecondary,
    marginTop: spacing.sm,
  },
  actionsSection: {
    marginTop: spacing.sm,
  },
  actionButton: {
    marginBottom: spacing.md,
  },
  cancelButton: {
    marginBottom: spacing.md,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    justifyContent: 'flex-end',
  },
  bottomSheet: {
    backgroundColor: colors.white,
    borderTopLeftRadius: 20,
    borderTopRightRadius: 20,
    padding: spacing.xl,
    paddingBottom: spacing.xxxl,
  },
  bottomSheetHandle: {
    width: 40,
    height: 4,
    borderRadius: 2,
    backgroundColor: colors.border,
    alignSelf: 'center',
    marginBottom: spacing.xl,
  },
  bottomSheetTitle: {
    ...typography.h3,
    color: colors.text,
    marginBottom: spacing.xl,
  },
  reasonItem: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.md,
    borderRadius: 12,
    marginBottom: spacing.sm,
  },
  reasonItemSelected: {
    backgroundColor: colors.background,
  },
  reasonRadio: {
    width: 22,
    height: 22,
    borderRadius: 11,
    borderWidth: 2,
    borderColor: colors.border,
    alignItems: 'center',
    justifyContent: 'center',
    marginRight: spacing.md,
  },
  reasonRadioSelected: {
    borderColor: colors.primary,
  },
  reasonRadioDot: {
    width: 12,
    height: 12,
    borderRadius: 6,
    backgroundColor: colors.primary,
  },
  reasonText: {
    ...typography.body,
    color: colors.text,
  },
  confirmCancelButton: {
    marginTop: spacing.xl,
  },
});
