import React, { useCallback, useEffect } from 'react';
import {
  View,
  Text,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  ActivityIndicator,
  Alert,
  Linking,
} from 'react-native';
import { useRoute } from '@react-navigation/native';
import type { RouteProp } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';
import { useBookingStore } from '../../stores/booking.store';
import {
  STATUS_LABELS,
  STATUS_COLORS,
  formatBookingTime,
  getBookingDuration,
} from '../../types/booking';
import type { BookingStackParamList } from './types';

type DetailRoute = RouteProp<BookingStackParamList, 'BookingDetail'>;

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

export function BookingDetailScreen(): React.JSX.Element {
  const styles = createStyles();
  const route = useRoute<DetailRoute>();
  const { recordId } = route.params;

  const {
    selectedRecord: record,
    isLoading,
    isUpdating,
    error,
    fetchRecord,
    markAttendance,
    confirmRecord,
    cancelRecord,
  } = useBookingStore();

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

  const handleCall = useCallback(() => {
    if (record?.clientPhone) {
      void Linking.openURL(`tel:${record.clientPhone}`);
    }
  }, [record]);

  const handleConfirm = useCallback(() => {
    Alert.alert('Подтверждение', 'Подтвердить запись?', [
      { text: 'Отмена', style: 'cancel' },
      {
        text: 'Подтвердить',
        onPress: () => void confirmRecord(recordId),
      },
    ]);
  }, [recordId, confirmRecord]);

  const handleComplete = useCallback(() => {
    Alert.alert('Завершение', 'Клиент пришёл на занятие?', [
      { text: 'Отмена', style: 'cancel' },
      {
        text: 'Пришёл',
        onPress: () => void markAttendance(recordId, 'COMPLETED'),
      },
      {
        text: 'Не пришёл',
        style: 'destructive',
        onPress: () => void markAttendance(recordId, 'NO_SHOW'),
      },
    ]);
  }, [recordId, markAttendance]);

  const handleCancel = useCallback(() => {
    Alert.alert('Отмена записи', 'Отменить запись?', [
      { text: 'Нет', style: 'cancel' },
      {
        text: 'Отменить',
        style: 'destructive',
        onPress: () => void cancelRecord(recordId),
      },
    ]);
  }, [recordId, cancelRecord, cancelReason]);

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

  const statusColor = STATUS_COLORS[record.status];
  const duration = getBookingDuration(record.startAt, record.endAt);
  const canConfirm = record.status === 'PENDING';
  const canMarkAttendance = record.status === 'CONFIRMED' || record.status === 'IN_PROGRESS';
  const canCancel = record.status === 'PENDING' || record.status === 'CONFIRMED';

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.content}>
      {error && (
        <View style={styles.errorBanner}>
          <Text style={styles.errorText}>{error}</Text>
        </View>
      )}

      {/* Status header */}
      <View style={[styles.statusHeader, { backgroundColor: statusColor + '15' }]}>
        <View style={[styles.statusDot, { backgroundColor: statusColor }]} />
        <Text style={[styles.statusLabel, { color: statusColor }]}>
          {STATUS_LABELS[record.status]}
        </Text>
        <Text style={styles.recordNumber}>#{record.number}</Text>
      </View>

      {/* Time card */}
      <View style={styles.card}>
        <View style={styles.cardHeader}>
          <Ionicons name="time-outline" size={20} color={colors.primary} />
          <Text style={styles.cardTitle}>Время</Text>
        </View>
        <Text style={styles.timeText}>{formatBookingTime(record.startAt, record.endAt)}</Text>
        <Text style={styles.dateText}>{formatDate(record.startAt)}</Text>
        <Text style={styles.durationBadge}>{duration} мин</Text>
      </View>

      {/* Client card */}
      <View style={styles.card}>
        <View style={styles.cardHeader}>
          <Ionicons name="person-outline" size={20} color={colors.primary} />
          <Text style={styles.cardTitle}>Клиент</Text>
        </View>
        <Text style={styles.clientName}>{record.clientName}</Text>
        {record.clientPhone && (
          <TouchableOpacity style={styles.phoneRow} onPress={handleCall} activeOpacity={0.7}>
            <Ionicons name="call-outline" size={16} color={colors.primary} />
            <Text style={styles.phoneText}>{record.clientPhone}</Text>
          </TouchableOpacity>
        )}
        {record.clientEmail && <Text style={styles.emailText}>{record.clientEmail}</Text>}
      </View>

      {/* Service card */}
      <View style={styles.card}>
        <View style={styles.cardHeader}>
          <Ionicons name="fitness-outline" size={20} color={colors.primary} />
          <Text style={styles.cardTitle}>Услуга</Text>
        </View>
        {record.service && <Text style={styles.serviceName}>{record.service.name}</Text>}
        {record.groupEventId && (
          <View style={styles.groupBadge}>
            <Ionicons name="people-outline" size={14} color={colors.primary} />
            <Text style={styles.groupBadgeText}>Групповое занятие</Text>
          </View>
        )}
        <View style={styles.priceRow}>
          <Text style={styles.priceLabel}>Стоимость:</Text>
          <Text style={styles.priceValue}>{record.price} ₽</Text>
        </View>
        {Number(record.paidAmount) > 0 && (
          <View style={styles.priceRow}>
            <Text style={styles.priceLabel}>Оплачено:</Text>
            <Text style={[styles.priceValue, { color: colors.success }]}>
              {record.paidAmount} ₽
            </Text>
          </View>
        )}
      </View>

      {/* Notes */}
      {record.notes && (
        <View style={styles.card}>
          <View style={styles.cardHeader}>
            <Ionicons name="document-text-outline" size={20} color={colors.primary} />
            <Text style={styles.cardTitle}>Заметки</Text>
          </View>
          <Text style={styles.notesText}>{record.notes}</Text>
        </View>
      )}

      {/* Cancel reason */}
      {record.cancelReason && (
        <View style={styles.card}>
          <View style={styles.cardHeader}>
            <Ionicons name="close-circle-outline" size={20} color={colors.error} />
            <Text style={[styles.cardTitle, { color: colors.error }]}>Причина отмены</Text>
          </View>
          <Text style={styles.notesText}>{record.cancelReason}</Text>
        </View>
      )}

      {/* Action buttons */}
      <View style={styles.actions}>
        {canConfirm && (
          <TouchableOpacity
            style={[styles.actionBtn, styles.confirmBtn]}
            onPress={handleConfirm}
            disabled={isUpdating}
            activeOpacity={0.7}
          >
            {isUpdating ? (
              <ActivityIndicator size="small" color={colors.white} />
            ) : (
              <>
                <Ionicons name="checkmark-circle" size={20} color={colors.white} />
                <Text style={styles.actionBtnText}>Подтвердить</Text>
              </>
            )}
          </TouchableOpacity>
        )}

        {canMarkAttendance && (
          <TouchableOpacity
            style={[styles.actionBtn, styles.attendanceBtn]}
            onPress={handleComplete}
            disabled={isUpdating}
            activeOpacity={0.7}
          >
            {isUpdating ? (
              <ActivityIndicator size="small" color={colors.white} />
            ) : (
              <>
                <Ionicons name="checkmark-done" size={20} color={colors.white} />
                <Text style={styles.actionBtnText}>Отметить посещение</Text>
              </>
            )}
          </TouchableOpacity>
        )}

        {canCancel && (
          <TouchableOpacity
            style={[styles.actionBtn, styles.cancelBtn]}
            onPress={handleCancel}
            disabled={isUpdating}
            activeOpacity={0.7}
          >
            <Ionicons name="close-circle" size={20} color={colors.error} />
            <Text style={[styles.actionBtnText, { color: colors.error }]}>Отменить запись</Text>
          </TouchableOpacity>
        )}
      </View>

      {/* Meta info */}
      <View style={styles.metaRow}>
        <Text style={styles.metaText}>
          Источник: {record.source} | Создано: {new Date(record.createdAt).toLocaleString('ru-RU')}
        </Text>
      </View>
    </ScrollView>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },
    content: {
      padding: spacing.lg,
      paddingBottom: 100,
    },
    loadingContainer: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: colors.background,
    },
    errorBanner: {
      backgroundColor: colors.error,
      padding: spacing.md,
      borderRadius: 8,
      marginBottom: spacing.md,
    },
    errorText: {
      ...typography.bodySmall,
      color: colors.white,
      textAlign: 'center',
    },
    statusHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      padding: spacing.lg,
      borderRadius: 12,
      marginBottom: spacing.md,
    },
    statusDot: {
      width: 10,
      height: 10,
      borderRadius: 5,
      marginRight: spacing.sm,
    },
    statusLabel: {
      ...typography.subtitle,
      fontWeight: '600',
      flex: 1,
    },
    recordNumber: {
      ...typography.body,
      color: colors.textMuted,
      fontWeight: '500',
    },
    card: {
      backgroundColor: colors.card,
      borderRadius: 12,
      padding: spacing.lg,
      marginBottom: spacing.md,
      shadowColor: colors.black,
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.08,
      shadowRadius: 8,
      elevation: 3,
    },
    cardHeader: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: spacing.md,
    },
    cardTitle: {
      ...typography.body,
      fontWeight: '600',
      color: colors.text,
      marginLeft: spacing.sm,
    },
    timeText: {
      ...typography.h3,
      color: colors.text,
      marginBottom: 2,
    },
    dateText: {
      ...typography.body,
      color: colors.textSecondary,
      marginBottom: spacing.xs,
    },
    durationBadge: {
      ...typography.bodySmall,
      color: colors.textMuted,
    },
    clientName: {
      ...typography.subtitle,
      color: colors.text,
      marginBottom: spacing.sm,
    },
    phoneRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
      marginBottom: spacing.xs,
    },
    phoneText: {
      ...typography.body,
      color: colors.primary,
    },
    emailText: {
      ...typography.bodySmall,
      color: colors.textSecondary,
    },
    serviceName: {
      ...typography.subtitle,
      color: colors.text,
      marginBottom: spacing.sm,
    },
    groupBadge: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: spacing.xs,
      backgroundColor: colors.primary + '15',
      paddingHorizontal: spacing.sm,
      paddingVertical: spacing.xs,
      borderRadius: 6,
      alignSelf: 'flex-start',
      marginBottom: spacing.sm,
    },
    groupBadgeText: {
      ...typography.bodySmall,
      color: colors.primary,
    },
    priceRow: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginTop: spacing.xs,
    },
    priceLabel: {
      ...typography.body,
      color: colors.textSecondary,
    },
    priceValue: {
      ...typography.body,
      fontWeight: '600',
      color: colors.text,
    },
    notesText: {
      ...typography.body,
      color: colors.textSecondary,
      lineHeight: 22,
    },
    actions: {
      gap: spacing.sm,
      marginBottom: spacing.lg,
    },
    actionBtn: {
      flexDirection: 'row',
      alignItems: 'center',
      justifyContent: 'center',
      gap: spacing.sm,
      paddingVertical: spacing.md,
      borderRadius: 12,
    },
    confirmBtn: {
      backgroundColor: '#2196F3',
    },
    attendanceBtn: {
      backgroundColor: colors.success,
    },
    cancelBtn: {
      backgroundColor: colors.error + '10',
      borderWidth: 1,
      borderColor: colors.error + '30',
    },
    actionBtnText: {
      ...typography.body,
      fontWeight: '600',
      color: colors.white,
    },
    metaRow: {
      padding: spacing.md,
      alignItems: 'center',
    },
    metaText: {
      ...typography.caption,
      color: colors.textMuted,
      textAlign: 'center',
    },
  });
