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

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

type FaceScanFunctions = Omit<InitialiseLivenessScanResult, 'component'>;

const GetidLivenessScanWrapper = ({
  sdk,
  onComplete,
  onError,
}: FaceScanProps) => {
  const [captureClicked, setCaptureClicked] = useState<boolean>(false);
  const [hintMessage, setHintMessage] = useState<string>('');
  const [sdkFunctions, setSdkFunctions] = useState<FaceScanFunctions>({
    capture: () => Promise.resolve(),
    stopCapture: () => {},
  });
  const [error, setError] = useState<any>(null);

  const [faceComponent, setFaceComponent] = useState<React.JSX.Element>();
  const [isCameraReady, setIsCameraReady] = useState(false);

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

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

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

  useEffect(() => {
    const initDocScan = async () => {
      const initialiseFaceScan = sdk.initialiseLivenessScan;

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

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

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

  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>

        {error && <Text style={styles.textLoading}>Error: {error}</Text>}

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

        <View style={styles.btnTakePicture}>
          <Button
            title={captureClicked ? 'Stop capture' : 'Capture'}
            onPress={() => {
              // subcribe to the capture promise, whenever the takePicture func is called, this promise will be resolved
              if (captureClicked) {
                sdkFunctions.stopCapture?.();
                setCaptureClicked((capture: boolean) => !capture);
              } else {
                setError(null);
                setCaptureClicked((capture: boolean) => !capture);
                sdkFunctions
                  .capture?.()
                  .then(() => {
                    console.log('Face capture completed');
                    setCaptureClicked(false);
                    onComplete?.();
                  })
                  .catch((e) => {
                    setCaptureClicked(false);
                    setError(e.message);
                  });
              }
            }}
          />
        </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(GetidLivenessScanWrapper);
