import React, {useRef, useState, useEffect} from 'react';
import {StyleProp, View, ViewStyle} from 'react-native';
import {useTranslation} from 'react-i18next';
import SignatureScreen, {SignatureViewRef} from 'react-native-signature-canvas';
import {Dialog, BottomModalFooterProps} from '@components';
import {useInstanceId} from '@redux/selectors';
import {WILL_DER_INSTANCE_ID} from '@shared/constants';
import {SHARED_STRINGS} from '@shared/strings';
import {useTheme} from '@shared/theme';

import {getDigitalSignatureDialogStyle, styles} from './styles';
import {SignatureData} from './interfaces';

export interface DigitalSignatureDialogProps {
  isVisible: boolean;
  title: string;
  onCloseDialog: () => void;
  onAccept: (signature: string) => void;
  acceptText?: string;
  isRequired?: boolean;
  isLoading?: boolean;
  style?: StyleProp<ViewStyle>;
  fullScreen?: boolean;
  locked?: boolean;
  bottomModalFooterProps?: BottomModalFooterProps;
  value?: Nullable<string>;
}

const MIN_POINTS_COUNT = 10;

export function DigitalSignatureDialog({
  isVisible,
  onCloseDialog,
  title,
  onAccept,
  isLoading,
  acceptText,
  style,
  fullScreen = true,
  locked = true,
  bottomModalFooterProps,
  value,
}: DigitalSignatureDialogProps) {
  const ref = useRef<SignatureViewRef>(null);
  const {t} = useTranslation();
  const {isDarkMode, theme} = useTheme();
  const instanceId = useInstanceId();
  const isWillDerInstance = instanceId === WILL_DER_INSTANCE_ID;
  const [hasSignature, setHasSignature] = useState(false);
  const signatureBackgroundColor = theme.background.layout.default;
  const signatureBorderColor = isDarkMode
    ? signatureBackgroundColor
    : theme.border.neutral.default;
  const signatureBorderWidth = isDarkMode ? 0 : 1;
  const signaturePenColor = theme.text.neutral.default;
  // The canvas pixel buffer must stay transparent so the captured PNG embeds
  // cleanly into signed PDFs. Using a themed solid color here would bake an
  // opaque rectangle behind the signature in the final document.
  const signatureCanvasBackgroundColor = 'transparent';

  useEffect(() => {
    if (isVisible) {
      setHasSignature(false);
    }
  }, [isVisible, setHasSignature]);

  const onClear = () => {
    ref.current?.clearSignature();
    setHasSignature(false);
  };

  const onConfirm = () => {
    ref.current?.readSignature();
  };

  const onOkSignature = (signature: string) =>
    !isLoading && onAccept(signature);

  const onEnd = () => {
    ref.current?.getData();
  };

  const onGetData = (data: string) => {
    if (!data || data.length === 0) return;

    let parsedData: SignatureData;
    try {
      parsedData = JSON.parse(data);
    } catch {
      setHasSignature(false);
      return;
    }

    if (!Array.isArray(parsedData) || parsedData.length === 0) {
      setHasSignature(false);
      return;
    }

    const totalPoints = parsedData.reduce((sum, path) => {
      if (path?.points && Array.isArray(path.points)) {
        return sum + path.points.length;
      }
      return sum;
    }, 0);

    setHasSignature(totalPoints >= MIN_POINTS_COUNT);
  };

  const onEmpty = () => {
    setHasSignature(false);
  };

  return (
    <Dialog
      locked={locked}
      fullScreen={fullScreen}
      isVisible={isVisible}
      title={title}
      onClose={onCloseDialog}
      enableContentPanningGesture={false}
      footer={{
        primaryButton: {
          disabled: isLoading || !hasSignature,
          text: acceptText || t(SHARED_STRINGS.SIGN),
          onPress: onConfirm,
          isLoading,
          // TODO: Remove this line after testing
          variant: isWillDerInstance ? 'secondary' : 'primary',
        },
        secondaryButton: {
          text: t(SHARED_STRINGS.CLEAR),
          onPress: onClear,
          disabled: isLoading,
        },
        ...bottomModalFooterProps,
      }}>
      <View
        style={[
          styles.signatureScreenContainer,
          {
            backgroundColor: signatureBackgroundColor,
            borderColor: signatureBorderColor,
            borderWidth: signatureBorderWidth,
          },
          style,
        ]}>
        <SignatureScreen
          backgroundColor={signatureCanvasBackgroundColor}
          penColor={signaturePenColor}
          ref={ref}
          onOK={onOkSignature}
          onEnd={onEnd}
          onGetData={onGetData}
          onEmpty={onEmpty}
          autoClear={false}
          webStyle={getDigitalSignatureDialogStyle(theme)}
          nestedScrollEnabled
          {...(value && {dataURL: value})}
        />
      </View>
    </Dialog>
  );
}
