import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
  View, Text, TouchableOpacity, StyleSheet,
} from 'react-native';
import { colors } from '../../theme/colors';
import { typography } from '../../theme/typography';
import { spacing } from '../../theme/spacing';

type CallState = 'CALLING' | 'ACTIVE' | 'ENDED';

const CALL_STATE_LABELS: Record<CallState, string> = {
  CALLING: 'Вызов...',
  ACTIVE: 'Разговор',
  ENDED: 'Завершён',
};

interface CallScreenProps {
  clientName?: string;
  phoneNumber: string;
  onEndCall?: () => void;
}

function formatTimer(seconds: number): string {
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
}

export function CallScreen({
  clientName,
  phoneNumber,
  onEndCall,
}: CallScreenProps): React.JSX.Element {
  const styles = createStyles();
  const [callState, setCallState] = useState<CallState>('CALLING');
  const [elapsed, setElapsed] = useState(0);
  const [isMuted, setIsMuted] = useState(false);
  const [isSpeaker, setIsSpeaker] = useState(false);
  const [showKeypad, setShowKeypad] = useState(false);
  const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    // Simulate call being answered after 3 seconds
    const connectTimeout = setTimeout(() => {
      if (callState === 'CALLING') setCallState('ACTIVE');
    }, 3000);
    return () => clearTimeout(connectTimeout);
  }, [callState]);

  useEffect(() => {
    if (callState === 'ACTIVE') {
      timerRef.current = setInterval(() => {
        setElapsed((prev) => prev + 1);
      }, 1000);
    }
    return () => {
      if (timerRef.current) clearInterval(timerRef.current);
    };
  }, [callState]);

  const handleEndCall = useCallback(() => {
    setCallState('ENDED');
    if (timerRef.current) clearInterval(timerRef.current);
    onEndCall?.();
  }, [onEndCall]);

  const handleToggleMute = useCallback(() => {
    setIsMuted((prev) => !prev);
  }, []);

  const handleToggleSpeaker = useCallback(() => {
    setIsSpeaker((prev) => !prev);
  }, []);

  const handleToggleKeypad = useCallback(() => {
    setShowKeypad((prev) => !prev);
  }, []);

  const displayName = clientName ?? phoneNumber;
  const statusLabel = CALL_STATE_LABELS[callState];
  const isEnded = callState === 'ENDED';

  const KEYPAD_ROWS = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7', '8', '9'],
    ['*', '0', '#'],
  ];

  return (
    <View style={styles.container}>
      <View style={styles.infoSection}>
        <View style={styles.avatarPlaceholder}>
          <Text style={styles.avatarText}>
            {(clientName ?? phoneNumber).charAt(0).toUpperCase()}
          </Text>
        </View>
        <Text style={styles.displayName} numberOfLines={1}>{displayName}</Text>
        {clientName && (
          <Text style={styles.phoneNumber}>{phoneNumber}</Text>
        )}
        <Text style={[styles.status, isEnded && styles.statusEnded]}>
          {statusLabel}
        </Text>
        <Text style={styles.timer}>{formatTimer(elapsed)}</Text>
      </View>

      {showKeypad && (
        <View style={styles.keypadContainer}>
          {KEYPAD_ROWS.map((row, rowIdx) => (
            <View key={rowIdx} style={styles.keypadRow}>
              {row.map((digit) => (
                <TouchableOpacity
                  key={digit}
                  style={styles.keypadButton}
                  activeOpacity={0.6}
                  disabled={isEnded}
                >
                  <Text style={styles.keypadDigit}>{digit}</Text>
                </TouchableOpacity>
              ))}
            </View>
          ))}
        </View>
      )}

      <View style={styles.actionsSection}>
        <View style={styles.actionsRow}>
          <TouchableOpacity
            style={[styles.actionButton, isMuted && styles.actionButtonActive]}
            onPress={handleToggleMute}
            activeOpacity={0.7}
            disabled={isEnded}
          >
            <Text style={[styles.actionIcon, isMuted && styles.actionIconActive]}>
              {isMuted ? 'M' : 'M'}
            </Text>
            <Text style={[styles.actionLabel, isMuted && styles.actionLabelActive]}>
              {isMuted ? 'Вкл. звук' : 'Без звука'}
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.actionButton, isSpeaker && styles.actionButtonActive]}
            onPress={handleToggleSpeaker}
            activeOpacity={0.7}
            disabled={isEnded}
          >
            <Text style={[styles.actionIcon, isSpeaker && styles.actionIconActive]}>
              S
            </Text>
            <Text style={[styles.actionLabel, isSpeaker && styles.actionLabelActive]}>
              {isSpeaker ? 'Динамик' : 'Динамик'}
            </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={[styles.actionButton, showKeypad && styles.actionButtonActive]}
            onPress={handleToggleKeypad}
            activeOpacity={0.7}
            disabled={isEnded}
          >
            <Text style={[styles.actionIcon, showKeypad && styles.actionIconActive]}>
              #
            </Text>
            <Text style={[styles.actionLabel, showKeypad && styles.actionLabelActive]}>
              Клавиши
            </Text>
          </TouchableOpacity>
        </View>

        <TouchableOpacity
          style={[styles.endCallButton, isEnded && styles.endCallButtonDisabled]}
          onPress={handleEndCall}
          activeOpacity={0.7}
          disabled={isEnded}
        >
          <Text style={styles.endCallIcon}>X</Text>
        </TouchableOpacity>
        <Text style={styles.endCallLabel}>
          {isEnded ? 'Звонок завершён' : 'Завершить'}
        </Text>
      </View>
    </View>
  );
}

