import React, { useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { Box, Button, TextField, Typography } from '@mui/material';

import Api from '@northern.tech/store/api/general-api';

import { CodeDisplay } from '../components/CodeDisplay';
import { SETUP_COMMAND } from '../constants';
import { useNotify } from '../notify';
import { useValidateStyles } from '../styles';

interface ValidateCodeResponse {
  isValid: boolean;
  error?: string;
  sessionId?: string;
}

export const useCodeValidation = () => {
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate();
  const { error: notifyError } = useNotify();

  const validateCode = async (code: string) => {
    try {
      const { data } = await Api.post<ValidateCodeResponse>('/setup/validate_code', { code });
      const { isValid = false, error = '', sessionId = '' } = data;

      if (!isValid) {
        setError(error);
        return false;
      }

      navigate('/complete');
      return true;
    } catch (err) {
      notifyError(err.data);
      return false;
    }
  };

  return { error, validateCode };
};

export const ValidateCode: React.FC = () => {
  const { classes } = useValidateStyles();
  const [code, setCode] = useState('');
  const { error, validateCode } = useCodeValidation();

  const handleSubmit = useCallback(
    async (e: React.FormEvent) => {
      e.preventDefault();
      await validateCode(code);
    },
    [code, validateCode]
  );

  const handleCodeChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    setCode(e.target.value);
  }, []);

  return (
    <Box className={classes.container}>
      <Box id="login" className={`setup validate ${classes.loginBox}`}>
        <Box className="login-box relative center">
          <Box>
            <Box>
              <Typography variant="h4" component="h2">
                Welcome to the CFEngine web UI, Mission Portal
              </Typography>
              <Typography className={`${classes.subtitle} margin-bottom-small`}>
                To complete setup, enter the 6 digit code printed out by your installer.
              </Typography>
            </Box>

            <Box component="form" onSubmit={handleSubmit} className="form-horizontal" id="setup-code">
              <Box className="control-group flex flex--align_center">
                <Typography component="label" className="control-label" htmlFor="code">
                  Setup code
                </Typography>
                <Box className="controls">
                  <TextField
                    id="code"
                    type="text"
                    name="code"
                    required
                    autoComplete="off"
                    value={code}
                    className={classes.input}
                    onChange={handleCodeChange}
                    inputProps={{ maxLength: 6 }}
                    fullWidth
                  />
                </Box>
              </Box>

              {error && <Box className="alert alert-error">{error}</Box>}

              <Box className="margin-top-small flex flex--end">
                <Button type="submit" id="reset" className="btn btn-primary margin-left-small" variant="contained">
                  Submit
                </Button>
              </Box>
            </Box>

            <CodeDisplay command={SETUP_COMMAND} />
          </Box>
        </Box>
      </Box>
    </Box>
  );
};

export default ValidateCode;
