/* eslint-disable */
// React Imports
'use client'
import { ChangeEvent, FormHTMLAttributes, use, useEffect, useMemo, useState, type ReactElement } from 'react'

// Next Imports
import Card from '@mui/material/Card'
import CardContent from '@mui/material/CardContent'
// Component Imports
import {
  alpha,
  Avatar,
  Box,
  Button,
  Checkbox,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Divider,
  Drawer,
  FormControlLabel,
  Grid,
  IconButton,
  Paper,
  Stack,
  Tab,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  TableSortLabel,
  TextField,
  Toolbar,
  Tooltip,
  Typography
} from '@mui/material'
import { visuallyHidden } from '@mui/utils'
import CloseIcon from '@mui/icons-material/Close'
// import { createClubs, deleteClubs, loadClubs, searchClub } from '@/libs/clubs'
import DoctorTableRow from './components/table-row'
import UpdateDoctorDrawer from './components/update-doctor'

import { useRouter } from 'next/navigation'
import useAPI from '@/hooks/useAPI'

interface Data {
  id: number
  name: string
  logo: string | any
}

function createData(id: number, name: string, logo: string | any): Data {
  return {
    id,
    name,
    logo
  }
}

function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
  if (b[orderBy] < a[orderBy]) {
    return -1
  }
  if (b[orderBy] > a[orderBy]) {
    return 1
  }
  return 0
}

type Order = 'asc' | 'desc'

function getComparator<Key extends keyof any>(
  order: Order,
  orderBy: Key
): (a: { [key in Key]: number | string }, b: { [key in Key]: number | string }) => number {
  return order === 'desc'
    ? (a, b) => descendingComparator(a, b, orderBy)
    : (a, b) => -descendingComparator(a, b, orderBy)
}

function stableSort<T>(array: readonly T[], comparator: (a: T, b: T) => number) {
  const stabilizedThis = array.map((el, index) => [el, index] as [T, number])
  stabilizedThis.sort((a, b) => {
    const order = comparator(a[0], b[0])
    if (order !== 0) {
      return order
    }
    return a[1] - b[1]
  })
  return stabilizedThis.map(el => el[0])
}

interface HeadCell {
  disablePadding: boolean
  id: string
  label: string
  numeric: boolean
}

const headCells: readonly HeadCell[] = [
  {
    id: 'profilePicture',
    numeric: false,
    disablePadding: false,
    label: 'Profile'
  },
  {
    id: 'firstName',
    numeric: false,
    disablePadding: false,
    label: 'Name'
  },
  {
    id: 'email',
    numeric: false,
    disablePadding: false,
    label: 'Email'
  },
  {
    id: 'createdAt',
    numeric: false,
    disablePadding: false,
    label: 'Created At'
  }
]

interface EnhancedTableProps {
  numSelected: number
  onRequestSort: (event: React.MouseEvent<unknown>, property: keyof Data) => void
  onSelectAllClick: (event: React.ChangeEvent<HTMLInputElement>) => void
  order: Order
  orderBy: string
  rowCount: number
}

