import { useEffect } from 'react';
import { ActivityIndicator, Modal, Pressable, Text, View } from 'react-native';
import {
  initialWindowMetrics,
  SafeAreaProvider,
  SafeAreaView,
} from 'react-native-safe-area-context';
import { useVideoPlayer, VideoView } from 'expo-video';
import { Mic } from 'lucide-react-native';
import { toast } from 'sonner-native';
import { cn } from '@/lib/utils';
import { toUserMessage } from '@/lib/errors';

interface ReviewSheetProps {
  open: boolean;
  /** Local file URI from the recorder. */
  uri: string | null;
  mode: 'video' | 'audio' | null;
  durationMs: number;
  /**
   * True once the parent has flipped to the uploading state. The sheet stays
   * mounted (so playback doesn't tear down) and blocks all interaction behind
   * a "Sending..." overlay until the parent clears it.
   */
  sending: boolean;
  onSend: () => Promise<void>;
  onRetake: () => void;
  onCancel: () => void;
}

/**
 * Loop-plays the just-recorded clip and offers Retake / Send. WhatsApp-style
 * confirmation: any send-failure surfaces a toast and keeps the sheet open
 * so the user doesn't lose their take.
 */
export function ReviewSheet({
  open,
  uri,
  mode,
  durationMs,
  sending,
  onSend,
  onRetake,
  onCancel,
}: ReviewSheetProps) {
  const player = useVideoPlayer(uri ?? '', (p) => {
    p.loop = true;
    p.muted = false;
    p.audioMixingMode = 'mixWithOthers';
  });

  useEffect(() => {
    if (!open || !uri) return;
    if (sending) {
      player.pause();
    } else {
      player.play();
    }
  }, [open, uri, sending, player]);

  const handleSend = async () => {
    if (sending) return;
    try {
      await onSend();
    } catch (err) {
      toast.error(toUserMessage(err));
    }
  };

  const seconds = Math.max(1, Math.round(durationMs / 1000));

  return (
    <Modal
      visible={open}
      animationType="fade"
      transparent={false}
      onRequestClose={sending ? undefined : onCancel}
    >
      <SafeAreaProvider initialMetrics={initialWindowMetrics}>
        <View className="flex-1 bg-black">
          {uri ? (
            mode === 'audio' ? (
              <View className="flex-1 items-center justify-center px-8">
                <View className="bg-white/10 h-28 w-28 items-center justify-center rounded-full">
                  <Mic color="white" size={42} strokeWidth={1.5} />
                </View>
                <Text className="text-white mt-6 text-lg font-semibold">
                  Voice message · {seconds}s
                </Text>
                <Text className="text-white/50 mt-2 text-sm">
                  Tap send to share, or retake.
                </Text>
                <View className="absolute" style={{ width: 1, height: 1 }}>
                  <VideoView
                    style={{ width: 1, height: 1 }}
                    player={player}
                    nativeControls={false}
                  />
                </View>
              </View>
            ) : (
              <VideoView
                style={{ flex: 1 }}
                player={player}
                nativeControls={false}
                contentFit="cover"
                allowsFullscreen={false}
                allowsPictureInPicture={false}
              />
            )
          ) : null}

          <SafeAreaView
            edges={['top']}
            className="absolute top-0 left-0 right-0"
          >
            <View className="px-4 pt-3">
              <Pressable
                onPress={onCancel}
                disabled={sending}
                hitSlop={12}
                accessibilityLabel="Cancel"
              >
                <Text
                  className={cn(
                    'text-base',
                    sending ? 'text-white/30' : 'text-white/80',
                  )}
                >
                  Cancel
                </Text>
              </Pressable>
            </View>
          </SafeAreaView>

          <SafeAreaView
            edges={['bottom']}
            className="absolute bottom-0 left-0 right-0"
          >
            <View className="flex-row items-center justify-between px-6 pb-4 pt-3">
              <Pressable
                onPress={onRetake}
                disabled={sending}
                className={cn(
                  'rounded-full bg-white/15 px-5 py-3',
                  sending && 'opacity-40',
                )}
                accessibilityLabel="Retake"
              >
                <Text className="text-white text-base font-medium">Retake</Text>
              </Pressable>

              <Pressable
                onPress={handleSend}
                disabled={sending}
                className={cn(
                  'rounded-full px-7 py-3',
                  sending ? 'bg-white/40' : 'bg-white',
                )}
                accessibilityLabel="Send"
              >
                <Text className="text-black text-base font-semibold">
                  {sending ? 'Sending...' : 'Send'}
                </Text>
              </Pressable>
            </View>
          </SafeAreaView>

          {sending ? (
            <View className="absolute inset-0 items-center justify-center bg-black/85">
              <ActivityIndicator color="white" />
              <Text className="text-white/70 mt-4 text-sm">Sending...</Text>
            </View>
          ) : null}
        </View>
      </SafeAreaProvider>
    </Modal>
  );
}
