import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  Box,
  TextField,
  Button,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Typography,
  type SelectChangeEvent,
  Container,
  Paper,
} from '@mui/material'
import Swal from 'sweetalert2'
import { registerUsers } from './Register.api'
import { setUserId } from '../../../Config'

interface RegistrationData {
  name: string
  email: string
  dob: string
  gender: string
  phone: string
  password: string
  reEnterPassword: string
}

const RegisterPage: React.FC = () => {
  const navigate = useNavigate()

  const [formData, setFormData] = useState<RegistrationData>({
    name: '',
    email: '',
    dob: '',
    gender: '',
    phone: '',
    password: '',
    reEnterPassword: '',
  })

  const handleChange = (
    event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | SelectChangeEvent,
  ) => {
    setFormData({ ...formData, [event.target.name]: event.target.value })
  }

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    if (formData.password !== formData.reEnterPassword) {
      void Swal.fire({
        position: 'center',
        icon: 'error',
        title: 'Passwords do not match.',
        showConfirmButton: false,
        timer: 2000,
      })
    } else {
      void registerUsers(formData)
        .then((result) => {
          if (result.message === 'created') {
            void Swal.fire({
              position: 'center',
              icon: 'success',
              title: 'Registration successful',
              showConfirmButton: false,
              timer: 2000,
            }).then(() => {
              const id: string = result.data._id
              setUserId(id)
              setTimeout(() => {
                navigate('/select')
              })
            })
          } else {
            void Swal.fire({
              position: 'center',
              icon: 'error',
              title: 'Registration failed',
              showConfirmButton: false,
              timer: 2000,
            })
          }
        })
        .catch((error) => {
          console.error('Registration failed:', error.response?.data || error.message)
        })
    }
  }

  return (
    <Container maxWidth='sm'>
      <Paper elevation={3} sx={{ p: 3, mt: 3 }}>
        <Typography variant='h5' sx={{ textAlign: 'center', mb: 2 }}>
          Register
        </Typography>
        <Box component='form' noValidate autoComplete='off' onSubmit={handleSubmit}>
          <TextField
            fullWidth
            required
            label='Name'
            name='name'
            value={formData.name}
            onChange={handleChange}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            required
            type='email'
            label='Email'
            name='email'
            value={formData.email}
            onChange={handleChange}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            required
            type='date'
            label='Date of Birth'
            name='dob'
            value={formData.dob}
            onChange={handleChange}
            InputLabelProps={{ shrink: true }}
            sx={{ mb: 2 }}
          />
          <FormControl fullWidth sx={{ mb: 2 }}>
            <InputLabel id='gender-label'>Gender</InputLabel>
            <Select
              labelId='gender-label'
              name='gender'
              value={formData.gender}
              label='Gender'
              onChange={handleChange}
            >
              <MenuItem value='male'>Male</MenuItem>
              <MenuItem value='female'>Female</MenuItem>
              <MenuItem value='other'>Other</MenuItem>
            </Select>
          </FormControl>
          <TextField
            fullWidth
            required
            label='Phone'
            name='phone'
            value={formData.phone}
            onChange={handleChange}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            required
            type='password'
            label='Password'
            name='password'
            value={formData.password}
            onChange={handleChange}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            required
            type='password'
            label='Re-enter Password'
            name='reEnterPassword'
            value={formData.reEnterPassword}
            onChange={handleChange}
            sx={{ mb: 3 }}
          />
          <Button
            type='submit'
            variant='contained'
            fullWidth
            sx={{
              py: 1.5,
              backgroundColor: '#7950F1',
              ':hover': {
                backgroundColor: '#5a2ce6',
              },
            }}
          >
            Register
          </Button>
        </Box>
      </Paper>
    </Container>
  )
}

export default RegisterPage
