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, // <- Add this import
  InputLabel,
  TextField,
  Typography,
  CircularProgress,
  Snackbar,
  Alert,
} from '@mui/material'; // Add `FormControl` 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 ManageCategories() {
  const [categories, setCategories] = useState([]);
  const [editCategory, setEditCategory] = useState(null); // To hold the category being edited
  const [openEdit, setOpenEdit] = useState(false); // To control the Edit dialog
  const [openCreate, setOpenCreate] = useState(false); // To control the Create Category 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 categories on component mount
  const fetchCategories = async () => {
    setLoading(true);
    try {
      const response = await axios.get(`${serverUrl}/api/v1/admin/getAllCategories`, {
        withCredentials: true,
      });
      setCategories(response.data.categories); // Assuming API returns an array of categories
      setLoading(false);
    } catch (error) {
      console.error('Error fetching categories:', error);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, [serverUrl]);

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

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

  // Handle the Edit form submit
  const handleEditSubmit = async () => {
    try {
      await axios.put(`${serverUrl}/api/v1/admin/updateCategory/${editCategory.id}`, {
        id: editCategory.id,
        category: editCategory.category,
        status: editCategory.status,
      }, {
        withCredentials: true,
      });
      setOpenEdit(false); // Close the dialog after saving
      setSnackbar({ open: true, message: 'Category updated successfully', severity: 'success' });
      fetchCategories(); // Re-fetch categories after update
    } catch (error) {
      console.error('Error updating category:', error);
      setSnackbar({ open: true, message: 'Error updating category', severity: 'error' });
    }
  };

  // Handle individual input changes for editing
  const handleCategoryChange = (e) => {
    setEditCategory((prevData) => ({
      ...prevData,
      category: e.target.value,
    }));
  };

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

  // Validation Schema for the Create Category form
  const validationSchema = Yup.object().shape({
    category: Yup.string().required('Category is required'),
  });

  // Handle Create Category form submit
  const handleCreateCategorySubmit = async (values, { setErrors, resetForm }) => {
    try {
      const response = await axios.post(`${serverUrl}/api/v1/admin/createCategory`, {
        category: values.category,
        status: values.status,
      }, {
        withCredentials: true,
      });

      if (response.data.status === 1) {
        setOpenCreate(false); // Close the dialog after creating
        resetForm(); // Reset the form after success
        setSnackbar({ open: true, message: 'Category created successfully', severity: 'success' });
        fetchCategories(); // Re-fetch categories after creation
      } else {
        setErrors({ submit: response.data.message });
      }
    } catch (error) {
      console.error('Error creating category:', error);
      setErrors({ submit: 'An error occurred. Please try again.' });
      setSnackbar({ open: true, message: 'Error creating category', 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 Categories"
          sx={{ width: '100%', maxWidth: '100%' }} // Ensure full responsiveness
          secondary={
            <Button variant="outlined" onClick={() => setOpenCreate(true)}>
              Create Category
            </Button>
          }
        >
          {loading ? (
            <Grid container justifyContent="center">
              <CircularProgress />
            </Grid>
          ) : (
            <TableContainer component={Paper}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>ID</TableCell>
                    <TableCell>Category</TableCell>
                    <TableCell>Status</TableCell>
                    <TableCell>Action</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {categories.map((category) => (
                    <TableRow key={category.id}>
                      <TableCell>{category.id}</TableCell>
                      <TableCell>{category.category}</TableCell>
                      <TableCell>{category.status === 1 ? 'Active' : 'Inactive'}</TableCell>
                      <TableCell>
                        <Button
                          variant="contained"
                          color="primary"
                          onClick={() => handleEdit(category)}
                          style={{ marginRight: '10px' }}
                        >
                          Edit
                        </Button>
                        <Button
                          variant="contained"
                          color="error"
                          onClick={() => handleDelete(category.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 Category</DialogTitle>
        <DialogContent>
          <Grid container spacing={2}>
            {/* Category Field */}
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Category"
                value={editCategory?.category || ''}
                name="category"
                onChange={handleCategoryChange}
              />
            </Grid>

            {/* Status Select Field */}
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>Status</InputLabel>
                <Select
                  value={editCategory?.status !== undefined ? editCategory.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 Category Dialog */}
      <Dialog open={openCreate} onClose={() => setOpenCreate(false)}>
        <DialogTitle>Create Category</DialogTitle>
        <DialogContent>
          <Formik
            initialValues={{ category: '', status: 1 }}
            validationSchema={validationSchema}
            onSubmit={handleCreateCategorySubmit}
          >
            {({ errors, handleBlur, handleChange, handleSubmit, touched, values }) => (
              <form noValidate onSubmit={handleSubmit}>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <TextField
                    fullWidth
                    label="Category"
                    name="category"
                    value={values.category}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    error={Boolean(touched.category && errors.category)}
                    helperText={touched.category && errors.category}
                  />
                </FormControl>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <InputLabel>Status</InputLabel>
                  <Select
                    name="status"
                    value={values.status}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    fullWidth
                    error={Boolean(touched.status && errors.status)}
                  >
                    <MenuItem value={1}>Active</MenuItem>
                    <MenuItem value={0}>Inactive</MenuItem>
                  </Select>
                </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>
  );
}

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