import React, { useState, useEffect } from 'react';
import { Modal, Button, Input } from '@akinon/next/components';
import { LoaderSpinner } from '@akinon/next/components';
import { useAppSelector } from '@akinon/next/redux/hooks';
import type { OTPModalProps } from '../types/custom-render.types';
import mpBlackLogo from '../assets/img/masterpass-black-logo.png';
import { handleResendOtp } from '../utils/response-handler';
import clsx from 'clsx';

const OTPModal: React.FC<OTPModalProps> = ({
  open,
  onClose,
  onSubmit,
  type,
  responseCode,
  description,
  texts
}) => {
  const { token, tokenData } = useAppSelector((state) => state.masterpassRest);
  const [otp, setOtp] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isResending, setIsResending] = useState(false);
  const [canResend, setCanResend] = useState(false);
  const [remainingTime, setRemainingTime] = useState(90);

  useEffect(() => {
    if (!open) {
      setError(null);
      setOtp('');
    }
  }, [open]);

  useEffect(() => {
    if (open && type === 'OTP') {
      setRemainingTime(90);
      setCanResend(false);
      const timer = setInterval(() => {
        setRemainingTime((prev) => {
          if (prev <= 1) {
            setCanResend(true);
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return () => clearInterval(timer);
    }
  }, [open, type, responseCode]);

  const handleSubmit = async () => {
    setError(null);
    setIsLoading(true);
    try {
      const result = await onSubmit(otp);
      if (result?.requiresOTP) {
        setOtp('');
      } else if (result?.message) {
        setError(result.message);
      }
    } catch (error) {
      setError(texts.otpModalErrorText);
    } finally {
      setIsLoading(false);
    }
  };

  const handleResendClick = async () => {
    setError(null);
    setIsResending(true);
    try {
      const result = await handleResendOtp(token, tokenData?.MerchantId);
      if (result.success) {
        setRemainingTime(90);
        setCanResend(false);
        setOtp('');
        const timer = setInterval(() => {
          setRemainingTime((prev) => {
            if (prev <= 1) {
              setCanResend(true);
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        setError(result.message || texts.otpModalErrorText);
      }
    } catch (error) {
      setError(texts.otpModalErrorText);
    } finally {
      setIsResending(false);
    }
  };

  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes}:${secs.toString().padStart(2, '0')}`;
  };

  const getContentByResponseCode = () => {
    switch (responseCode) {
      case '5000':
        return {
          title: texts.rtaVerificationTitle,
          description: texts.rtaVerificationDescription,
          placeholder: texts.rtaVerificationPlaceholder,
          helperText: null
        };
      case '5001':
        return {
          title: texts.bankOtpVerificationTitle,
          description: texts.bankOtpVerificationDescription,
          placeholder: texts.bankOtpVerificationPlaceholder,
          helperText: null
        };
      case '5008':
        return {
          title: texts.phoneVerificationTitle,
          description: texts.phoneVerificationDescription,
          placeholder: texts.phoneVerificationPlaceholder,
          helperText: null
        };
      case '5013':
        return {
          title: texts.cvvVerificationTitle,
          description: texts.cvvVerificationDescription,
          placeholder: texts.cvvVerificationPlaceholder,
          helperText: texts.cvvVerificationHelperText
        };
      default:
        return null;
    }
  };

  const getDescription = () => {
    const responseCodeContent = getContentByResponseCode();
    if (responseCodeContent) {
      return responseCodeContent.description;
    }

    if (description) {
      return description;
    }
    switch (type) {
      case 'RTA':
        return texts.rtaVerificationDescription;
      case 'CVV':
        return texts.cvvVerificationDescription;
      default:
        return texts.otpVerificationDescription;
    }
  };

  const getTitle = () => {
    const responseCodeContent = getContentByResponseCode();
    if (responseCodeContent) {
      return responseCodeContent.title;
    }

    switch (type) {
      case 'RTA':
        return texts.rtaVerificationTitle;
      case 'CVV':
        return texts.cvvVerificationTitle;
      default:
        return null;
    }
  };

  const getPlaceholder = () => {
    const responseCodeContent = getContentByResponseCode();
    if (responseCodeContent) {
      return responseCodeContent.placeholder;
    }
    return '';
  };

  const getHelperText = () => {
    const responseCodeContent = getContentByResponseCode();
    return responseCodeContent?.helperText || null;
  };

  const getMaxLength = () => {
    if (responseCode === '5013' || type === 'CVV') {
      return 4;
    }
    return 6;
  };

  return (
    <Modal
      portalId="masterpass-otp-modal"
      open={open}
      setOpen={onClose}
      title={
        <img src={mpBlackLogo.src} alt="Masterpass" className="w-36 h-auto" />
      }
      className="w-full sm:w-[28rem] max-h-[90vh] overflow-y-auto"
    >
      <div className="px-6">
        {getTitle() && (
          <h3 className="text-center mt-4 text-lg font-semibold">{getTitle()}</h3>
        )}
        <p className="text-center mt-2 text-sm text-gray-600">{getDescription()}</p>
        <div className="flex flex-col gap-3 p-5 w-3/4 m-auto">
          <Input
            type="text"
            value={otp}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              setOtp(e.target.value.replace(/\D/g, '').slice(0, getMaxLength()));
              setError(null);
            }}
            maxLength={getMaxLength()}
            pattern="[0-9]*"
            inputMode="numeric"
            className="text-center"
            placeholder={getPlaceholder()}
          />
          {getHelperText() && (
            <p className="text-xs text-gray-500 text-center">{getHelperText()}</p>
          )}
          {error && (
            <p className="text-[#d72b01] text-xs text-center">{error}</p>
          )}
          <Button
            className="py-3 h-auto"
            onClick={handleSubmit}
            disabled={isLoading || otp.length === 0}
          >
            {isLoading ? (
              <LoaderSpinner className="w-4 h-4" />
            ) : (
              texts.verifyButton
            )}
          </Button>
          {type === 'OTP' && (
            <Button
              appearance="outlined"
              className={clsx(
                'px-5 py-3 h-auto',
                !canResend || isResending || isLoading
                  ? 'cursor-not-allowed'
                  : 'cursor-pointer'
              )}
              onClick={handleResendClick}
              disabled={!canResend || isResending || isLoading}
            >
              {isResending ? (
                <LoaderSpinner className="w-4 h-4" />
              ) : canResend ? (
                texts.otpModalResendOtpButton
              ) : (
                `${texts.otpModalResendOtpButton} (${formatTime(
                  remainingTime
                )})`
              )}
            </Button>
          )}
          <Button
            appearance="outlined"
            className="underline px-5 py-3 h-auto"
            onClick={onClose}
            disabled={isLoading}
          >
            {texts.otpModalCancelButton}
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default OTPModal;
