import React, { useState, useEffect } from 'react';
import {
  Box,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  MenuItem,
  IconButton,
  Menu,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Typography,
  Card,
  Alert,
  Snackbar,
  InputAdornment,
  TablePagination,
  Divider,
  Chip
} from '@mui/material';
import {
  MoreVert as MoreVertIcon,
  Add as AddIcon,
  Edit as EditIcon,
  Delete as DeleteIcon,
  Close as CloseIcon
} from '@mui/icons-material';
import SequenceGeneratorAPI from './sequencegeneratorapi';

const SequenceGenerator = () => {
  const [sequences, setSequences] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [openDialog, setOpenDialog] = useState(false);
  const [editingId, setEditingId] = useState(null);
  const [currentSequence, setCurrentSequence] = useState(null);
  const [anchorEl, setAnchorEl] = useState(null);
  const [openMenuId, setOpenMenuId] = useState(null);
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(10);
  const [snackbarOpen, setSnackbarOpen] = useState(false);
  const [snackbarMessage, setSnackbarMessage] = useState('');
  const [snackbarSeverity, setSnackbarSeverity] = useState('success');

  useEffect(() => {
    fetchSequences();
  }, []);

  const fetchSequences = async () => {
    setLoading(true);
    try {
      const data = await SequenceGeneratorAPI.getAll();
      setSequences(data);
    } catch (err) {
      setError(err.response?.data?.message || 'Failed to fetch sequences');
      showSnackbar(err.response?.data?.message || 'Failed to fetch sequences', 'error');
    } finally {
      setLoading(false);
    }
  };

  const showSnackbar = (message, severity) => {
    setSnackbarMessage(message);
    setSnackbarSeverity(severity);
    setSnackbarOpen(true);
  };

  const handleCreate = () => {
    setCurrentSequence(null);
    setEditingId(null);
    setOpenDialog(true);
  };

  const handleEdit = (record) => {
    setCurrentSequence(record);
    setEditingId(record.id);
    setOpenDialog(true);
  };

  const handleDelete = async (id) => {
    try {
      await SequenceGeneratorAPI.delete(id);
      showSnackbar('Sequence deleted successfully', 'success');
      fetchSequences();
    } catch (err) {
      showSnackbar(err.response?.data?.message || 'Failed to delete sequence', 'error');
    }
  };

  const handleMenuClick = (event, id) => {
    setAnchorEl(event.currentTarget);
    setOpenMenuId(id);
  };

  const handleMenuClose = () => {
    setAnchorEl(null);
    setOpenMenuId(null);
  };

  const handleSubmit = async (event) => {
  if (event) {
    event.preventDefault();
  }
  
  try {
    // Get form values directly from state or form inputs
    const form = event?.currentTarget || document.querySelector('form');
    const formData = new FormData(form);
    const values = Object.fromEntries(formData.entries());

    // Convert number fields from strings to numbers
    values.starting_no = Number(values.starting_no);
    values.current_no = Number(values.current_no);
    
    if (editingId) {
      await SequenceGeneratorAPI.update(editingId, values);
      showSnackbar('Sequence updated successfully', 'success');
    } else {
      await SequenceGeneratorAPI.create(values);
      showSnackbar('Sequence created successfully', 'success');
    }
    
    setOpenDialog(false);
    fetchSequences();
  } catch (err) {
    showSnackbar(err.response?.data?.message || 'Operation failed', 'error');
  }
};


  const handleChangePage = (event, newPage) => {
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };

  const columns = [
    { id: 'sequence_name', label: 'Name' },
    { id: 'sequence_code', label: 'Sequence Code' },
    { id: 'current_no', label: 'Current No' },
    { id: 'demonstration', label: 'Demonstration' },
    { id: 'actions', label: 'Actions' }
  ];

  return (
    <Box sx={{ p: 3 }}>
      {/* Error Alert */}
      {error && (
        <Alert
          severity="error"
          sx={{ mb: 2 }}
          onClose={() => setError(null)}
        >
          {error}
        </Alert>
      )}

      {/* Success/Error Snackbar */}
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={6000}
        onClose={() => setSnackbarOpen(false)}
        anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
      >
        <Alert 
          onClose={() => setSnackbarOpen(false)} 
          severity={snackbarSeverity}
          sx={{ width: '100%' }}
        >
          {snackbarMessage}
        </Alert>
      </Snackbar>

      {/* Header and Add Button */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h4" component="h2">
          Document Sequence
        </Typography>
        <Button 
          variant="contained" 
          startIcon={<AddIcon />}
          onClick={handleCreate}
        >
          Add Sequence
        </Button>
      </Box>

      {/* Table */}
      <TableContainer component={Paper} sx={{ boxShadow: 3 }}>
        <Table>
          <TableHead sx={{ backgroundColor: 'primary.main' }}>
            <TableRow>
              {columns.map((column) => (
                <TableCell key={column.id} sx={{ color: 'common.white', fontWeight: 'bold' }}>
                  {column.label}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {sequences
              .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
              .map((row) => (
                <TableRow key={row.id} hover>
                  <TableCell>{row.sequence_name}</TableCell>
                  <TableCell>{row.sequence_code}</TableCell>
                  <TableCell>{row.current_no}</TableCell>
                  <TableCell>
                    <Chip 
                      label={row.demonstration} 
                      color="primary"
                      variant="outlined"
                    />
                  </TableCell>
                  <TableCell>
                    <IconButton
                      aria-label="more"
                      aria-controls={`menu-${row.id}`}
                      aria-haspopup="true"
                      onClick={(e) => handleMenuClick(e, row.id)}
                    >
                      <MoreVertIcon />
                    </IconButton>
                    <Menu
                      id={`menu-${row.id}`}
                      anchorEl={anchorEl}
                      open={openMenuId === row.id}
                      onClose={handleMenuClose}
                    >
                      <MenuItem onClick={() => { handleEdit(row); handleMenuClose(); }}>
                        <EditIcon sx={{ mr: 1 }} /> Edit
                      </MenuItem>
                      <MenuItem 
                        onClick={() => { 
                          handleDelete(row.id); 
                          handleMenuClose(); 
                        }}
                        sx={{ color: 'error.main' }}
                      >
                        <DeleteIcon sx={{ mr: 1 }} /> Delete
                      </MenuItem>
                    </Menu>
                  </TableCell>
                </TableRow>
              ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Pagination */}
      <TablePagination
        rowsPerPageOptions={[5, 10, 25]}
        component="div"
        count={sequences.length}
        rowsPerPage={rowsPerPage}
        page={page}
        onPageChange={handleChangePage}
        onRowsPerPageChange={handleChangeRowsPerPage}
      />

      {/* Add/Edit Dialog */}
      <Dialog
        open={openDialog}
        onClose={() => setOpenDialog(false)}
        maxWidth="md"
        fullWidth
      >
        <DialogTitle>
          {editingId ? 'Update Sequence Generator' : 'Add New Sequence'}
          <IconButton
            aria-label="close"
            onClick={() => setOpenDialog(false)}
            sx={{
              position: 'absolute',
              right: 8,
              top: 8,
              color: (theme) => theme.palette.grey[500],
            }}
          >
            <CloseIcon />
          </IconButton>
        </DialogTitle>
        <DialogContent dividers>
          {currentSequence && (
            <Card variant="outlined" sx={{ mb: 3 }}>
              <Box sx={{ p: 2 }}>
                <Typography variant="h6" gutterBottom>
                  Sequence Details
                </Typography>
                <Divider sx={{ mb: 2 }} />
                <Box sx={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
                  <Box sx={{ display: 'flex' }}>
                    <Typography variant="subtitle1" sx={{ width: '30%', fontWeight: 'bold' }}>
                      Sequence ID
                    </Typography>
                    <Typography variant="body1">{currentSequence.id}</Typography>
                  </Box>
                  <Box sx={{ display: 'flex' }}>
                    <Typography variant="subtitle1" sx={{ width: '30%', fontWeight: 'bold' }}>
                      Demonstration
                    </Typography>
                    <Chip 
                      label={currentSequence.demonstration} 
                      color="primary"
                      sx={{ fontWeight: 'bold' }}
                    />
                  </Box>
                </Box>
              </Box>
            </Card>
          )}

          <Box component="form"  id="sequence-form" onSubmit={handleSubmit} sx={{ mt: 1 }}>
            <TextField
              margin="normal"
              fullWidth
              label="Name*"
              name="sequence_name"
              defaultValue={currentSequence?.sequence_name || ''}
              required
              sx={{ mb: 2 }}
            />

            <TextField
              margin="normal"
              fullWidth
              label="Sequence Code"
              name="sequence_code"
              defaultValue={currentSequence?.sequence_code || ''}
              sx={{ mb: 2 }}
            />

            <TextField
              margin="normal"
              fullWidth
              label="Prefix*"
              name="prefix"
              defaultValue={currentSequence?.prefix || ''}
              required
              sx={{ mb: 2 }}
            />

            <TextField
              margin="normal"
              fullWidth
              label="Suffix"
              name="suffix"
              defaultValue={currentSequence?.suffix || ''}
              sx={{ mb: 2 }}
            />

            <TextField
              margin="normal"
              fullWidth
              label="Separator"
              name="seperator"
              defaultValue={currentSequence?.seperator || ''}
              sx={{ mb: 2 }}
            />

            <TextField
              margin="normal"
              fullWidth
              label="Starting No"
              name="starting_no"
              type="number"
              defaultValue={currentSequence?.starting_no || 1}
              InputProps={{ inputProps: { min: 1 } }}
              sx={{ mb: 2 }}
            />

            <TextField
              margin="normal"
              fullWidth
              label="Current No"
              name="current_no"
              type="number"
              defaultValue={currentSequence?.current_no || 1}
              InputProps={{ inputProps: { min: 1 } }}
            />
          </Box>
        </DialogContent>
        <DialogActions>
  <Button onClick={() => setOpenDialog(false)}>Cancel</Button>
  <Button 
    variant="contained" 
    type="submit"
    form="sequence-form" // Associate with the form
  >
    {editingId ? 'Update' : 'Create'}
  </Button>
</DialogActions>
      </Dialog>
    </Box>
  );
};

export default SequenceGenerator;