import React, { useState } from 'react';

import { Typography, Button, Box, Paper, Radio, RadioGroup, FormControlLabel, FormControl, FormLabel, Link, Checkbox } from '@mui/material';

import TermsAndConditionsDialog from './TermsAndConditionsDialog';

export enum Role {
  Validator = 'validator',
  Participant = 'participant'
}

const SelectRoleCard = ({ handleAccept, handleRoleChange }: { handleAccept: () => void, handleRoleChange: (role: Role) => void }) => {
  const [selectedRole, setSelectedRole] = useState<Role>(Role.Participant);
  const [checked, setChecked] = useState(false);
  const [isHidden, setIsHidden] = useState(false);

  const [isDialogOpen, setisDialogOpen] = useState(false)

  const handleCheckboxChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setChecked(event.target.checked);
  };

  const handleContinue = () => {
    handleAccept()
    setIsHidden(true)
  }

  const handleRadioChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setSelectedRole(event.target.value as Role);
    handleRoleChange((event.target as HTMLInputElement).value === Role.Validator ? Role.Validator : Role.Participant);
    setChecked(false);
  };

  return (
    <Paper elevation={3} sx={{ padding: 2, marginTop: 2, display: isHidden ? "none" : "block", marginBottom: 3 }} >
      <FormControl component="fieldset">
        <FormLabel component="legend">Select your role</FormLabel>
        <RadioGroup
          aria-label="roles"
          name="roles"
          value={selectedRole}
          onChange={handleRadioChange}
        >
          <FormControlLabel
            value={Role.Validator}
            control={<Radio />}
            label="Validator"
          />
          <FormControlLabel
            value={Role.Participant}
            control={<Radio />}
            label="Participant"
          />
        </RadioGroup>
      </FormControl>
      <Box mt={2} display="flex" alignItems="center">
        <Checkbox
          checked={checked}
          onChange={handleCheckboxChange}
          color="primary"
        />
        <Typography variant="body1">
          I accept the <Link onClick={() => setisDialogOpen(true)} target="_blank" rel="noopener">
            terms and conditions
          </Link>
        </Typography>
      </Box>
      <Box mt={4} display="flex" justifyContent="end">
        <Button
          variant="contained"
          color="primary"
          onClick={handleContinue}
          disabled={!checked}
        >
          Continue
        </Button>
      </Box>
      <TermsAndConditionsDialog open={isDialogOpen} onClose={() => setisDialogOpen(false)}/>
    </Paper>
  );
};

export default SelectRoleCard;
