import { View, StyleSheet, Button, Text } from 'react-native';
import React, { memo, useCallback, useEffect, useState } from 'react';
import HintMessage from './HintMessage';
import { type GetIdSdk, GetidSdkTypes } from '@get-id/react-native-sdk';

type FaceScanProps = {
  sdk: GetIdSdk;
  onComplete?: () => void;
  onError?: (error: any) => void;
};

type FaceScanFunctions = {
  takePicture?: Function;
  capture?: Function;
  stopCapture?: Function;
};

const GetidSelfieScanWrapper = ({
  sdk,
  onComplete,
  onError,
}: FaceScanProps) => {
  const [hintMessage, setHintMessage] = useState<string>('');
  const [sdkFunctions, setSdkFunctions] = useState<FaceScanFunctions>({});
  const [captureClicked, setCaptureClicked] = useState(false);
  const [faceComponent, setFaceComponent] = useState<React.JSX.Element>();
  const [isCameraReady, setIsCameraReady] = useState(false);

  const onCameraReady = useCallback(() => {
    setIsCameraReady(true);
  }, []);

  const onUserHintChange = useCallback((hint: GetidSdkTypes.SelfieUserHint) => {
    console.log(`onUserHintChange: ${hint}`);
    setHintMessage(hint);
  }, []);

  const onServerValidationStarted = useCallback(() => {
    console.log(
      'onDocumentScanServerValidationStarted: Document scan server validation started'
    );
  }, []);

  useEffect(() => {
    const initFaceScan = async () => {
      const initialiseFaceScan = sdk.initialiseSelfie;

      try {
        const { component, ...functions } = await initialiseFaceScan({
          onServerValidationStarted,
          onCameraReady,
          onUserHintChange,
          useAutoCapture: true,
        });

        setFaceComponent(component);
        setSdkFunctions(functions);
      } catch (e: any) {
        console.error('Error initialising face scan', e);
        onError?.(e);
      }
    };

    initFaceScan();
  }, [
    sdk,
    onServerValidationStarted,
    onUserHintChange,
    onError,
    onCameraReady,
  ]);

  const startCapture = () => {
    setCaptureClicked(true);
    sdkFunctions
      .capture?.()
      .then(() => {
        console.log('Face image completed');
        onComplete?.();
      })
      .catch((error: GetidSdkTypes.SelfieError) => {
        console.error('Error:', error.message);
        stopCapture();
      });
  };

  const takePicture = () => {
    sdkFunctions.takePicture?.();
  };

  const stopCapture = () => {
    setCaptureClicked(false);
    sdkFunctions.stopCapture?.();
  };

  return (
    <>
      {!isCameraReady && (
        <View style={styles.containerLoading}>
          <Text>Loading...</Text>
        </View>
      )}
      <View
        style={{
          ...styles.containerFullPage,
          ...(isCameraReady ? {} : styles.hiddenPage),
        }}
      >
        {faceComponent}

        <Text style={styles.titleDescription}>Time for selfie</Text>

        {hintMessage && <HintMessage message={hintMessage} />}

        <View style={styles.btnTakePicture}>
          <Button
            title="Capture"
            disabled={captureClicked}
            onPress={startCapture}
          />
          <Button
            title={'Take picture'}
            color={'green'}
            disabled={!captureClicked}
            onPress={takePicture}
          />
        </View>
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  containerFullPage: {
    flex: 1,
    justifyContent: 'flex-end',
  },
  containerLoading: {
    flex: 1,
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 100,
    backgroundColor: 'white',
  },
  hiddenPage: {
    opacity: 0,
  },
  btnTakePicture: {
    color: 'white',
    textAlign: 'center',
    marginBottom: 50,
    marginHorizontal: 10,
    // flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: 'rgba(0, 0, 0, 0.9)',
  },
  textLoading: {
    color: 'white',
    fontSize: 24,
    textAlign: 'center',
    fontWeight: 'bold',
    marginBottom: 50,
  },
  titleDescription: {
    color: 'white',
    fontSize: 16,
    textAlign: 'center',
    fontWeight: 'bold',
    marginBottom: 'auto',
    marginTop: 80,
    alignSelf: 'center',
  },
});

export default memo(GetidSelfieScanWrapper);
