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

// Next Imports
import { useRouter } from 'next/navigation'

// MUI Imports
import {
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  Paper,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  TableSortLabel,
  TextField,
  Typography
} from '@mui/material'
import { visuallyHidden } from '@mui/utils'

// Component Imports
import CategoryTableRow from './components/table-row'
import UpdateCategoryDrawer from './components/update-category'

// Hooks
import useAPI from '@/hooks/useAPI'

interface Data {
  id: number
  name: string
}

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

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: 'avatar',
  //   numeric: false,
  //   disablePadding: false,
  //   label: ''
  // },
  {
    id: 'name',
    numeric: false,
    disablePadding: false,
    label: 'Category Name'
  },
  {
    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%)' }}>
        {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 CategoryPage = () => {
  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 [updateCategoryDrawerOpen, setUpdateCategoryDrawerOpen] = useState(false)
  const [editCategoryData, setEditCategoryData] = useState<any>(null)
  const [rows, setRows] = useState<any>([])
  const [deleteCategoryId, setDeleteCategoryId] = useState('')
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [searchTerm, setSearchTerm] = useState<string>('')
  const [defaultRows, setDefaultRows] = useState<any>([])
  const router = useRouter()
  const api = useAPI();

 const getCategories = async () => {
  try {
    const apiInstance = await api;
    const response = await apiInstance.category.get();

    console.log(response.data)
    
    if (response.data && response.data.categories) {
      // Map the data to include _id for backward compatibility
      const mappedCategories = response.data.categories.map(category => ({
        ...category,
        _id: category.id // Add _id property that points to the same value as id
      }));
      
      setRows(mappedCategories);
      setDefaultRows(mappedCategories);
    } else {
      setRows([]);
      setDefaultRows([]);
      console.error('API returned empty data');
    }
  } catch (error) {
    console.error('Error fetching categories:', error);
    setRows([]);
    setDefaultRows([]);
  }
}




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

  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 handleDeleteCategoryClick = (id: string) => {
    setDeleteCategoryId(id)
    setDeleteDialogOpen(true)
  }

  const handleEditCategoryClick = (data: any) => {
    setEditCategoryData(data)
    router.push(`/admin/category/${data.id}/edit`)
    // setUpdateCategoryDrawerOpen(true)
  }

const handleDeleteCategory = async () => {
  try {
    const apiInstance = await api;
    await apiInstance.category.delete(deleteCategoryId);
    
    setDeleteDialogOpen(false);
    getCategories();
  } catch (error) {
    console.error('Error deleting category:', error);
  }
}

  const handleSearchCategory = async (searchTerm: string) => {
    setSearchTerm(searchTerm)
    if (!searchTerm) {
      setRows(defaultRows)
      return
    }
    
    // Filter locally for now
    const filteredRows = defaultRows.filter((row: any) => 
      row.name.toLowerCase().includes(searchTerm.toLowerCase())
    );
    setRows(filteredRows);
    
    // Uncomment when API is ready
    // try {
    //   const res = await (await api).category.search(searchTerm);
    //   setRows(res.data.data);
    // } catch (error) {
    //   console.error('Error searching categories:', error);
    // }
  }

  return (
    <Box>
      <Box sx={{ width: '100%' }}>
        <Paper sx={{ width: '100%', mb: 2 }}>
          <Stack direction={'row'} justifyContent={'space-between'} alignItems={'center'} pl={4}>
            <Stack direction={'row'} alignItems={'center'} spacing={2}>
              <Typography variant='h4'>Categories</Typography>
              <TextField
                variant='outlined'
                size='small'
                placeholder='Search...'
                value={searchTerm}
                onChange={e => handleSearchCategory(e.target.value)}
                sx={{ width: 250 }}
              />
            </Stack>
            <Box textAlign={'right'} p={4}>
              <Button variant='contained' onClick={() => router.push('category/add')}>
                Add Category
              </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 (
                    <CategoryTableRow
                      handleEditCategoryClick={handleEditCategoryClick}
                      handleDeleteCategoryClick={handleDeleteCategoryClick}
                      labelId={labelId}
                      key={index}
                      row={row}
                    />
                  )
                })}
                {emptyRows > 0 && (
                  <TableRow style={{ height: 53 * emptyRows }}>
                    <TableCell colSpan={3} />
                  </TableRow>
                )}
              </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 Category</DialogTitle>
        <DialogContent>
          <DialogContentText id='alert-dialog-description'>Are you sure you want to delete this category?</DialogContentText>
        </DialogContent>
        <DialogActions sx={{ padding: 3 }}>
          <Button
            onClick={() => {
              setDeleteDialogOpen(false)
            }}
            variant='outlined'
          >
            Cancel
          </Button>
          <Button onClick={handleDeleteCategory} variant='contained' color='error' autoFocus>
            Delete
          </Button>
        </DialogActions>
      </Dialog>
{/* 
      <UpdateCategoryDrawer
        updateCategoryDrawerOpen={updateCategoryDrawerOpen}
        setUpdateCategoryDrawerOpen={setUpdateCategoryDrawerOpen}
        getCategories={getCategories}
        data={editCategoryData}
      /> */}
    </Box>
  )
}

export default CategoryPage
