//@ts-nocheck
import { observer } from 'mobx-react-lite';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import {
  Alert,
  Platform,
  SafeAreaView,
  StyleSheet,
  TouchableOpacity,
  View,
} from 'react-native';
import { formatDDMMYYY, formatMoney } from '../../utils';
import {
  Camera as VisionCamera,
  useCameraDevice,
} from 'react-native-vision-camera';
import MButton from '../../components/MButton';
import { IconPause, IconPlay } from '../../assets/icons';
import { MText } from '../../components/MText';
import { useNavigation } from '@react-navigation/native';
import videoStore from './videoStore';
import {
  checkMultiple,
  requestMultiple,
  openSettings,
  PERMISSIONS,
  RESULTS,
} from 'react-native-permissions';
import Loading from '../../components/Loading';
import MHeader from '../../components/MHeader';

const COUNTDOWN_SECONDS = 3;

const getCameraPermissions = () =>
  Platform.OS === 'ios'
    ? [PERMISSIONS.IOS.CAMERA, PERMISSIONS.IOS.MICROPHONE]
    : [PERMISSIONS.ANDROID.CAMERA, PERMISSIONS.ANDROID.RECORD_AUDIO];

export const Video = observer(function Video(props: any) {
  const navigation = useNavigation();
  const camera = useRef(null);
  const [count, setCount] = useState(COUNTDOWN_SECONDS);
  const [isRecording, setIsRecording] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [passPermission, setPassPermission] = useState(false);
  const device = useCameraDevice('front');

  const loan = props?.route?.params?.loan;
  const content = useMemo(() => {
    return `Hôm nay ngày ${formatDDMMYYY(new Date())} tôi tên là ${
      loan?.fullname || ''
    } có thực hiện khoản vay tại Tima với số tiền là ${formatMoney(
      loan?.loanAmount || 0
    )}`;
  }, [loan?.fullname, loan?.loanAmount]);

  const requestPermissions = async () => {
    const permissions = getCameraPermissions();
    const statuses = await checkMultiple(permissions);
    const toRequest = permissions.filter(
      (permission) => statuses[permission] !== RESULTS.GRANTED
    );

    if (toRequest.length === 0) {
      setPassPermission(true);
      return true;
    }

    const requested = await requestMultiple(toRequest);
    const values = Object.values(requested);
    const allGranted = values.every((status) => status === RESULTS.GRANTED);
    const anyBlocked = values.some((status) => status === RESULTS.BLOCKED);

    if (!allGranted) {
      setPassPermission(false);
      Alert.alert(
        'Thông báo',
        anyBlocked
          ? 'Vui lòng bật quyền Camera và Micro trong Cài đặt để tiếp tục.'
          : 'Vui lòng cấp quyền Camera và Micro để tiếp tục.',
        anyBlocked
          ? [
              { text: 'Huỷ' },
              {
                text: 'Mở cài đặt',
                onPress: () => openSettings(),
              },
            ]
          : [{ text: 'OK' }]
      );
    }

    setPassPermission(allGranted);
    return allGranted;
  };

  useEffect(() => {
    requestPermissions();
    setCount(COUNTDOWN_SECONDS);
    const id = setInterval(() => {
      setCount((prev) => {
        if (prev <= 1) {
          clearInterval(id);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => clearInterval(id);
  }, []);

  const stopRecording = () => {
    if (!camera.current) return;
    camera.current.stopRecording();
    setIsRecording(false);
  };

  const startVideo = async () => {
    if (!camera.current || isLoading || isRecording || count > 0) {
      return;
    }
    const hasPermission = await requestPermissions();
    if (!hasPermission) return;

    setIsRecording(true);
    try {
      const data = await new Promise((resolve, reject) => {
        camera.current.startRecording({
          videoCodec: Platform.OS === 'ios' ? 'h264' : undefined,
          onRecordingFinished: resolve,
          onRecordingError: reject,
        });
      });

      setIsLoading(true);
      const uri = 'file://' + data.path;
      const formData = new FormData();
      formData.append('video', {
        name: data.path.split(/[\\/]/).pop(),
        uri,
        type: 'video/*',
      });

      videoStore.uploadVideo(
        loan?.id,
        formData,
        () => {
          setIsLoading(false);
          Alert.alert('Thông báo', 'Tải video lên thành công', [
            {
              text: 'Ok',
              onPress: () => navigation.goBack(),
            },
          ]);
        },
        () => {
          setIsLoading(false);
        }
      );
    } catch (err) {
      setIsRecording(false);
      setIsLoading(false);
      console.error(err);
      Alert.alert('Thông báo', 'Không thể quay video. Vui lòng thử lại.');
    }
  };

  return (
    <View
      style={{
        flex: 1,
      }}
    >
      <MHeader title="Quay video" onBack={() => navigation.goBack()} />
      <SafeAreaView style={{ flex: 1, backgroundColor: 'white' }}>
        <View style={{ flex: 1, justifyContent: 'center' }}>
          {count === 0 && (
            <View
              style={{
                position: 'absolute',
                bottom: 100,
                right: 0,
                left: 0,
                zIndex: 1,
                paddingHorizontal: 10,
                justifyContent: 'center',
                backgroundColor: 'black',
                paddingVertical: 10,
              }}
            >
              <MText
                style={{
                  color: 'white',
                  fontSize: 16,
                  textAlign: 'center',
                }}
              >
                {content}
              </MText>
            </View>
          )}
          {passPermission && device ? (
            <VisionCamera
              ref={camera}
              style={styles.preview}
              device={device}
              isActive={true}
              video={true}
              audio={true}
            />
          ) : null}
          <View
            style={{
              backgroundColor: '#00000080',
              justifyContent: 'center',
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              paddingVertical: 16,
            }}
          >
            {isRecording ? (
              <TouchableOpacity
                style={{
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                onPress={() => {
                  stopRecording();
                }}
              >
                <IconPause fill={'white'} width={60} height={60} />
              </TouchableOpacity>
            ) : (
              <TouchableOpacity
                style={{
                  justifyContent: 'center',
                  alignItems: 'center',
                }}
                disabled={videoStore.isLoading}
                onPress={() => {
                  startVideo();
                }}
              >
                <IconPlay fill={'white'} width={60} height={60} />
              </TouchableOpacity>
            )}
          </View>
        </View>
        <Loading isLoading={isLoading} />
      </SafeAreaView>
    </View>
  );
});

const styles = StyleSheet.create({
  preview: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
});
