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 manageMerchant() {
  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/getAllMerchant`, {
        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(() => {
    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/updateMerchant/${editUser.id}`, {
            id: editUser.id, // Ensure the ID is included
            name: editUser.name,
            email: editUser.email,
            mobile: editUser.mobile,
            company: editUser.company,
            webhook: editUser.webhook,
            webhook_status: editUser.webhook_status,
            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 handleMobileChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      email: e.target.value,
    }));
  };
  const handleCompanyChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      company: e.target.value,
    }));
  };
  
  const handleWebhookChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      webhook: e.target.value,
    }));
  };
  
  const handleWebhookStatusChange = (e) => {
    setEditUser((prevData) => ({
      ...prevData,
      webhook_status: 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'),
    mobile: Yup.string().matches(/^[0-9]{10}$/, 'Must be a valid 10-digit mobile number').required('Mobile is required'),
    company: Yup.string().required('Company name is required'),
    status: Yup.string().required('Status is required'),
  });

  // Handle Create User form submit
  const handleCreateUserSubmit = async (values, { setErrors, resetForm }) => {
    // alert('working');
    try {
      
      const response = await axios.post(`${serverUrl}/api/v1/admin/createMerchant`, {
        name: values.name,
        email: values.email,
        mobile: values.mobile,
        company: values.company,
        status: values.status // 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={2}
      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 Mercants"
          sx={{ width: '100%', maxWidth: '100%' }} // Ensure full responsiveness
          secondary={
            <Button variant="outlined" onClick={() => setOpenCreate(true)}>
              Create Merchant
            </Button>
          }
        >
          {loading ? (
            <Grid container justifyContent="center">
              <CircularProgress />
            </Grid>
          ) : (
            <TableContainer component={Paper}>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell>ID</TableCell>
                    <TableCell>Name</TableCell>
                    <TableCell>Email</TableCell>
                    <TableCell>Mobile</TableCell>
                    <TableCell>Company</TableCell>
                    <TableCell>Access Key</TableCell>
                    <TableCell>Secret Key</TableCell>
                    <TableCell>Webhook Url</TableCell>
                    <TableCell>Webhook Status</TableCell>
                    <TableCell>token</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.mobile}</TableCell>
                        <TableCell>{user.company}</TableCell>
                        <TableCell>{user.live_access_key}</TableCell>
                        <TableCell>{user.live_secret_key}</TableCell>
                        <TableCell>{user.webhook}</TableCell>
                        <TableCell>{user.webhook_status === 1 ? 'Active' : 'Inactive'}</TableCell>
                        <TableCell>{user.live_token}</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>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Mobile"
                value={editUser?.mobile || ''}
                name="mobile"
                onChange={handleMobileChange}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Company"
                value={editUser?.company || ''}
                name="company"
                onChange={handleCompanyChange}
              />
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="Webhoook"
                value={editUser?.webhook || ''}
                name="webhoook"
                onChange={handleWebhookChange}
              />
            </Grid>
            <Grid item xs={12}>
              <FormControl fullWidth>
                <InputLabel>Webhook Status</InputLabel>
                <Select
                  value={editUser?.webhook_status !== undefined ? editUser.webhook_status : ''}
                  name="status"
                  onChange={handleWebhookStatusChange}
                >
                  <MenuItem value={1}>Active</MenuItem>
                  <MenuItem value={2}>Inactive</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={2}>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: '',mobile: '',company: '' }}
            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="Mobile"
                    name="mobile"
                    value={values.mobile}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    error={Boolean(touched.mobile && errors.mobile)}
                    helperText={touched.mobile && errors.mobile}
                  />
                </FormControl>
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <TextField
                    fullWidth
                    label="Company Name"
                    name="company"
                    value={values.company}
                    onBlur={handleBlur}
                    onChange={handleChange}
                    error={Boolean(touched.company && errors.company)}
                    helperText={touched.company && errors.company}
                  />
                </FormControl>
                
                <FormControl fullWidth sx={{ mt: 2 }}>
                  <InputLabel>Status</InputLabel>
                  <Select
                    name="status"
                    value={values.status || 'active'} // Default value when undefined
                    onChange={handleChange}
                    onBlur={handleBlur}
                  >
                    <MenuItem value="active">Active</MenuItem>
                    <MenuItem value="inactive">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>
  );
}

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