import React, { ChangeEvent, useEffect, useState } from "react";
import { getUsersList, useGetUsersData } from "../../APIs/ManageUsersAPIs/getUsersList";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  tableRowClasses,
  Paper,
  Button,
  IconButton,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TablePagination,
} from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit';
import AddIcon from '@mui/icons-material/Add';

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 {
    name: string;
    email: string;
    last_login:string;
    active:boolean|string;
  }
  
export default function ManageUsers(){
    const [manageUsersData,setManageUsersData] = useState<any>()
    const { data: manageUsersResponse, isLoading, isError } = useGetUsersData();
    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 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);
      setSelectedRow({name: '', email: '', last_login: '', active: '' });
      setNewRow({name: '', email: '', last_login: '', active: '' });
    };
  
    const handleClose = () => {
      setOpen(false);
      setSelectedRow({name: '', email: '', last_login: '', active: '' });
      setNewRow({name: '', email: '', last_login: '', 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);
    };
    console.log(selectedRow,"sdfhhgfdg")
  
    return(
        <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}>
                    <Table>
                    <TableHead className="manageusers-table-header-style">
                        <TableRow>
                            <TableCell>
                                <Button variant="contained" sx={{bgcolor:'white',color:'#1e1e1e', fontWeight:600}} startIcon={<AddIcon />} onClick={handleOpen}>
                                    New
                                </Button>
                            </TableCell>
                            <TableCell>Name</TableCell>
                            <TableCell>Email Id</TableCell>
                            <TableCell>Last Login</TableCell>
                            <TableCell>Active</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {manageUsersResponse && manageUsersResponse.map((row:any) => (
                        <TableRow key={row.id} sx={{height:'20px'}}>
                            <TableCell>
                            <IconButton onClick={() => handleEdit(row)} aria-label="edit">
                                <EditIcon sx={{ color: 'white' }}/>
                            </IconButton>
                            {/* <IconButton onClick={() => handleDelete(row.id)} aria-label="delete">
                                <DeleteIcon sx={{ color: 'white' }}/>
                            </IconButton> */}
                            </TableCell>
                            <TableCell>{row.username}</TableCell>
                            <TableCell>{row.email_id}</TableCell>
                            <TableCell>{row.last_login}</TableCell>
                            {row.active?
                            <TableCell sx={{color:'green', backgroundColor:'#171716', borderBottom:'1px solid rgb(45 51 59)'}}>Active</TableCell>
                            :
                            <TableCell 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="name"
                        value={selectedRow && selectedRow.name}
                        onChange={handleChange}
                        />
                        <StyledTextField
                        label="Email"
                        name="email"
                        value={selectedRow && selectedRow.email_id}
                        onChange={handleChange}
                        />
                        <StyledTextField
                        label="Last Login"
                        type="last_login"
                        name="last_login"
                        value={selectedRow && selectedRow.last_login}
                        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>
    )
}