import React, { ChangeEvent, useEffect, useState } from "react";
import { useGetIntranetUsersData } from "../../APIs/IntranetUsersAPIs/getUsersList";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  tableRowClasses,
  Paper,
  Button,
  IconButton,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TablePagination,
  Grid,
  InputAdornment,
  Box,
} from '@mui/material';
import EditIcon from '@mui/icons-material/Edit';
import AddIcon from '@mui/icons-material/Add';
import { postNewIntranetUsersData } from "../../APIs/IntranetUsersAPIs/postAddUser";
import { AccountCircle } from "@mui/icons-material";
import SearchIcon from '@mui/icons-material/Search';


const StyledTextField = (props:any) => (
    <TextField
      variant="standard"
      margin="dense"
      fullWidth
      {...props}
      sx={{
        input: { color: 'white' },
        '& label': { color: 'white' },
        '& label.Mui-focused': { color: 'white' },
        '& .MuiInput-underline:after': { borderBottomColor: 'white' },
        '& .MuiOutlinedInput-root': {
          '& fieldset': { borderColor: 'white' },
          '&:hover fieldset': { borderColor: 'white', borderWidth: 2 },
          // '&.Mui-focused fieldset': { borderColor: 'white' },
        },
        ...props.sx,
      }}
    />
  );

  interface Row {
    username: string;
    role: string;
    active:any;
  }
  
