/* eslint-disable react/jsx-key */
/* eslint-disable compat/compat */
/* eslint-disable react/jsx-props-no-spreading */
/* eslint-disable no-nested-ternary */
import React, { useEffect, useState } from 'react';
import { Grid, Button } from '@mui/material';
import Typography from '@mui/material/Typography';
import { makeStyles, withStyles } from '@mui/styles';

import { green, red, blue } from '@mui/material/colors';

import Radio, { RadioProps } from '@mui/material/Radio';
import { observer } from 'mobx-react';
import { useNavigate } from 'react-router-dom';
import { clone } from 'mobx-keystone';
import { useTranslation } from 'react-i18next';
import { getRootStore, RootStore } from '../../models/root-store.ts';
import { ipcRenderer } from 'electron';

const GreenRadio = withStyles({
  root: {
    '& svg': {
      width: '1.6em',
      height: '1.6em',
    },
    color: 'grey',
    '&$checked': {
      color: green[600],
      animation: `$bounce 0.5s infinite alternate`,
      animationTimingFunction: 'ease-in-out',
    },
  },

  '@keyframes bounce': {
    '0%': {
      transform: 'translateY(10%)',
    },
    '50%': {
      transform: 'translateY(-10%)',
      scale: '120%',
    },
    '100%': {
      transform: 'translateY(-10%)',
    },
  },
  checked: {},
})((props: RadioProps) => <Radio color="default" {...props} />);

const BlueRadio = withStyles({
  root: {
    '& svg': {
      width: '1.6em',
      height: '1.6em',
    },
    color: 'grey',
    '&$checked': {
      color: blue[600],
    },
  },
  checked: {},
})((props: RadioProps) => <Radio color="default" {...props} />);

const RedRadio = withStyles({
  root: {
    '& svg': {
      width: '1.6em',
      height: '1.6em',
    },
    color: 'grey',
    '&$checked': {
      color: red[600],
      animation: `$bounce 1s alternate`,
      animationTimingFunction: 'ease-in-out',
    },
  },

  '@keyframes bounce': {
    '0%': {
      transform: 'translateX(0%)',
    },
    '25%': {
      transform: 'translateX(30%)',
      scale: '120%',
    },
    '50%': {
      transform: 'translateX(-30%)',
      scale: '140%',
    },
    '75%': {
      scale: '120%',
    },
    '100%': {
      transform: 'translateX(0%)',
    },
  },
  checked: {},
})((props: RadioProps) => <Radio color="default" {...props} />);

