import PropTypes from 'prop-types';
import React, { useEffect, useState } from 'react';

import { useNavigate } from 'react-router-dom';
import {
  Grid,
  Button,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  MenuItem,
  Select,
  FormControl,
  InputLabel,
  TextField,
  Typography,
  CircularProgress,
  Snackbar,
  Alert
} from '@mui/material';
import { Formik } from 'formik';
import * as Yup from 'yup';
import axios from 'axios';
import MainCard from 'components/MainCard';
import AnimateButton from 'components/@extended/AnimateButton';

export default function ManageUsers() {
  const [users, setUsers] = useState([]);
  const [editUser, setEditUser] = useState(null); // To hold the user being edited
  const [openEdit, setOpenEdit] = useState(false); // To control the Edit dialog
  const [openCreate, setOpenCreate] = useState(false); // To control the Create User dialog
  const [loading, setLoading] = useState(true); // Loading state
  const [snackbar, setSnackbar] = useState({ open: false, message: '', severity: 'success' }); // Snackbar for feedback
  const navigate = useNavigate();
  const serverUrl = import.meta.env.VITE_APP_SERVER_URL;

  // Fetch all users on component mount
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${serverUrl}/api/v1/admin/getAllUsers`, {
        withCredentials: true
      });
      setUsers(response.data.users); // Assuming API returns an array of users
      setLoading(false);
    } catch (error) {
      console.error('Error fetching users:', error);
      setLoading(false);
    }
  };

  useEffect(() => {
    document.title = "Predictator | Users";
    fetchUsers();
  }, [serverUrl]);

  // Handle Delete action
  const handleDelete = async (userId) => {
    if (window.confirm('Are you sure you want to delete this user?')) {
      try {
        await axios.delete(`${serverUrl}/api/v1/admin/deleteUser/${userId}`, {
          withCredentials: true
        });
        fetchUsers(); // Re-fetch users after delete
        setSnackbar({ open: true, message: 'User deleted successfully', severity: 'success' });
      } catch (error) {
        console.error('Error deleting user:', error);
        setSnackbar({ open: true, message: 'Error deleting user', severity: 'error' });
      }
    }
  };

  // Handle Edit action (open popup)
  const handleEdit = (user) => {
    setEditUser(user); // Set the user to be edited
    setOpenEdit(true); // Open the dialog
  };

  // Handle the Edit form submit
// Handle the Edit form submit
    const handleEditSubmit = async () => {
        try {
        await axios.put(`${serverUrl}/api/v1/admin/updateUser/${editUser.id}`, {
            id: editUser.id, // Ensure the ID is included
            name: editUser.name,
            email: editUser.email,
            status: editUser.status,
            userType: editUser.user_type,
        }, {
            withCredentials: true
        });
        setOpenEdit(false); // Close the dialog after saving
        setSnackbar({ open: true, message: 'User updated successfully', severity: 'success' });
        fetchUsers(); // Re-fetch users after update
        } catch (error) {
        console.error('Error updating user:', error);
        setSnackbar({ open: true, message: 'Error updating user', severity: 'error' });
        }
    };
  

  // Handlers for individual input changes
  const handleNameChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      name: e.target.value,
    }));
  };

  const handleEmailChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      email: e.target.value,
    }));
  };

  const handleUserTypeChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      user_type: e.target.value, // Correct usage of user_type
    }));
  };

  const handleStatusChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      status: e.target.value,
    }));
  };

  // Validation Schema for the Create User form
  const validationSchema = Yup.object().shape({
    name: Yup.string().required('Name is required'),
    email: Yup.string().email('Must be a valid email').required('Email is required'),
    password: Yup.string().required('Password is required'),
    user_type: Yup.string().required('User Type is required') // Using user_type in the validation schema
  });

  // Handle Create User form submit
  const handleCreateUserSubmit = async (values, { setErrors, resetForm }) => {
    try {
      const response = await axios.post(`${serverUrl}/api/v1/admin/createUser`, {
        name: values.name,
        email: values.email,
        password: values.password,
        user_type: values.user_type // Correct usage of user_type
      }, {
        withCredentials: true
      });

      if (response.data.status === 1) {
        setOpenCreate(false); // Close the dialog after creating
        resetForm(); // Reset the form after success
        setSnackbar({ open: true, message: 'User created successfully', severity: 'success' });
        fetchUsers(); // Re-fetch users after creation
      } else {
        setErrors({ submit: response.data.message });
      }
    } catch (error) {
      console.error('Error creating user:', error);
      setErrors({ submit: 'An error occurred. Please try again.' });
      setSnackbar({ open: true, message: 'Error creating user', severity: 'error' });
    }
  };

  return (
    <Grid
      container
      spacing={0}
      direction="column"
      alignItems="center"
      justifyContent="center"
      sx={{ height: 'auto', mt: 5 }}
    >
      <Grid item xs={12} sm={10} md={8} lg={6} style={{ width: '70%' }}>
        <MainCard
          title="Manage Users"
          sx={{ width: '100%', maxWidth: '100%' }} // Ensure full responsiveness
          secondary={
            <Button variant="outlined" onClick={() => setOpenCreate(true)}>
              Create User
            </Button>
          }
        >
          {loading ? (
            <Grid container justifyContent="center">
              <CircularProgress />
            </Grid>
          ) : (
            <TableContainer component={Paper}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>ID</TableCell>
                    <TableCell>Name</TableCell>
                    <TableCell>Email</TableCell>
                    <TableCell>User Type</TableCell>
                    <TableCell>Status</TableCell>
                    <TableCell>Action</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                    {users.map((user) => (
                        <TableRow key={user.id}>
                        <TableCell>{user.id}</TableCell>
                        <TableCell>{user.name}</TableCell>
                        <TableCell>{user.email}</TableCell>
                        <TableCell>{user.user_type ? user.user_type : 'N/A'}</TableCell>
                        <TableCell>{user.status === 1 ? 'Active' : 'Inactive'}</TableCell>
                        <TableCell>
                            <Button
                            variant="contained"
                            color="primary"
                            onClick={() => handleEdit(user)}
                            style={{ marginRight: '10px' }}
                            >
                            Edit
                            </Button>
                            <Button
                            variant="contained"
                            color="error"
                            onClick={() => handleDelete(user.id)}
                            >
                            Delete
                            </Button>
                        </TableCell>
                        </TableRow>
                    ))}
                </TableBody>

              </Table>
            </TableContainer>
          )}
        </MainCard>
      </Grid>

      {/* Snackbar for feedback */}
      <Snackbar
        open={snackbar.open}
        autoHideDuration={4000}
        onClose={() => setSnackbar({ open: false, message: '', severity: 'success' })}
      >
        <Alert severity={snackbar.severity} onClose={() => setSnackbar({ open: false, message: '', severity: 'success' })}>
          {snackbar.message}
        </Alert>
      </Snackbar>

      {/* Edit Dialog */}
      <Dialog open={openEdit} onClose={() => setOpenEdit(false)}>
        <DialogTitle>Edit User</DialogTitle>
        <DialogContent>
          <Grid container spacing={2}>
            {/* Name Field */}
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Name"
                value={editUser?.name || ''}
                name="name"
                onChange={handleNameChange}
              />
            </Grid>

            {/* Email Field */}
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Email"
                value={editUser?.email || ''}
                name="email"
                onChange={handleEmailChange}
              />
            </Grid>

            {/* User Type Select Field */}
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>User Type</InputLabel>
                <Select
                  value={editUser?.user_type || ''}
                  name="user_type"
                  onChange={handleUserTypeChange}
                >
                  <MenuItem value="admin">Admin</MenuItem>
                  <MenuItem value="subadmin">Sub Admin</MenuItem>
                  <MenuItem value="editor">Editor</MenuItem>
                </Select>
              </FormControl>
            </Grid>

            {/* Status Select Field */}
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>Status</InputLabel>
                <Select
                  value={editUser?.status !== undefined ? editUser.status : ''}
                  name="status"
                  onChange={handleStatusChange}
                >
                  <MenuItem value={1}>Active</MenuItem>
                  <MenuItem value={0}>Inactive</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenEdit(false)}>Cancel</Button>
          <Button onClick={handleEditSubmit} color="primary">
            Save
          </Button>
        </DialogActions>
      </Dialog>

      {/* Create User Dialog */}
      <Dialog open={openCreate} onClose={() => setOpenCreate(false)}>
        <DialogTitle>Create User</DialogTitle>
        <DialogContent>
          <Formik
            initialValues={{ name: '', email: '', password: '', user_type: '' }}
            validationSchema={validationSchema}
            onSubmit={handleCreateUserSubmit}
          >
            {({ errors, handleBlur, handleChange, handleSubmit, touched, values }) => (
              <form noValidate onSubmit={handleSubmit}>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <TextField
                    fullWidth
                    label="Name"
                    name="name"
                    value={values.name}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    error={Boolean(touched.name && errors.name)}
                    helperText={touched.name && errors.name}
                  />
                </FormControl>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <TextField
                    fullWidth
                    label="Email"
                    name="email"
                    value={values.email}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    error={Boolean(touched.email && errors.email)}
                    helperText={touched.email && errors.email}
                  />
                </FormControl>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <TextField
                    fullWidth
                    label="Password"
                    name="password"
                    type="password"
                    value={values.password}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    error={Boolean(touched.password && errors.password)}
                    helperText={touched.password && errors.password}
                  />
                </FormControl>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <InputLabel>User Type</InputLabel>
                  <Select
                    name="user_type"
                    value={values.user_type}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    fullWidth
                    error={Boolean(touched.user_type && errors.user_type)}
                  >
                    <MenuItem value="admin">Admin</MenuItem>
                    <MenuItem value="subadmin">Sub Admin</MenuItem>
                    <MenuItem value="editor">Editor</MenuItem>
                  </Select>
                  {touched.user_type && errors.user_type && (
                    <Typography variant="body2" color="error">
                      {errors.user_type}
                    </Typography>
                  )}
                </FormControl>
                {errors.submit && (
                  <Typography variant="body2" color="error" sx={{ mt: 2 }}>
                    {errors.submit}
                  </Typography>
                )}
                <DialogActions>
                  <Button onClick={() => setOpenCreate(false)}>Cancel</Button>
                  <Button type="submit" color="primary">
                    Create
                  </Button>
                </DialogActions>
              </form>
            )}
          </Formik>
        </DialogContent>
      </Dialog>
    </Grid>
  );
}

ManageUsers.propTypes = { isDemo: PropTypes.bool };
