import React, { useState, useEffect } from 'react';
import axios from 'axios';
import {
  Container,
  Grid,
  TextField,
  Pagination,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Button
} from '@mui/material';

const SchemasComponent = () => {
  const [schemas, setSchemas] = useState([]);
  const [filteredSchemas, setFilteredSchemas] = useState([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [page, setPage] = useState(1);
  const [open, setOpen] = useState(false);
  const [selectedSchema, setSelectedSchema] = useState(null);

  const schemasPerPage = 10;

  useEffect(() => {
    axios.get(`${import.meta.env.VITE_REACT_APP_LEUMAS_API_ENDPOINT}/schema`)
      .then(response => {
        setSchemas(response.data);
        setFilteredSchemas(response.data);
      })
      .catch(error => console.error('Error fetching schemas:', error));
  }, []);

  useEffect(() => {
    setFilteredSchemas(
      schemas.filter(schema => schema.toLowerCase().includes(searchQuery.toLowerCase()))
    );
  }, [searchQuery, schemas]);

  const handleSearchChange = (event) => {
    setSearchQuery(event.target.value);
  };

  const handlePageChange = (event, value) => {
    setPage(value);
  };

  const handleClickOpen = (schema) => {
    setSelectedSchema(schema);
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
    setSelectedSchema(null);
  };

  const startIndex = (page - 1) * schemasPerPage;
  const displayedSchemas = filteredSchemas.slice(startIndex, startIndex + schemasPerPage);

  return (
    <Container>
      <TextField
        label="Search"
        variant="outlined"
        fullWidth
        margin="normal"
        value={searchQuery}
        onChange={handleSearchChange}
      />
      <Grid container spacing={2}>
        {displayedSchemas.map((schema, index) => (
          <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
            <Button
              variant="outlined"
              fullWidth
              onClick={() => handleClickOpen(schema)}
            >
              {schema}
            </Button>
          </Grid>
        ))}
      </Grid>
      <Pagination
        count={Math.ceil(filteredSchemas.length / schemasPerPage)}
        page={page}
        onChange={handlePageChange}
        color="primary"
        style={{ marginTop: '20px', display: 'flex', justifyContent: 'center' }}
      />
      <Dialog open={open} onClose={handleClose}>
        <DialogTitle>Navigate to {selectedSchema}</DialogTitle>
        <DialogContent>
          <DialogActions>
            <Button onClick={() => window.location.href = `/public/${selectedSchema}`}>Public</Button>
            <Button onClick={() => window.location.href = `/owned/${selectedSchema}`}>Owned</Button>
            <Button onClick={() => window.location.href = `/purchased/${selectedSchema}`}>Purchased</Button>
            <Button onClick={() => window.location.href = `/create/${selectedSchema}`}>Create</Button>
            <Button onClick={() => window.location.href = `/new/${selectedSchema}`}>New</Button>
            <Button onClick={() => window.location.href = `/build/new/${selectedSchema}`}>Build New</Button>
          </DialogActions>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Close</Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default SchemasComponent;
