import { useEffect, useState } from 'react';
import { LoadCanvasTemplate, loadCaptchaEnginge, validateCaptcha } from 'react-simple-captcha';

import { Box, TextField, Stack } from '@mui/material';
import { CancelRounded, CheckCircleRounded } from '@mui/icons-material';



// ✅ Define props type
interface NewReCaptchaProps {
  isValidCaptcha: boolean | null;
  setIsValidCaptcha: React.Dispatch<React.SetStateAction<boolean | null>>;
}

function NewReCaptcha({ isValidCaptcha, setIsValidCaptcha }: NewReCaptchaProps) {
  const [captcha, setCaptcha] = useState<string>('');

  useEffect(() => {
    // ✅ loadCaptchaEnginge(length, background, textColor, type)
    loadCaptchaEnginge(4, 'white', 'black', 'numbers');
  }, []);

  return (
    <Stack gap={2} direction="row" mt={2}>
      {/* Captcha Image & Reload */}
      <Box
        display="flex"
        alignItems="center"
        sx={{
          '& #reload_href': { display: 'none !important' },
        }}
      >
        <LoadCanvasTemplate reloadText="" />
      </Box>

      {/* Input Captcha */}
      <Box display="flex" width="100%" flexDirection="column" gap={1}>
        <TextField
          label="Captcha"
          variant="outlined"
          size="small"
          value={captcha}
          onChange={(e) => {
            const value = e.target.value;
            setCaptcha(value);

            if (value.length === 4) {
              if (validateCaptcha(value)) {
                setIsValidCaptcha(true);
              } else {
                setIsValidCaptcha(false);
              }
            } else {
              setIsValidCaptcha(null); // reset kalau belum 4 digit
            }
          }}
          InputProps={{
            endAdornment: (
              <>
                {isValidCaptcha === true && <CheckCircleRounded color="success" />}
                {isValidCaptcha === false && <CancelRounded color="error" />}
              </>
            ),
          }}
        />
      </Box>
    </Stack>
  );
}

export default NewReCaptcha;
