import React, { useState } from 'react'
import { Box, TextField, Button, Typography, Container, Paper } from '@mui/material'
import { useNavigate } from 'react-router-dom'
import Swal from 'sweetalert2'
import { loginUsers } from './Login.api'
import { setUserId } from '../../../Config'
interface LoginData {
  email: string
  password: string
}

const RegisterPage: React.FC = () => {
  const [formData, setFormData] = useState<LoginData>({
    email: '',
    password: '',
  })

  const navigate = useNavigate()

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

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    void loginUsers(formData)
      .then((result) => {
        if (result.message === 'true') {
          void Swal.fire({
            position: 'center',
            icon: 'success',
            title: 'Login successful',
            showConfirmButton: false,
            timer: 2000,
          }).then(() => {
            const id: string = result.data._id
            setUserId(id)
            navigate('/select')
          })
        } else {
          void Swal.fire({
            position: 'center',
            icon: 'error',
            title: 'Login 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: 15 }}>
        <Typography variant='h4' sx={{ textAlign: 'center', mb: 3 }}>
          Login
        </Typography>
        <Box component='form' noValidate autoComplete='off' onSubmit={handleSubmit}>
          <TextField
            fullWidth
            required
            label='Email'
            name='email'
            type='email'
            value={formData.email}
            onChange={handleChange}
            sx={{ mb: 2 }}
          />
          <TextField
            fullWidth
            required
            label='Password'
            name='password'
            type='password'
            value={formData.password}
            onChange={handleChange}
            sx={{ mb: 3 }}
          />
          <Button
            type='submit'
            variant='contained'
            fullWidth
            sx={{
              py: 1.5,
              backgroundColor: '#7950F1',
              ':hover': {
                backgroundColor: '#5a2ce6',
              },
            }}
          >
            Login
          </Button>
        </Box>
      </Paper>
    </Container>
  )
}

export default RegisterPage
