import {Platform, Pressable, StyleSheet, Text, View} from 'react-native';
import React, {useEffect} from 'react';
import {styles} from './styles';
import Header from '../header/header.component';
import Footer from '../footer/footer.component';
import CaptureButton from '../../design-system/capture-button/capture-button.component';
import FlipButton from '../../design-system/flip-button/flip-button.component';
import {globalStyles} from '../../../globalStyles';
import {getBranding} from '../../branding';
import Icon from 'react-native-vector-icons/Ionicons';
import {
  Camera,
  useCameraDevice,
  useCameraDevices,
} from 'react-native-vision-camera';
import {useMyStepsVerification} from '../../provider/verification.context';
import Toast from 'react-native-toast-message';

type props = {
  webcamRef: React.MutableRefObject<any>;
  userStep: number;
  findOutStepContent: () => {
    step: number;
    heading: string;
    subHeading: string;
  };
  goBackUserSteps: (index?: number) => void;
  handlerUserSteps: () => void;
  buttonText: (userStep: number) => any;
  handleSingleCapturePhoto: (step: number) => void;
  skipGuidanceScreens?: boolean;
};

/**
 * A component for capturing a selfie using the device's camera.
 *
 * @param {Object} props - The component props.
 * @param {Object} props.webcamRef - A mutable ref object for accessing the camera component.
 * @param {string} props.cameraMode - The type of camera to use (front or back).
 * @param {number} props.userStep - The current step in the user verification process.
 * @param {Function} props.findOutStepContent - A function that returns an object with the heading and subheading text for the current verification step.
 * @param {Function} props.goBackUserSteps - A function that allows the user to go back to the previous verification step.
 * @param {Function} props.handlerUserSteps - A function that handles the user's progress through the verification steps.
 * @param {Function} props.buttonText - A function that returns the text to display on the footer button based on the current verification step.
 * @param {Function} props.handleSingleCapturePhoto - A function that handles capturing a single photo for the current verification step.
 * @param {Function} props.flipCamera - A function that switches between the front and back camera.
 * @returns {JSX.Element} - The rendered component as a JSX element.
 */

const CaptureSelfie = ({
  webcamRef,
  userStep,
  findOutStepContent,
  goBackUserSteps,
  handlerUserSteps,
  buttonText,
  handleSingleCapturePhoto,
  skipGuidanceScreens,
}: props) => {
  const device = useCameraDevice('front');
  const flipCamera = () => {};
  let context = useMyStepsVerification();
  const { t } = context;

  useEffect(() => {
    if (!device || !webcamRef?.current) return;
    let cancelled = false;
    const checkRes = async () => {
      try {
        const probe = await webcamRef.current?.takePhoto?.({
          enableShutterSound: false,
          qualityPrioritization: 'speed',
        });
        if (cancelled || !probe?.width || !probe?.height) return;
        const w = Math.max(probe.width, probe.height);
        const h = Math.min(probe.width, probe.height);
        if (w < 1920 && h < 1080) {
          Toast.show({
            type: 'info',
            text1: t.lowCameraResolution,
            text2: t.frontCameraMsg.replace('{w}', String(w)).replace('{h}', String(h)),
            visibilityTime: 5000,
          });
        }
      } catch (_) {}
    };
    const timer = setTimeout(checkRes, Platform.OS === 'android' ? 500 : 1500);
    return () => { cancelled = true; clearTimeout(timer); };
  }, [device]);

  return (
    <View style={styles.container}>
      {/* Camera Screen */}
      {device && (
        <Camera
          style={[styles.camera]}
          device={device}
          isActive={true}
          ref={webcamRef}
          photo={true}
          video={true}
        />
      )}

      {/* Oval Screen */}
      <View style={styles.blurredContainer} />
      {/* Content Screen */}
      <View style={[styles.absoluteContainer, StyleSheet.absoluteFill]}>
        <View
          style={{
            flex: 1,
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}>
          <Pressable
            onPress={() => {
              context.skipGuidanceScreens
                ?(context.allowSingle && context.selectedOption == "Passport") ? goBackUserSteps(4) : goBackUserSteps(2)
                : goBackUserSteps();
            }}>
            <Icon
              name="arrow-back"
              size={30}
              color={'white'}
              style={{marginTop: 10}}
            />
          </Pressable>

          <View style={{alignItems: 'center', marginTop: 20}}>
            <Text
              style={[
                styles.heading,
                globalStyles.textMedium,
                {
                  color:
                    getBranding().colors.title_camera_color ||
                    getBranding().colors.primary,
                  fontSize: 18,
                  fontWeight: 700,
                },
              ]}>
              {findOutStepContent()?.heading}
            </Text>
            <Text style={[globalStyles.textMedium, {color: 'white'}]}>
              {findOutStepContent()?.subHeading}
            </Text>
          </View>

          {context.onCancel ? (
            <Pressable onPress={context.onCancel} style={({pressed}) => pressed && styles.opacity}>
              <Icon name="close" size={30} color={'white'} style={{marginTop: 10}} />
            </Pressable>
          ) : (
            <View style={{width: 30}} />
          )}
        </View>
        <View style={styles.buttonContainer}>
          <View style={{flex: 1, alignItems: 'flex-start'}}>
            <Footer
              onPress={handlerUserSteps}
              buttonText={buttonText}
              userStep={userStep}
            />
          </View>
          <View style={{flex: 1, alignItems: 'center'}}>
            <CaptureButton onClick={() => handleSingleCapturePhoto(userStep)} />
            <Text
              style={[
                styles.selfieHeading,
                globalStyles.textRegular,
                {color: 'white', fontSize: 17, fontWeight: 700},
              ]}>
              {t.takeASelfie}
            </Text>
            <Text
              style={[
                styles.selfieSubHeading,
                globalStyles.textMedium,
                {opacity: 0},
              ]}>
              {t.faceVerification}
            </Text>
          </View>
          <View style={{flex: 1, opacity: 0, alignItems: 'flex-end'}}>
            <FlipButton onClick={flipCamera} />
          </View>
        </View>
      </View>
    </View>
  );
};

export default CaptureSelfie;