function Keypad() {
  const [rootStore] = useState(() => getRootStore());
  const [code, setCode] = useState([]);
  const [animation, setAnimation] = useState(false);
  const [error, setError] = useState(false);
  const [pinSent, setPinSent] = useState(false);
  const [pinOk, setPinOk] = useState(false);
  const [passageOpend, setPassageOpend] = useState(false);

  const useStyles = makeStyles({
    content: {
      alignItems: 'center',
    },
    root: {
      flexGrow: 1,
    },
    paper: {
      backgroundColor: '#95A5A6',
      textAlign: 'center',
    },
    code: {
      margin: 0,
      padding: 0,
      textAlign: 'center',
    },
    gridItemButton: {
      margin: 0,
      padding: 0,
      textAlign: 'center',
    },
    button: {
      backgroundColor: 'lightgrey',
      height: `${rootStore.layout.keypadSize}%`,
      width: '90%',
      margin: 5,
      padding: 5,
      textAlign: 'center',
    },
    typo: {
      fontSize: 'auto',
    },
    btn: {
      height: 50,
      fontSize: 18,
    },
    buttonRipplePulsate: {
      animationDuration: `5000ms`,
    },
    check: {
      color: 'grey',
      '&$checked': {
        color: green[600],
      },
    },
    checkAnim: {
      color: 'grey',
      '&$checked': {
        color: green[600],
      },
    },
  });

  const classes = useStyles();

  const history = useNavigate();


  useEffect(() => {
    const handlePassageChange = (_event, passageState) => {
      console.log(' Passage state updated:', passageState);
  
      if (passageState.id === rootStore.passageList.defaultPassageId) {
        if (passageState.action === 1) {
          console.log('Passage is OPEN! Triggering green animation...');
  
          // Show green after a small delay (prevents flickering)
          setTimeout(() => {
            setAnimation(true);
            setError(false); // Ensure red is not shown
          }, 500);
  
          setTimeout(() => history('/'), 1500); // Redirect after 1.5 sec
        }
      }
    };
  
    ipcRenderer.on('workerWindowNetwork->mainWindow-ws-passageChanged', handlePassageChange);
  
    return () => {
      ipcRenderer.removeListener('workerWindowNetwork->mainWindow-ws-passageChanged', handlePassageChange);
    };
  }, []);
  
  const runFetchPostPin = async (codePin: string) => {
    try {
      console.log('Sending the code:', codePin);
      setError(false);
      setAnimation(false);
      const response = await ipcRenderer.invoke('scanCode', [
        rootStore.acs01List?.defaultAcs01.localUrl,
        codePin,
        rootStore.readerList.defaultReaderId,
      ]);
   
 
      await new Promise((resolve) => setTimeout(resolve, 1000));
  
     
  
  
      if (response?.success && passageResponse?.isOpen) {
        console.log('Passage is open! Showing green after delay...');
  
        setTimeout(() => {
          setAnimation(true);
        }, 500);
  
        setTimeout(() => history('/'), 1500); 
      } else {
        console.log('Incorrect PIN or passage still closed, showing red...');
  
        setTimeout(() => {
          setError(true);
        }, 500);
  
        setTimeout(() => {
          setError(false);
          setCode([]);
        }, 2000); 
      }
    } catch (error) {
      console.log('Error during PIN verification:', error);
  
      setTimeout(() => {
        setError(true);
      }, 500);
  
      setTimeout(() => {
        setError(false);
        setCode([]);
      }, 2000); 
    }
  };
  
  
  

  const handleButtonClickCancel = async () => {
    setCode([]);
    history('/');
  };

  const handleButtonClickClear = async () => {
    setCode([]);
  };

  const handleButtonClick = async (e: {
    preventDefault: () => void;
    currentTarget: { value: string };
  }) => {
    e.preventDefault();
    const value = [e.currentTarget.value];
    const combinedArray: any = [...code, ...value];

    if (combinedArray.length === 4) {
      console.log('Now running pos pin', combinedArray.join('').toString());
      const resultPin = await runFetchPostPin(
        combinedArray.join('').toString()
      );
      
    }
    if (code.length <= 3) {
      setCode(combinedArray);
    }
  };

  useEffect(() => {
    const timeout = setTimeout(() => {
      history('/');
    }, 5000); 
  
    return () => clearTimeout(timeout); 
  }, [code]); 

  useEffect(() => {
    const timeout = setTimeout(() => {
      if (animation === true) {
        history('/');
      }
    }, 1000);
    return () => {
      clearTimeout(timeout);
    };
  }, [animation]);

  return (
    <Grid
      container
      spacing={0}
      direction="column"
      alignItems="center"
      justifyContent="center"
      style={{
        marginTop: -10,
        overflow: 'hidden',
        minHeight: '85vh',
      }}
    >
      <Grid item xs={4} />
      <Grid item className={classes.code} xs={4}>
        {animation ? (
          <GreenRadio
            checked={code[0] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : error ? (
          <RedRadio
            checked={code[0] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : (
          <BlueRadio
            checked={code[0] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        )}
        {animation ? (
          <GreenRadio
            checked={code[1] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : error ? (
          <RedRadio
            checked={code[1] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : (
          <BlueRadio
            checked={code[1] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        )}
        {animation ? (
          <GreenRadio
            checked={code[2] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : error ? (
          <RedRadio
            checked={code[2] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : (
          <BlueRadio
            checked={code[2] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        )}
        {animation ? (
          <GreenRadio
            checked={code[3] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : error ? (
          <RedRadio
            checked={code[3] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        ) : (
          <BlueRadio
            checked={code[3] != null}
            value={code}
            name="radio-button-demo"
            size="medium"
          />
        )}
      </Grid>
      <Grid item xs={3} />
      <Grid item xs={1} />
      <Grid item md={1} lg={3} />
      <Grid item xs={12} md={10} lg={6}>
        <Grid container spacing={0}>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              size="large"
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={1}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                1
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={2}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                2
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={3}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                3
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={4}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                4
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={5}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                5
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={6}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                6
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={7}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                7
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={8}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                8
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={9}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                9
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClickCancel}
              onTouchEnd={handleButtonClickCancel}
              value="*"
              variant="outlined"
              color="primary"
              style={{ backgroundColor: '#f44336' }}
            >
              <Typography variant="h4">CANCEL</Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClick}
              onTouchEnd={handleButtonClick}
              value={0}
              variant="outlined"
              color="primary"
            >
              <Typography className={classes.typo} variant="h1">
                0
              </Typography>
            </Button>
          </Grid>
          <Grid item xs={4} className={classes.gridItemButton}>
            <Button
              className={classes.button}
              onMouseUp={handleButtonClickClear}
              onTouchEnd={handleButtonClickClear}
              value="#"
              variant="outlined"
              color="primary"
              style={{ backgroundColor: 'orange' }}
            >
              <Typography className={classes.typo} variant="h4">
                CLEAR
              </Typography>
            </Button>
          </Grid>
        </Grid>
      </Grid>
      <Grid item md={1} lg={3} />
    </Grid>
  );
}
export default observer(Keypad);
