import {
  SafeAreaView,
  Button,
  StyleSheet,
  Text,
  View,
  StatusBar,
} from 'react-native';
import React, { useState } from 'react';
import { GetIdSdk } from '@get-id/react-native-sdk';
import GetidDocScanWrapper from './components/GetidDocScanWrapper';
import Config from 'react-native-config';
import GetidLivenessScanWrapper from './components/GetidLivenessScanWrapper';
import GetidSelfieScanWrapper from './components/GetidSelfieScanWrapper';

const API_URL = Config.API_URL || '';
const SDK_KEY = Config.SDK_KEY || '';
const FLOW = Config.FLOW || 'klarna-native';

export default function App() {
  const [getidSdkInstance, setGetidSdkInstance] = useState<GetIdSdk | null>();
  const [step, setStep] = useState(0);
  const [verificationCompleted, setVerificationCompleted] = useState(false);
  const [verificationStatus, setVerificationStatus] = useState<any>();
  const [applicationId, setApplicationId] = useState<string>();
  const [loading, setLoading] = useState(false);

  const [forceLiveness, setForceLiveness] = useState(false);
  const [forceDoc, setForceDoc] = useState(false);
  const [forceSelfie, setForceSelfie] = useState(false);
  const [appError, setAppError] = useState<string | null>(null);

  const startGetIdSdk = () => {
    if (!getidSdkInstance) {
      GetIdSdk.initialiseSDK({
        sdkKey: SDK_KEY,
        flow: FLOW,
        apiUrl: API_URL,
        externalId: 'test123',
        profile: [
          {
            value: 'John',
            category: 'First name',
          },
          {
            value: 'Doe',
            category: 'Last name',
          },
          {
            value: '1985-10-25',
            category: 'Date of birth',
          },
        ],
        acceptableDocuments: (supportedDocuments) => {
          const excludedDocumentVersions = ['CAN_P_ePassport_1580780960'];
          return supportedDocuments.map((doc) => ({
            ...doc,
            excludedDocumentVersions,
          }));
        },
      })
        .then((sdk) => {
          setGetidSdkInstance(sdk);
        })
        .catch((error) => {
          console.error('Error:', error);
        });
    }
    setAppError(null);
  };

  const nextStep = (additional: number = 0) =>
    setStep((s) => s + 1 + additional);

  const verifyApp = async () => {
    const verificationResults = await getidSdkInstance?.submitForVerification({
      timeoutInSeconds: 120,
      onVerificationStatusChange: (status) => {
        console.log('Verification status:', status);
        setVerificationStatus(status);
      },
      onApplicationIdChange: (appId) => {
        console.log('Application Id:', appId);
        setApplicationId(appId);
      },
    });

    console.log('Verification results:', verificationResults);
  };
  const onComplete = async () => {
    try {
      setLoading(true);

      await verifyApp();
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setVerificationCompleted(true);
      setLoading(false);
    }
  };

  const onError = (error: any) => {
    setGetidSdkInstance(null);
    setAppError(error.message);
  };

  if (!getidSdkInstance || appError) {
    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.header}> Klarna APP </Text>
        <View style={styles.buttons}>
          <Button
            title="Start GetId SDK (doc only)"
            onPress={() => {
              setForceDoc(true);
              startGetIdSdk();
            }}
          />
          <Button
            title="Start GetId SDK (Selfie)"
            onPress={() => {
              setStep(2);
              setForceSelfie(true);
              startGetIdSdk();
            }}
          />
          <Button
            title="Start GetId SDK (Liveness)"
            onPress={() => {
              setStep(3);
              setForceLiveness(true);
              startGetIdSdk();
            }}
          />
          <Button
            title="Start GetId SDK (doc + selfie + Liveness)"
            onPress={() => {
              startGetIdSdk();
            }}
          />
          {appError && <Text style={styles.appError}>Error: {appError}</Text>}
        </View>
      </SafeAreaView>
    );
  }

  if (verificationCompleted || loading) {
    return (
      <SafeAreaView style={styles.container}>
        <Text style={styles.header}>
          {loading ? 'Loading...' : 'Verification Completed'}
        </Text>
        {verificationStatus && (
          <Text style={styles.info}>
            Verification Status: {verificationStatus}
          </Text>
        )}
        {applicationId && (
          <Text style={styles.info}>Application Id: {applicationId}</Text>
        )}
      </SafeAreaView>
    );
  }

  console.log('Step:', step);
  return (
    <View style={styles.container}>
      <StatusBar translucent backgroundColor="transparent" />

      {step === 0 && (
        <GetidDocScanWrapper
          sdk={getidSdkInstance}
          onNextStep={nextStep}
          docType="front"
          onComplete={() => (forceDoc ? onComplete() : nextStep(1))}
          onError={onError}
        />
      )}
      {step === 1 && (
        <GetidDocScanWrapper
          sdk={getidSdkInstance}
          onNextStep={nextStep}
          docType="back"
          onComplete={() => (forceDoc ? onComplete() : nextStep())}
          onError={onError}
        />
      )}
      {(forceSelfie || step === 2) && (
        <GetidSelfieScanWrapper
          sdk={getidSdkInstance}
          onComplete={() => (forceSelfie ? onComplete() : nextStep())}
          onError={onError}
        />
      )}
      {(forceLiveness || step === 3) && (
        <GetidLivenessScanWrapper
          sdk={getidSdkInstance}
          onComplete={() => onComplete()}
          onError={onError}
        />
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    fontSize: 30,
    fontWeight: 'bold',
    textAlign: 'center',
    margin: 10,
    fontFamily: 'monospace',
    marginVertical: 50,
  },
  info: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
    fontFamily: 'monospace',
    marginVertical: 50,
  },
  buttons: { display: 'flex', flexDirection: 'column', gap: 20 },
  appError: {
    color: 'red',
    fontSize: 16,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});
