/**
 * ActiveCallScreen.tsx — the in-call experience. Immersive dark screen with the
 * caller, a live MM:SS timer, the 6-button control grid (Mute, Keypad, Speaker,
 * Hold, Add — placeholder, and Contacts — placeholder) and a big red hang-up.
 *
 * The <RTCView>/audio element is invisible: react-native-webrtc plays remote
 * audio through the device automatically once InCallManager routes it. We keep a
 * hidden sink here for platforms that need an explicit stream attach.
 */
import React, { useEffect, useState } from 'react';
import { View, Text, Pressable, StyleSheet, SafeAreaView } from 'react-native';
// import { RTCView } from 'react-native-webrtc'; // enable if you attach remote stream to a view
import Avatar from '../components/Avatar';
import CallActionButton from '../components/CallActionButton';
import { colors, spacing, typography } from '../theme';

export type CallPhase = 'connecting' | 'ringing' | 'active' | 'held' | 'ended';

interface Props {
  caller: string;
  phase: CallPhase;
  muted: boolean;
  speaker: boolean;
  held: boolean;
  onMute: () => void;
  onSpeaker: () => void;
  onHold: () => void;
  onHangup: () => void;
  onKeypad?: () => void;
}

export default function ActiveCallScreen(props: Props) {
  const { caller, phase, muted, speaker, held } = props;
  const [seconds, setSeconds] = useState(0);

  // Start the timer only once media is up.
  useEffect(() => {
    if (phase !== 'active' && phase !== 'held') return;
    const t = setInterval(() => setSeconds((s) => s + 1), 1000);
    return () => clearInterval(t);
  }, [phase]);

  const statusText =
    phase === 'connecting' ? 'Connecting…'
    : phase === 'ringing' ? 'Ringing…'
    : phase === 'held' ? 'On hold'
    : phase === 'ended' ? 'Call ended'
    : formatDuration(seconds);

  return (
    <SafeAreaView style={styles.safe}>
      {/* Caller */}
      <View style={styles.top}>
        <Avatar name={caller} size={112} light />
        <Text style={styles.name}>{caller}</Text>
        <Text style={styles.status}>{statusText}</Text>
      </View>

      {/* Control grid */}
      <View style={styles.grid}>
        <CallActionButton icon={muted ? '🔇' : '🎙'} label="Mute" active={muted} onPress={props.onMute} />
        <CallActionButton icon="⌨️" label="Keypad" onPress={props.onKeypad || (() => {})} />
        <CallActionButton icon={speaker ? '🔊' : '🔈'} label="Speaker" active={speaker} onPress={props.onSpeaker} />
        <CallActionButton icon={held ? '▶️' : '⏸'} label="Hold" active={held} onPress={props.onHold} />
        <CallActionButton icon="➕" label="Add" disabled onPress={() => {}} />
        <CallActionButton icon="👥" label="Contacts" disabled onPress={() => {}} />
      </View>

      {/* Hang up */}
      <View style={styles.hangWrap}>
        <Pressable
          onPress={props.onHangup}
          style={({ pressed }) => [styles.hang, pressed && { opacity: 0.8 }]}
        >
          <Text style={styles.hangIcon}>📞</Text>
        </Pressable>
      </View>
    </SafeAreaView>
  );
}

function formatDuration(s: number): string {
  const m = Math.floor(s / 60);
  const sec = s % 60;
  return `${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
}

const HANG = 74;
const styles = StyleSheet.create({
  safe: { flex: 1, backgroundColor: colors.callBg, justifyContent: 'space-between' },
  top: { alignItems: 'center', marginTop: spacing.xxl },
  name: { ...typography.callerName, color: colors.callText, marginTop: spacing.lg, textAlign: 'center', paddingHorizontal: spacing.lg },
  status: { ...typography.status, color: colors.callTextSecondary, marginTop: spacing.sm },
  grid: {
    flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center',
    rowGap: spacing.lg, columnGap: spacing.md, paddingHorizontal: spacing.xl,
  },
  hangWrap: { alignItems: 'center', paddingBottom: spacing.xxl },
  hang: {
    width: HANG, height: HANG, borderRadius: HANG / 2, backgroundColor: colors.decline,
    alignItems: 'center', justifyContent: 'center',
    transform: [{ rotate: '135deg' }], // rotate the phone glyph into a "hang up"
  },
  hangIcon: { fontSize: 32 },
});