export default function IntranetUsers(){
    const [searchByFilterOnBlur,setSearchByFilterOnBlur] = useState<any>()
    const { data: manageUsersResponse, isLoading, isError } = useGetIntranetUsersData();
    const [data, setData] = useState<Row[]>([]);
    const [open, setOpen] = useState(false);
    const [selectedRow, setSelectedRow] = useState<any>();
    const [newRow, setNewRow] = useState<any>();
    const [page, setPage] = React.useState(0);
    const [rowsPerPage, setRowsPerPage] = React.useState(10);
    const [filteredData, setFilteredData] = useState<Row[]>([]);

    useEffect(() => {
      if (searchByFilterOnBlur) {
        // Filter data based on the username
        const filtered = manageUsersResponse?.filter((row: any) =>
          row.username.toLowerCase().includes(searchByFilterOnBlur.toLowerCase()) ||
          row.role.toLowerCase().includes(searchByFilterOnBlur.toLowerCase())
        );
        setFilteredData(filtered || []);
      } else {
        // If search input is empty, show all data
        setFilteredData(manageUsersResponse || []);
      }
    }, [searchByFilterOnBlur, manageUsersResponse]);

    useEffect(()=>{
      if (!open){
        setSelectedRow({username: '', role: '', active: '' });
        setNewRow({username: '', role: '', active: '' });  
      }
    },[open])
    useEffect(() => {
      if (selectedRow){
        postNewIntranetUsersData(selectedRow);
      }
     },[data])
      
    const handleChangePage = (event:any, newPage:any) => {
      setPage(newPage);
    };
  
    const handleChangeRowsPerPage = (event:any) => {
      setRowsPerPage(+event.target.value);
      setPage(0);
    };
  
    const handleEdit = (row: Row) => {
      setSelectedRow({...row});
      setOpen(true);
    };

    const handleSave = () => {
      // if (selectedRow.id) {
      //   const updatedData = data.map((row) => (row.id === selectedRow.id ? selectedRow : row));
      //   setData(updatedData);
      // } else {
        const id = data.length + 1;
        setData([...data, { ...selectedRow, id }]);
      // }
    
      setOpen(false);
    };
  
    const handleClose = () => {
      setOpen(false);
      setSelectedRow({username: '', role: '', active: '' });
      setNewRow({username: '', role: '', active: '' });
    };
  
    const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
      const { name, value } = e.target;
      if (selectedRow) {
        // Editing existing row
        setSelectedRow({ ...selectedRow, [name]: value });
      } else {
        // Adding a new row
        setNewRow({ ...newRow, [name]: value });
      }
    };

    const handleOpen = () => {
      setOpen(true);
    };
  
    return(
      <Box sx={{ backgroundColor: "#0d0d0d", minHeight: "100vh" }}>
        <Paper square className='projectScreen-background' sx={{ width: '100%', overflow: 'hidden',backgroundColor:'rgb(13 13 13)' }}>
            <Paper  className='projectScreen-background' sx={{ margin:'1%', width: '100%', overflow: 'hidden' }}>
                <TableContainer component={Paper}>
                      <TableRow sx={{bgcolor:'#171716 !important',borderBottom:'#171716',width:'100%', display:'flex',flexDirection:'row-reverse'}}>
                        <TableCell className="no-padding-cell" sx={{borderBottom:'black'}}>
                          <TextField
                              id="standard-name"
                              variant="standard"
                              InputProps={{
                                startAdornment: (
                                  <InputAdornment sx={{fontSize: 40}} position="start">
                                    <SearchIcon sx={{color:'white'}}/>
                                  </InputAdornment>
                                ),
                              }}
                              value={searchByFilterOnBlur}
                              onChange={(e)=>{
                                  setSearchByFilterOnBlur(e.target.value);
                              }}
                              sx={{input: { color: 'white' },
                              "& label": {
                                  color: "white"
                                },
                                "& label.Mui-focused": {
                                  color: "white"
                                },
                                "& .MuiInput-underline:after": {
                                  borderBottomColor: "white"
                                },
                                "& .MuiOutlinedInput-root": {
                                  "& fieldset": {
                                    borderColor: "white"
                                  }},
                                  "&:hover fieldset": {
                                      borderColor: "white",
                                      borderWidth: 2
                                    },
                                    "&.Mui-focused fieldset": {
                                      borderColor: "white"
                                    },
                                    margin:1,
                                    // marginTop:3
                                                                     
                              }}
                              placeholder="Search..."
                          />
                        </TableCell>                          
                        </TableRow>
                    <Table>
                    <TableHead className="manageusers-table-header-style">
                        <TableRow>
                            <TableCell className="no-padding-cell">
                                <Button variant="contained" sx={{bgcolor:'#1e1e1e',color:'#3f51b5', fontWeight:600}}  onClick={handleOpen}>
                                    New
                                </Button>
                            </TableCell>
                            <TableCell className="no-padding-cell table-header-bottomBorder-style">Name</TableCell>
                            <TableCell className="no-padding-cell">Role</TableCell>
                            <TableCell className="no-padding-cell">Active</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {filteredData && filteredData.map((row:any) => (
                        <TableRow key={row.id} sx={{height:'20px'}}>
                            <TableCell className="no-padding-cell">
                            <IconButton onClick={() => handleEdit(row)} aria-label="edit">
                                <EditIcon sx={{ color: 'white' }}/>
                            </IconButton>
                            </TableCell>
                            <TableCell className="no-padding-cell">{row.username}</TableCell>
                            <TableCell className="no-padding-cell">{row.role}</TableCell>
                            {row.active==1?
                              <TableCell className="no-padding-cell" sx={{color:'green', backgroundColor:'#171716', borderBottom:'1px solid rgb(45 51 59)'}}>Active</TableCell>
                            :
                              <TableCell className="no-padding-cell" sx={{color:'red', backgroundColor:'#171716', borderBottom:'1px solid rgb(45 51 59)'}}>Inactive</TableCell>}
                        </TableRow>
                        ))}
                    </TableBody>
                    </Table>
                </TableContainer>
                <TablePagination
                  sx={{bgcolor:'#171716',color:'white'}}
                  rowsPerPageOptions={[10, 25, 100]}
                  component="div"
                  count={manageUsersResponse && manageUsersResponse.length}
                  rowsPerPage={rowsPerPage}
                  page={page}
                  onPageChange={handleChangePage}
                  onRowsPerPageChange={handleChangeRowsPerPage}
                />
                <Dialog  open={open} onClose={handleClose}>
                    <DialogTitle sx={{bgcolor:'rgb(24 24 23)', color:'white'}}>{selectedRow && selectedRow.id ? 'Edit Row' : 'Add New Row'}</DialogTitle>
                    <DialogContent sx={{ bgcolor: 'rgb(24 24 23)' }}>
                        <StyledTextField
                        label="Name"
                        type="text"
                        name="username"
                        value={selectedRow && selectedRow.username}
                        onChange={handleChange}
                        />
                        <StyledTextField
                        label="Role"
                        name="role"
                        value={selectedRow && selectedRow.role}
                        onChange={handleChange}
                        />
                        <StyledTextField
                        label="Active"
                        name="active"
                        value={selectedRow && selectedRow.active}
                        onChange={handleChange}
                        />
                    </DialogContent>
                    <DialogActions sx={{bgcolor:'rgb(24 24 23)'}}>
                    <Button onClick={handleClose} color="primary">
                        Cancel
                    </Button>
                    <Button onClick={handleSave} color="primary">
                        Save
                    </Button>
                    </DialogActions>
                </Dialog>
            </Paper>
        </Paper>
      </Box>
    )
}