import { useEffect, useRef, useState } from 'react';
import { Platform, Pressable, StyleSheet, Text, View } from 'react-native';
import { CameraView, type CameraType } from 'expo-camera';
import { SwitchCamera } from 'lucide-react-native';
import { logError } from '@/lib/errors';
import {
  acquireRecordingAudioSession,
  releaseRecordingAudioSession,
} from '@/lib/recording-audio-session';

const MAX_DURATION_S = 60;
const VIDEO_BITRATE_BPS = 1_200_000;

interface VideoRecordingOverlayProps {
  onComplete: (result: { uri: string; durationMs: number }) => void;
  onCancel: () => void;
}

export function VideoRecordingOverlay({
  onComplete,
  onCancel,
}: VideoRecordingOverlayProps) {
  const cameraRef = useRef<CameraView>(null);
  const [cameraReady, setCameraReady] = useState(false);
  const [recording, setRecording] = useState(false);
  const [elapsedMs, setElapsedMs] = useState(0);
  const [facing, setFacing] = useState<CameraType>('front');
  const startedAtRef = useRef<number | null>(null);
  const cancelledRef = useRef(false);

  useEffect(() => {
    return () => {
      cancelledRef.current = true;
      void releaseRecordingAudioSession().catch((err) =>
        logError(err, { scope: 'compose.video.exit' }),
      );
    };
  }, []);

  const startRecording = async () => {
    const cam = cameraRef.current;
    if (!cam || recording || !cameraReady) return;

    try {
      await acquireRecordingAudioSession();
    } catch (err) {
      logError(err, { scope: 'compose.video.audioSession' });
      onCancel();
      return;
    }

    setRecording(true);
    startedAtRef.current = Date.now();

    let result: { uri: string } | undefined;
    try {
      result = await cam.recordAsync({
        maxDuration: MAX_DURATION_S,
        ...(Platform.OS === 'ios' ? { codec: 'hvc1' as const } : {}),
      });
    } catch (err) {
      if (cancelledRef.current) return;
      logError(err, { scope: 'compose.video.recordAsync' });
      onCancel();
      return;
    } finally {
      void releaseRecordingAudioSession().catch((err) =>
        logError(err, { scope: 'compose.video.release' }),
      );
    }
    if (cancelledRef.current) return;

    const durationMs =
      startedAtRef.current !== null ? Date.now() - startedAtRef.current : 0;
    if (result?.uri) {
      onComplete({ uri: result.uri, durationMs });
    } else {
      onCancel();
    }
  };

  const stopRecording = () => {
    cameraRef.current?.stopRecording();
  };

  const cancel = () => {
    cancelledRef.current = true;
    if (recording) {
      cameraRef.current?.stopRecording();
    }
    onCancel();
  };

  useEffect(() => {
    if (!recording) return;
    const interval = setInterval(() => {
      if (startedAtRef.current === null) return;
      setElapsedMs(Date.now() - startedAtRef.current);
    }, 250);
    return () => clearInterval(interval);
  }, [recording]);

  const elapsedSec = Math.floor(elapsedMs / 1000);

  return (
    <View style={StyleSheet.absoluteFill} className="bg-black">
      <CameraView
        ref={cameraRef}
        style={StyleSheet.absoluteFill}
        facing={facing}
        videoQuality="480p"
        videoBitrate={VIDEO_BITRATE_BPS}
        mode="video"
        mute={false}
        onCameraReady={() => setCameraReady(true)}
      />

      {!recording && cameraReady ? (
        <View className="absolute top-0 right-0 pt-14 pr-5">
          <Pressable
            onPress={() => setFacing((f) => (f === 'front' ? 'back' : 'front'))}
            accessibilityLabel="Flip camera"
            className="h-11 w-11 items-center justify-center rounded-full bg-white/15"
          >
            <SwitchCamera color="white" size={22} strokeWidth={1.75} />
          </Pressable>
        </View>
      ) : null}

      {recording ? (
        <View
          pointerEvents="none"
          className="absolute top-0 left-0 right-0 items-center pt-16"
        >
          <View className="bg-red-500/90 flex-row items-center gap-2 rounded-full px-3 py-1.5">
            <View className="h-2 w-2 rounded-full bg-white" />
            <Text className="text-white text-xs font-semibold tracking-wide">
              REC · {elapsedSec.toString().padStart(2, '0')}s
            </Text>
          </View>
        </View>
      ) : null}

      <View className="absolute inset-x-0 bottom-12 flex-row items-center justify-around px-8">
        <Pressable
          onPress={cancel}
          accessibilityLabel="Cancel"
          className="rounded-full bg-white/15 px-6 py-3"
        >
          <Text className="text-white text-base font-medium">Cancel</Text>
        </Pressable>
        {recording ? (
          <Pressable
            onPress={stopRecording}
            accessibilityLabel="Stop recording"
            className="rounded-full bg-white px-7 py-3"
          >
            <Text className="text-black text-base font-semibold">Stop</Text>
          </Pressable>
        ) : (
          <Pressable
            onPress={startRecording}
            disabled={!cameraReady}
            accessibilityLabel="Start recording"
            className={
              cameraReady
                ? 'h-20 w-20 items-center justify-center rounded-full bg-white'
                : 'h-20 w-20 items-center justify-center rounded-full bg-white/40'
            }
          >
            <View className="h-16 w-16 rounded-full bg-red-500" />
          </Pressable>
        )}
      </View>
    </View>
  );
}
