import React, { useState, useEffect } from "react";
import {
  Button,
  IconButton,
  Modal,
  TextField,
  Checkbox,
  FormControlLabel,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  Pagination,
  Menu,
  MenuItem,
  Box,
  Typography,
  InputAdornment,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  FormControl,
  Select,
  InputLabel,
  CircularProgress,
} from "@mui/material";
import {
  Edit as EditIcon,
  Delete as DeleteIcon,
  Add as AddIcon,
  Menu as MenuIcon,
  Close as CloseIcon,
  Search as SearchIcon,
} from "@mui/icons-material";
import { styled } from "@mui/material/styles";
import { toast } from "react-toastify";
import { fetchRegistry, addRegistry, updateRegistry, deleteRegistry } from "./Apiregistryapi";

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  '&:nth-of-type(odd)': {
    backgroundColor: theme.palette.action.hover,
  },
  '&:hover': {
    backgroundColor: theme.palette.action.selected,
  },
}));

const APIRegistry = () => {
  const [apiEntries, setApiEntries] = useState([]);
  const [openModal, setOpenModal] = useState(false);
  const [currentApiEntry, setCurrentApiEntry] = useState({
    table_name: "",
    isActive: false,
  });
  const [loading, setLoading] = useState(true);
  const [currentPage, setCurrentPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");
  const [isEditing, setIsEditing] = useState(false);
  const [recordsPerPage, setRecordsPerPage] = useState(10);
  const [visibleColumns, setVisibleColumns] = useState({
    id: true,
    table_name: true,
    createdAt: true,
    updatedAt: true,
    isActive: true,
    actions: true,
  });
  const [columnsAnchorEl, setColumnsAnchorEl] = useState(null);
  const [recordsAnchorEl, setRecordsAnchorEl] = useState(null);
  const columnsMenuOpen = Boolean(columnsAnchorEl);
  const recordsMenuOpen = Boolean(recordsAnchorEl);

  useEffect(() => {
    const loadData = async () => {
      try {
        setLoading(true);
        const data = await fetchRegistry();
        setApiEntries(data || []);
      } catch (error) {
        toast.error("Failed to fetch API entries");
        console.error("Error loading data:", error);
      } finally {
        setLoading(false);
      }
    };

    loadData();
  }, []);

  const handleColumnsMenuClick = (event) => {
    setColumnsAnchorEl(event.currentTarget);
  };

  const handleRecordsMenuClick = (event) => {
    setRecordsAnchorEl(event.currentTarget);
  };

  const handleMenuClose = () => {
    setColumnsAnchorEl(null);
    setRecordsAnchorEl(null);
  };

  const toggleColumn = (column) => {
    setVisibleColumns((prev) => ({
      ...prev,
      [column]: !prev[column],
    }));
  };

  const handleInputChange = (event) => {
    const { name, value, type, checked } = event.target;
    setCurrentApiEntry((prev) => ({
      ...prev,
      [name]: type === 'checkbox' ? checked : value,
    }));
  };

  const handleSearch = (query) => {
    setSearchQuery(query);
    setCurrentPage(1);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    try {
      setLoading(true);
      let response;
      
      if (isEditing) {
        response = await updateRegistry(currentApiEntry.id, currentApiEntry);
        toast.success("API entry updated successfully!");
      } else {
        response = await addRegistry(currentApiEntry);
        toast.success("API entry added successfully!");
      }

      // Refresh the data
      const data = await fetchRegistry();
      setApiEntries(data || []);
      setOpenModal(false);
    } catch (error) {
      toast.error(error.message || "Failed to save API entry");
      console.error("Save error:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleOpenModal = (entry = {
    table_name: "",
    isActive: false,
  }) => {
    setIsEditing(!!entry.id);
    setCurrentApiEntry(entry);
    setOpenModal(true);
  };

  const handleCloseModal = () => {
    setOpenModal(false);
  };

  const handleDelete = async (id) => {
    try {
      setLoading(true);
      await deleteRegistry(id);
      const data = await fetchRegistry();
      setApiEntries(data || []);
      toast.success("API entry deleted successfully!");
    } catch (error) {
      toast.error(error.message || "Failed to delete API entry");
      console.error("Delete error:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleRecordsPerPageChange = (value) => {
    setRecordsPerPage(value);
    setCurrentPage(1);
    handleMenuClose();
  };

  // Filter and pagination logic
  const filteredAPIEntries = apiEntries.filter(item =>
    item.table_name?.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const totalPages = Math.ceil(filteredAPIEntries.length / recordsPerPage);
  const slicedAPIEntries = filteredAPIEntries.slice(
    (currentPage - 1) * recordsPerPage,
    currentPage * recordsPerPage
  );

  if (loading) {
    return (
      <Box display="flex" justifyContent="center" alignItems="center" height="80vh">
        <CircularProgress />
      </Box>
    );
  }

  return (
    <Box sx={{ marginTop: "11rem", padding: 3 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 4 }}>
        <Typography variant="h4" component="h1" sx={{ fontWeight: 'bold' }}>
          API Registry
        </Typography>
      </Box>

      <Box sx={{ display: 'flex', flexDirection: { xs: 'column', md: 'row' }, alignItems: 'center', my: 3, gap: 2 }}>
        <TextField
          placeholder="Search"
          value={searchQuery}
          onChange={(e) => handleSearch(e.target.value)}
          InputProps={{
            startAdornment: (
              <InputAdornment position="start">
                <SearchIcon />
              </InputAdornment>
            ),
          }}
          sx={{
            width: { xs: '100%', md: '60%' },
            maxWidth: '528px',
            '& .MuiOutlinedInput-root': {
              borderRadius: '10px',
              boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.1)',
            },
          }}
        />

        <Box sx={{ display: 'flex', gap: 2 }}>
          <Tooltip title="Add API Entry">
            <IconButton onClick={() => handleOpenModal()} color="primary">
              <AddIcon />
            </IconButton>
          </Tooltip>
          <Tooltip title="Menu">
            <IconButton onClick={handleColumnsMenuClick} color="primary">
              <MenuIcon />
            </IconButton>
          </Tooltip>
        </Box>
      </Box>

      <TableContainer component={Paper} sx={{ boxShadow: 3, mb: 3 }}>
        <Table>
          <TableHead sx={{ bgcolor: 'primary.main' }}>
            <TableRow>
              {Object.entries(visibleColumns)
                .filter(([_, visible]) => visible)
                .map(([key]) => (
                  <TableCell key={key} sx={{ color: 'white', fontWeight: 'bold' }}>
                    {key.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')}
                  </TableCell>
                ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {slicedAPIEntries.length === 0 ? (
              <TableRow>
                <TableCell
                  colSpan={Object.values(visibleColumns).filter(Boolean).length}
                  align="center"
                >
                  No Data Available
                </TableCell>
              </TableRow>
            ) : (
              slicedAPIEntries.map((entry) => (
                <StyledTableRow key={entry.id}>
                  {Object.entries(visibleColumns)
                    .filter(([_, visible]) => visible)
                    .map(([key]) => (
                      <TableCell key={key}>
                        {key === "actions" ? (
                          <Box sx={{ display: 'flex', gap: 1 }}>
                            <Tooltip title="Edit">
                              <IconButton
                                onClick={() => handleOpenModal(entry)}
                                color="primary"
                              >
                                <EditIcon />
                              </IconButton>
                            </Tooltip>
                            <Tooltip title="Delete">
                              <IconButton
                                onClick={() => handleDelete(entry.id)}
                                color="error"
                              >
                                <DeleteIcon />
                              </IconButton>
                            </Tooltip>
                          </Box>
                        ) : key === "isActive" ? (
                          <Typography
                            sx={{
                              color: entry.isActive ? 'success.main' : 'error.main',
                              bgcolor: entry.isActive ? 'success.light' : 'error.light',
                              px: 1,
                              py: 0.5,
                              borderRadius: 1,
                              display: 'inline-block',
                            }}
                          >
                            {entry.isActive ? "Active" : "Inactive"}
                          </Typography>
                        ) : (
                          entry[key]
                        )}
                      </TableCell>
                    ))}
                </StyledTableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>

      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mt: 3 }}>
        <Box>
          <Button
            variant="outlined"
            onClick={handleColumnsMenuClick}
            startIcon={<MenuIcon />}
          >
            Manage Columns
          </Button>
          <Menu
            anchorEl={columnsAnchorEl}
            open={columnsMenuOpen}
            onClose={handleMenuClose}
          >
            {Object.entries(visibleColumns).map(([column, visible]) => (
              <MenuItem key={column} onClick={() => toggleColumn(column)}>
                <FormControlLabel
                  control={
                    <Checkbox
                      checked={visible}
                      onChange={() => toggleColumn(column)}
                    />
                  }
                  label={column.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')}
                />
              </MenuItem>
            ))}
          </Menu>
        </Box>

        <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
          <Typography variant="body2">
            Rows per page:
          </Typography>
          <FormControl size="small" sx={{ minWidth: 80 }}>
            <Select
              value={recordsPerPage}
              onChange={(e) => handleRecordsPerPageChange(e.target.value)}
              displayEmpty
              inputProps={{ 'aria-label': 'Without label' }}
            >
              {[5, 10, 20, 50].map((number) => (
                <MenuItem key={number} value={number}>
                  {number}
                </MenuItem>
              ))}
            </Select>
          </FormControl>
          <Pagination
            count={totalPages}
            page={currentPage}
            onChange={(_, value) => setCurrentPage(value)}
            color="primary"
            showFirstButton
            showLastButton
          />
        </Box>
      </Box>

      <Dialog open={openModal} onClose={handleCloseModal} fullWidth maxWidth="sm">
  <DialogTitle>
    {isEditing ? "Edit API Entry" : "Add API Entry"}
    <IconButton
      aria-label="close"
      onClick={handleCloseModal}
      sx={{
        position: 'absolute',
        right: 8,
        top: 8,
        color: (theme) => theme.palette.grey[500],
      }}
    >
      <CloseIcon />
    </IconButton>
  </DialogTitle>
  <DialogContent>
    <Box component="form" onSubmit={handleSubmit} sx={{ mt: 2 }}>
      <TextField
        margin="normal"
        fullWidth
        label="Table Name"
        name="table_name"
        value={currentApiEntry.table_name}
        onChange={handleInputChange}
        required
        error={!currentApiEntry.table_name}
        helperText={!currentApiEntry.table_name ? "Table name is required" : ""}
      />
      
      <TextField
        margin="normal"
        fullWidth
        label="Created At"
        name="createdAt"
        type="datetime-local"
        value={currentApiEntry.createdAt || ''}
        onChange={handleInputChange}
        InputLabelProps={{
          shrink: true,
        }}
      />
      
      <TextField
        margin="normal"
        fullWidth
        label="Updated At"
        name="updatedAt"
        type="datetime-local"
        value={currentApiEntry.updatedAt || ''}
        onChange={handleInputChange}
        InputLabelProps={{
          shrink: true,
        }}
      />
      
      <FormControlLabel
        control={
          <Checkbox
            name="isActive"
            checked={currentApiEntry.isActive}
            onChange={handleInputChange}
          />
        }
        label="Active?"
      />
    </Box>
  </DialogContent>
  <DialogActions>
    <Button onClick={handleCloseModal}>Cancel</Button>
    <Button 
      onClick={handleSubmit} 
      variant="contained" 
      color="primary"
      disabled={!currentApiEntry.table_name}
    >
      {isEditing ? "Update" : "Add"}
    </Button>
  </DialogActions>
</Dialog>
    </Box>
  );
};

export default APIRegistry;