import React, { useState, useRef, useEffect } from 'react';
import {
  Chip,
  IconButton,
  Stack,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tabs,
  Tooltip,
  useMediaQuery,
  Typography,
  TablePagination,
  Divider,
  Switch,
  OutlinedInput,
  InputAdornment
} from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';

import Titlecard from 'components/nearle_components/Titlecard';
import { EditOutlined, SearchOutlined, UsergroupAddOutlined } from '@ant-design/icons';
import { useTheme } from '@mui/material/styles';
import { useNavigate } from 'react-router';
import MainCard from 'components/MainCard';
import { FaUsersGear } from 'react-icons/fa6';
import { RiEBike2Fill } from 'react-icons/ri';
import { useQuery } from '@tanstack/react-query';
import { getAllUsers } from '../api/api';
import { Empty } from 'antd';
import OpenToast from 'components/nearle_components/OpenToast';
import axios from 'axios';
import { useDebounce } from 'use-debounce';

const Users = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const isBelowCustom400 = useMediaQuery(theme.breakpoints.down('custom400'));
  const [roleId, setRoleId] = useState(2);
  const [page, setPage] = React.useState(null);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [searchword, setSearchword] = useState('');
  const [debouncedSearchword] = useDebounce(searchword, 500);

  const textFieldRef = useRef(null);
  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */

  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

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

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

  const handleTabchange = (event, newValue) => {
    console.log('handleTabchange', newValue);
    setRoleId(newValue);
  };

  const { data: usersList, refetch: userListRefetch } = useQuery({
    queryKey: ['userlist', roleId, page, rowsPerPage, debouncedSearchword], // roleId should be declared in scope
    queryFn: ({ queryKey }) => getAllUsers(queryKey),
    enabled: !!roleId // ensures query only runs if roleId is truthy
  });

  const updateUser = async (obj) => {
    try {
      let response = await axios.put(`${process.env.REACT_APP_URL2}/users/update`, obj);
      console.log('updateUser', response);
      OpenToast(response.data.message, 'success', 2000);
      userListRefetch();
    } catch (err) {
      OpenToast(err.message, 'error', 2500);
    }
  };

  return (
    <>
      <Titlecard title="Users">
        {isBelowCustom400 ? (
          <Tooltip title={'Create User'}>
            <IconButton
              title="kannan"
              sx={{
                backgroundColor: 'primary.main',
                color: 'white',
                '&:hover': {
                  backgroundColor: 'primary.main'
                }
              }}
              onClick={() => {
                navigate('/users/create');
              }}
            >
              <UsergroupAddOutlined />
            </IconButton>
          </Tooltip>
        ) : (
          <Chip
            icon={<UsergroupAddOutlined style={{ fontSize: 18 }} />}
            label={'Create User'}
            variant="filled"
            color="primary"
            onClick={() => {
              navigate('/users/create');
            }}
            sx={{
              px: isBelowCustom400 ? 1.5 : 2,
              py: 1,
              height: 38,
              fontWeight: 500,
              fontSize: '0.875rem',
              cursor: 'pointer'
            }}
          />
        )}
      </Titlecard>
      <MainCard
        headerstyle={{ px: 0, py: 1, backgroundColor: 'white' }}
        contentSX={{ p: 0 }}
        title={
          <Stack
            direction={{ xs: 'column', custom500: 'row' }}
            gap={2}
            sx={{
              display: 'flex',
              alignItems: { xs: 'start', custom500: 'center' },
              justifyContent: { custom500: 'space-between' },
              px: 2
            }}
          >
            <Tabs value={roleId} onChange={handleTabchange}>
              <Tab label="Staffs" value={2} icon={<FaUsersGear />} iconPosition="start" />
              <Tab label="Riders" value={3} icon={<RiEBike2Fill />} iconPosition="start" />
            </Tabs>
            <OutlinedInput
              inputRef={textFieldRef}
              id="header-search"
              aria-describedby="header-search-text"
              placeholder="Search (ctrl+k)"
              autoComplete="off"
              sx={{ width: { xs: '100%', custom500: 'auto' } }}
              value={searchword}
              onChange={(e) => setSearchword(e.target.value)}
              startAdornment={
                <InputAdornment position="start" sx={{ mr: -0.5 }}>
                  <SearchOutlined sx={{ color: theme.palette.primary.main }} />
                </InputAdornment>
              }
              endAdornment={
                <Tooltip title="Clear">
                  <IconButton
                    sx={{ visibility: searchword ? 'visible' : 'hidden' }}
                    onClick={() => {
                      setSearchword('');
                    }}
                  >
                    <ClearIcon sx={{ color: theme.palette.primary.main }} />
                  </IconButton>
                </Tooltip>
              }
            />
          </Stack>
        }
      >
        {/* Tabs Header */}

        <TableContainer sx={{ maxHeight: 'calc(100vh - 300px)' }}>
          <Table stickyHeader>
            <TableHead>
              <TableRow>
                <TableCell sx={{ position: 'sticky !important' }}>#</TableCell>
                <TableCell noWrap sx={{ position: 'sticky !important' }}>
                  {roleId === 2 ? 'Staff Name' : 'Rider Name'}
                </TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Contact</TableCell>
                <TableCell sx={{ position: 'sticky !important' }}>Shift</TableCell>
                <TableCell sx={{ position: 'sticky !important' }} l>
                  Address
                </TableCell>
                <TableCell sx={{ position: 'sticky !important' }} l>
                  Actions
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {(!usersList || usersList.length <= 0) && (
                <TableRow>
                  <TableCell colSpan={5}>
                    <Stack sx={{ width: '100%' }} display={'flex'} alignItems={'center'} justifyContent={'center'}>
                      <Empty description={roleId == 2 ? 'No Staffs' : 'No Riders'} />
                    </Stack>
                  </TableCell>
                </TableRow>
              )}
              {usersList?.map((user, index) => (
                <TableRow key={user.userid}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>
                    <Typography variant="body1" noWrap>
                      {user.fullname?.trim()}
                    </Typography>
                    <Typography variant="body2" noWrap color={'secondary'}>
                      {`ID : ${user.userid}`}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Stack>
                      <Typography variant="body1">{user.email}</Typography>
                      <Typography variant="subtitle2" color="text.secondary">
                        {user.contactno}
                      </Typography>
                    </Stack>
                  </TableCell>
                  <TableCell>
                    <Chip label={user.shiftname} />
                  </TableCell>
                  <TableCell>
                    <Typography
                      variant="body1"
                      sx={{
                        whiteSpace: 'wrap'
                      }}
                    >
                      {user.address}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <Stack direction={'row'} alignItems={'center'} spacing={2}>
                      <Switch
                        size="small"
                        checked={user.status == 'Active'}
                        onChange={(e) => {
                          updateUser({ userid: user.userid, status: e.target.checked ? 'Active' : 'InActive' });
                        }}
                        name="isActive"
                        color="primary"
                      />
                      <IconButton
                        sx={{ backgroundColor: theme.palette.primary.lighter }}
                        color="primary"
                        onClick={() => navigate('/users/edit', { state: { user } })}
                      >
                        <EditOutlined />
                      </IconButton>
                    </Stack>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>

        {(!!usersList || usersList?.length > 0) && (
          <>
            <Divider />
            <TablePagination
              rowsPerPageOptions={[5, 10, 25]}
              component="div"
              count={usersList?.length || 0}
              rowsPerPage={rowsPerPage}
              page={page}
              onPageChange={handleChangePage}
              onRowsPerPageChange={handleChangeRowsPerPage}
              sx={{ backgroundColor: 'bg.lighter', mb: -3 }}
            />
          </>
        )}
      </MainCard>
    </>
  );
};

export default Users;
