import {Alert, Image, Linking, Pressable, Text, View} from 'react-native';
import React, {useCallback, useEffect, useState} from 'react';
import {styles} from './styles';

const IDCARD = '../../assets/idcard.png';
const SELFIE = '../../assets/selfieimg.png';
const IDCARDBACK = '../../assets/backid.png';
const DLCARD = '../../assets/dl.png';
const Passport = '../../assets/passport.png';

import {CheckBox} from '@rneui/themed';
import {globalStyles} from '../../../globalStyles';
import {getBranding} from '../../branding';
import {useMyStepsVerification} from '../../provider/verification.context';

/**
 * A component for displaying the required documents for the KYC process and allowing the user to confirm their consent to the terms of use.
 *
 * @param {Object} props - The component props.
 * @param {boolean} props.isChecked - A boolean indicating whether the user has confirmed their consent.
 * @param {Function} props.handleCheckbox - A function that handles changes to the consent checkbox.
 * @param {string} props.selectedOption - The selected KYC document type.
 * @returns {JSX.Element} - The rendered component as a JSX element.
 */

type RequirementsDocumentsProps = {
  isChecked: boolean;
  handleCheckbox: () => void;
  selectedOption: string[];
  consenttermofuseLink?: string;
};

type DocStep = {
  type: 'doc_front' | 'doc_back' | 'doc_passport' | 'selfie';
  docType?: string;
  label: string;
};

const RequirementsDocuments = ({
  isChecked,
  handleCheckbox,
  selectedOption,
  consenttermofuseLink,
}: RequirementsDocumentsProps) => {
  const { t, isRTL } = useMyStepsVerification();
  const [documentSteps, setDocumentSteps] = useState<DocStep[]>([]);

  useEffect(() => {
    const steps: DocStep[] = [];
    selectedOption.forEach(item => {
      const docLabel = t.docLabels[item] || item;
      if (item === 'Passport') {
        steps.push({ type: 'doc_passport', docType: item, label: t.pictureFirstPage.replace('{doc}', docLabel) });
      } else {
        steps.push({ type: 'doc_front', docType: item, label: t.pictureFront.replace('{doc}', docLabel) });
        steps.push({ type: 'doc_back', docType: item, label: t.pictureBack.replace('{doc}', docLabel) });
      }
    });
    steps.push({ type: 'selfie', label: t.takeSelfie });
    setDocumentSteps(steps);
  }, [selectedOption, t]);

  const handleClick = async () => {
    if (consenttermofuseLink) {
      const supported = await Linking.canOpenURL(consenttermofuseLink);
      if (supported) {
        await Linking.openURL(consenttermofuseLink);
      } else {
        Alert.alert(`Don't know how to open this URL: ${consenttermofuseLink}`);
      }
    }
  };

  return (
    <>
      <View style={styles.mainContainer}>
        <View style={{flex: 1, flexDirection: 'column', marginTop: '10%'}}>
          {documentSteps.map((item, index) => {
            return (
              <View key={index} style={[styles.box, {marginTop: 18}]}>
                {item.type === 'selfie' ? (
                  <Image style={styles.tinyLogo} source={require(SELFIE)} />
                ) : (
                  <Image
                    style={styles.tinyLogo}
                    source={
                      item.type === 'doc_back'
                        ? require(IDCARDBACK)
                        : item.docType === 'Passport'
                        ? require(Passport)
                        : item.docType?.includes('ID Card')
                        ? require(IDCARD)
                        : require(DLCARD)
                    }
                  />
                )}
                <Text style={{marginRight: 10, fontSize: 14, fontWeight: 700, textAlign: isRTL ? 'right' : 'left'}}>
                  {item.label}
                </Text>
              </View>
            );
          })}
        </View>
      </View>
      <View
        style={{
          flex: 1,
          flexDirection: 'column',
          alignItems: 'flex-start',
          marginLeft: 15,
        }}>
        <View style={styles.row}>
          <View
            style={{
              flex: 1,
              flexDirection: 'row',
              justifyContent: 'center',
              marginTop: 10,
            }}>
            <CheckBox
              center
              checked={isChecked}
              onPress={handleCheckbox}
              wrapperStyle={styles.checkbox}
              size={24}
              containerStyle={styles.transparent}
              checkedColor={getBranding().colors.primary}
            />
            {consenttermofuseLink && (
              <Text style={[styles.subHeading, {marginTop: 10}]}>
                {consenttermofuseLink && (
                  <Pressable onPress={handleClick}>
                    <Text style={[styles.note, globalStyles.textBold]}>
                      {t.termsAndConditions}
                    </Text>
                  </Pressable>
                )}{' '}
                {t.termsAgreement}
              </Text>
            )}
            {!consenttermofuseLink && (
              <Text style={[styles.subHeading, {marginTop: 16}]}>
                {t.readSteps}
              </Text>
            )}
          </View>
        </View>
      </View>
    </>
  );
};

export default RequirementsDocuments;