const SEMI_WHITE = 'rgba(255, 255, 255, 0.12)';
const FADED_WHITE = 'rgba(255, 255, 255, 0.7)';

const createStyles = () => StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.salesCard, justifyContent: 'space-between', paddingTop: spacing.xxxl * 2, paddingBottom: spacing.xxxl },
  infoSection: { alignItems: 'center', paddingHorizontal: spacing.lg },
  avatarPlaceholder: { width: 96, height: 96, borderRadius: 48, backgroundColor: 'rgba(255, 255, 255, 0.15)', alignItems: 'center', justifyContent: 'center', marginBottom: spacing.lg },
  avatarText: { ...typography.h1, color: colors.white, fontSize: 36 },
  displayName: { ...typography.h2, color: colors.white, marginBottom: spacing.xs, textAlign: 'center' },
  phoneNumber: { ...typography.body, color: 'rgba(255, 255, 255, 0.6)', marginBottom: spacing.sm },
  status: { ...typography.bodySmall, color: colors.success, marginBottom: spacing.xs },
  statusEnded: { color: colors.error },
  timer: { ...typography.h3, color: colors.white, fontVariant: ['tabular-nums'] },
  keypadContainer: { paddingHorizontal: spacing.xxxl * 2, paddingVertical: spacing.md },
  keypadRow: { flexDirection: 'row', justifyContent: 'center', marginBottom: spacing.sm },
  keypadButton: { width: 64, height: 64, borderRadius: 32, backgroundColor: SEMI_WHITE, alignItems: 'center', justifyContent: 'center', marginHorizontal: spacing.md },
  keypadDigit: { ...typography.h3, color: colors.white },
  actionsSection: { alignItems: 'center', paddingHorizontal: spacing.lg },
  actionsRow: { flexDirection: 'row', justifyContent: 'center', marginBottom: spacing.xxl },
  actionButton: { width: 72, height: 72, borderRadius: 36, backgroundColor: SEMI_WHITE, alignItems: 'center', justifyContent: 'center', marginHorizontal: spacing.md },
  actionButtonActive: { backgroundColor: colors.white },
  actionIcon: { ...typography.subtitle, color: colors.white, marginBottom: 2 },
  actionIconActive: { color: colors.salesCard },
  actionLabel: { ...typography.caption, color: FADED_WHITE, fontSize: 10 },
  actionLabelActive: { color: colors.salesCard },
  endCallButton: { width: 72, height: 72, borderRadius: 36, backgroundColor: colors.error, alignItems: 'center', justifyContent: 'center', marginBottom: spacing.sm },
  endCallButtonDisabled: { opacity: 0.5 },
  endCallIcon: { ...typography.h3, color: colors.white, fontWeight: '700' },
  endCallLabel: { ...typography.caption, color: FADED_WHITE },
});