function EnhancedTableHead(props: EnhancedTableProps) {
  const { onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort } = props
  const createSortHandler = (property: keyof Data) => (event: React.MouseEvent<unknown>) => {
    onRequestSort(event, property)
  }

  return (
    <TableHead>
      <TableRow sx={{ backgroundColor: 'rgb(3 3 3 / 14%)' }}>
        {/* <TableCell padding="checkbox">
          <Checkbox
            color="primary"
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
            inputProps={{
              'aria-label': 'select all desserts',
            }}
          />
        </TableCell> */}
        {headCells.map(headCell => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? 'right' : 'left'}
            padding={headCell.disablePadding ? 'none' : 'normal'}
            sortDirection={orderBy === headCell.id ? order : false}
            sx={{
              fontSize: '16px', 
              fontWeight: 600
            }}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : 'asc'}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <Box component='span' sx={visuallyHidden}>
                  {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                </Box>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
        <TableCell></TableCell>
      </TableRow>
    </TableHead>
  )
}

const UserPage = () => {
  const [order, setOrder] = useState<Order>('asc')
  const [orderBy, setOrderBy] = useState<keyof Data>('name')
  const [selected, setSelected] = useState<readonly number[]>([])
  const [page, setPage] = useState(0)
  const [rowsPerPage, setRowsPerPage] = useState(20)
  const [addClubDrawerOpen, setAddClubDrawerOpen] = useState(false)
  const [updateDoctorDrawerOpen, setUpdateDoctorDrawerOpen] = useState(false)
  const [editDoctorData, setEditDoctorData] = useState<any>(null)
  const [rows, setRows] = useState<any>([])
  const [deleteClubId, setDeleteClubId] = useState('')
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  //   const [editClubData, setEditClubData] = useState<any>(null)
  const [searchTerm, setSearchTerm] = useState<string>('')
  const [defaultRows, setDefaultRows] = useState<any>([])
  const router = useRouter()
  const api = useAPI();
  const getUsers = async () => 
    {
    const response = await (await api).user.get();
    console.log('response',response.data.data);
    
    setRows(response.data.data)
    setDefaultRows(response.data.data)
  }

  useEffect(() => {
    getUsers()
  }, [])

  const handleRequestSort = (event: React.MouseEvent<unknown>, property: keyof Data) => {
    const isAsc = orderBy === property && order === 'asc'
    setOrder(isAsc ? 'desc' : 'asc')
    setOrderBy(property)
  }

  const handleSelectAllClick = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.checked) {
      const newSelected = rows.map((n: any) => n.id)
      setSelected(newSelected)
      return
    }
    setSelected([])
  }

  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage)
  }

  const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRowsPerPage(parseInt(event.target.value, 10))
    setPage(0)
  }

  const isSelected = (id: number) => selected.indexOf(id) !== -1

  // Avoid a layout jump when reaching the last page with empty rows.
  const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0

  const visibleRows = useMemo(
    () => stableSort(rows, getComparator(order, orderBy)).slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage),
    [order, orderBy, page, rowsPerPage, rows]
  )

  const handleDeleteDoctorClick = (id: string) => {
    setDeleteClubId(id)
    setDeleteDialogOpen(true)
  }

  const handleEditDoctorClick = (data: any) => {
    setEditDoctorData(data)
    // setUpdateDoctorDrawerOpen(true) // This will open the drawer component
    // window.location.href = `/admin/doctor/components/update-doctor?id=${data._id}`  }
    router.push(`/admin/doctor/${data._id}/edit`)  }

  const handleDeleteDoctor = async () => {
    // const res = await deleteDoctor(deleteClubId)

    setDeleteDialogOpen(false)
    getUsers()
  }

  const handleSearchDoctor = async (searchTerm: string) => {
    setSearchTerm(searchTerm)
    if (!searchTerm) {
      setRows(defaultRows)
      return
    }
    // const res = await searchDoctor(searchTerm)
    // console.log('search res', res)
    // setRows(res.result)
  }

  return (
    <Box>
      {/* <Box mb={5}>
      <Grid container spacing={2}>
        <Grid item sm={6} xs={12} xl={4} >
          <Card sx={{ width: '100%' }}>
            <CardContent>
              <Stack direction={'row'} justifyContent={'space-between'}>
                <Typography>Clubs</Typography>
                <i className="ri-group-line text-[26px]"></i>
              </Stack>
              <Typography variant='h4'>{rows.length}</Typography>
              <Typography variant='caption'>Total Clubs</Typography>

            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </Box> */}

      <Box sx={{ width: '100%' }}>
        <Paper sx={{ width: '100%', mb: 2 }}>
          {/* <EnhancedTableToolbar numSelected={selected.length} /> */}
          <Stack direction={'row'} justifyContent={'space-between'} alignItems={'center'} pl={4}>
            <Stack direction={'row'} alignItems={'center'} spacing={2}>
              <Typography variant='h4'>Users</Typography>
              <TextField
                variant='outlined'
                size='small'
                placeholder='Search...'
                value={searchTerm}
                onChange={e => handleSearchDoctor(e.target.value)}
                sx={{ width: 250 }}
              />
            </Stack>
            <Box textAlign={'right'} p={4}>
              <Button variant='contained' onClick={() => router.push('user/add')}>
                Add User
              </Button>
            </Box>
          </Stack>

          <TableContainer>
            <Table sx={{ minWidth: 750 }} aria-labelledby='tableTitle'>
              <EnhancedTableHead
                numSelected={selected.length}
                order={order}
                orderBy={orderBy}
                onSelectAllClick={handleSelectAllClick}
                onRequestSort={handleRequestSort}
                rowCount={rows.length}
              />
              <TableBody>
                {visibleRows.map((row: any, index: number) => {
                  const labelId = `enhanced-table-checkbox-${index}`
                  return (
                    <DoctorTableRow
                      handleEditDoctorClick={handleEditDoctorClick}
                      handleDeleteDoctorClick={handleDeleteDoctorClick}
                      labelId={labelId}
                      key={index}
                      row={row}
                    />
                  )
                })}
              </TableBody>
            </Table>
          </TableContainer>
          <TablePagination
            rowsPerPageOptions={[5, 10, 25]}
            component='div'
            count={rows.length}
            rowsPerPage={rowsPerPage}
            page={page}
            onPageChange={handleChangePage}
            onRowsPerPageChange={handleChangeRowsPerPage}
          />
        </Paper>
      </Box>
      <Dialog open={deleteDialogOpen} fullWidth maxWidth='sm'>
        <DialogTitle id='alert-dialog-title'>Delete</DialogTitle>
        <DialogContent>
          <DialogContentText id='alert-dialog-description'>Are you sure want to delete?</DialogContentText>
        </DialogContent>
        <DialogActions sx={{ padding: 3 }}>
          <Button
            onClick={() => {
              setDeleteDialogOpen(false)
            }}
            variant='outlined'
          >
            Cancel
          </Button>
          <Button onClick={handleDeleteDoctor} variant='contained' color='error' autoFocus>
            Delete
          </Button>
        </DialogActions>
      </Dialog>

      <UpdateDoctorDrawer
        updateDoctorDrawerOpen={updateDoctorDrawerOpen}
        setUpdateDoctorDrawerOpen={setUpdateDoctorDrawerOpen}
        getUsers={getUsers}
        data={editDoctorData}
      />
    </Box>
  )
}

export default UserPage
