"use client";
import React, { useCallback } from "react";
import { useEffect, useState } from "react";

import {
  Grid, Box, Alert,
  TableContainer,
  Table,
  TableRow,
  TableCell,
  TableBody,
  TableHead,
  Button,
  Typography,
  Dialog,
  DialogContent,
  Icon,
  Paper,
  DialogContentText,
  DialogActions,
  DialogTitle,
  IconButton,
  LinearProgress,
  TextField,
  Pagination,
  Chip
} from "@mui/material";
import PageContainer from "@/app/components/container/PageContainer";
import BaseCard from "@/app/components/shared/BaseCard";
import {
  basicsTableData,
  EnTableType,
  TableType,
} from "@/app/components/tables/tableData";
import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from "@tanstack/react-table";
// components
import YearlyBreakup from "@/app/components/dashboards/modern/YearlyBreakup";
import MonthlyEarnings from "@/app/components/dashboards/modern/MonthlyEarnings";
import TopCards from "@/app/components/dashboards/modern/TopCards";
import RevenueUpdates from "@/app/components/dashboards/modern/RevenueUpdates";
import EmployeeSalary from "@/app/components/dashboards/modern/EmployeeSalary";
import Customers from "@/app/components/dashboards/modern/Customers";
import Projects from "@/app/components/dashboards/modern/Projects";
import Social from "@/app/components/dashboards/modern/Social";
import SellingProducts from "@/app/components/dashboards/modern/SellingProducts";
import WeeklyStats from "@/app/components/dashboards/modern/WeeklyStats";
import TopPerformers from "@/app/components/dashboards/modern/TopPerformers";
import axios from "axios";
import { useParams, useRouter, useSearchParams } from "next/navigation";
import { getSession } from '@/utils/sessionData';
// import TopCardsNew from "../../components/dashboards/modern/TopCardsNew";
import TableBasicReact from "./TableBasicReact";
import CloseIcon from '@mui/icons-material/Close'
import debounce from 'lodash.debounce';


export default function Dashboard() {
  const [searchTerm, setSearchTerm] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  useEffect(() => {
    setIsLoading(false);
  }, []);

  const router = useRouter();
  const checkSession = async () => {
    const session = getSession()
    if (!session?.admin_id && !session?.token) {
      router.push('/login')
    }
  }
  useEffect(() => {
    checkSession()
  }, [])

  const [sessionData, setSessionData] = useState<any>();
  const [txns, setTxns] = useState<any>([])
  const [game, setGame] = useState<any>();
  const params = useParams();
  const id = params.id;
  const [openDialog, setOpenDialog] = useState(false)
  const [selectedRow, setSelectedRow] = useState<any>(null);
  const searchParams = useSearchParams();
  const kioskId = searchParams?.get("kioskId") ?? searchParams?.get("kiosk_id");
  const [totalCount, setTotalCount] = useState<number>(0);

  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [globalFilter, setGlobalFilter] = useState<any>('');
  const [sorting, setSorting] = useState([{ id: 'created_at', desc: true }]);


  const fetchGames = async () => {


    try {
      setIsLoading(true);
      const token = sessionData?.token;
      const payload = {
        token,
        page: page + 1,
        limit: pageSize,
        search: searchTerm,
        id: id
      }
      const response = await axios.post(`/api/getUsers`, payload);
      if (response?.data?.status !== 'error') {
        setTxns(response.data.users || []);

        // setGames(response?.data?.creations || []);
        setTotalCount(response?.data?.totalCount || 0);
        // setGame(response?.data?.game || {});
      }
    } catch (error: any) {
      console.error(error.message);
    } finally {
      setIsLoading(false);
    }

  };

  const handleCloseDialog = () => {
    setSelectedRow(null);
    setOpenDialog(false);
  };
  useEffect(() => {
    const session = getSession();
    setSessionData(session);
  }, []);

  useEffect(() => {
    if (sessionData?.token && sessionData?.admin_id) {
      fetchGames()
    }
  }, [sessionData?.token, sessionData?.admin_id, page, pageSize, searchTerm]);


  const handleSearch = (e: any) => {
    console.log(e.target.value)
    const value = e.target.value;
    setGlobalFilter(value);

  };

  useEffect(() => {
    const handler = setTimeout(() => {
      setSearchTerm(globalFilter); // update debounced value
    }, 500); // adjust delay here

    return () => {
      clearTimeout(handler); // cancel previous timeout on new keystroke
    };
  }, [globalFilter]);

  const columnHelper = createColumnHelper<EnTableType>();

  const columns = [
    columnHelper.accessor("id", {
      header: () => "ID",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > {row.index + 1}</Typography>

      ),
    }),
    columnHelper.accessor("firstName", {
      header: () => "First Name",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > {row?.original?.firstName}</Typography>

      ),
    }),
    columnHelper.accessor("lastName", {
      header: () => "Last Name",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > {row?.original?.lastName}</Typography>
      ),
    }),

    columnHelper.accessor("phone", {
      header: () => "Phone",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > {row?.original?.phone}</Typography>
      ),
    }),
    columnHelper.accessor("balance", {
      header: () => "Balance",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > ${row?.original?.balance}</Typography>
      ),
    }),
    columnHelper.accessor("idenfy_verified", {
      header: () => "Verification",
      cell: ({ row }) => (
        <Chip label={row?.original?.idenfy_verified == '1' ? 'Verified' : 'Unverified'} color={row?.original?.idenfy_verified == '1' ? 'success' : 'warning'} />
      ),
    }),
    {
      accessorKey: 'id',
      header: 'View',
      cell: ({ row }: any) => (
        <Button
          onClick={() => {
            router.push(`/viewUser/${row?.original?.id}?kiosk_id=${kioskId}`)
            // setSelectedRow(row.original);
            // setOpenDialog(true);
          }}
        >
          View
        </Button>
      ),

    }
  ];

  const table = useReactTable({
    data: txns,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (

    (<PageContainer title="Users" description="this is Users">
      <Box >
        <Grid container spacing={3}>
          {/* column */}
          <Grid
            size={{
              xs: 12,
              lg: 12
            }}>
            {isLoading && <LinearProgress />}

            <BaseCard title="Users" searchBar={
              <TextField
                fullWidth
                variant="outlined"
                placeholder="Search..."
                value={globalFilter}
                onChange={handleSearch}
              />
            }>
              <Grid>
                <Box>
                  <TableContainer>
                    <Table sx={{ whiteSpace: 'nowrap' }}>
                      <TableHead>
                        {table.getHeaderGroups().map((headerGroup) => (
                          <TableRow key={headerGroup.id}>
                            {headerGroup.headers.map((header) => (
                              <TableCell key={header.id}>
                                <Typography variant="h6">
                                  {header.isPlaceholder
                                    ? null
                                    : flexRender(
                                      header.column.columnDef.header,
                                      header.getContext()
                                    )}
                                </Typography>
                              </TableCell>
                            ))}
                          </TableRow>
                        ))}
                      </TableHead>
                      <TableBody>
                        {table.getRowModel().rows.map((row) => (
                          <TableRow key={row.id}>
                            {row.getVisibleCells().map((cell) => (
                              <TableCell key={cell.id}>
                                {flexRender(
                                  cell.column.columnDef.cell,
                                  cell.getContext()
                                )}
                              </TableCell>
                            ))}
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </TableContainer>
                  <Box display="flex" justifyContent="center" mt={2}>
                    <Pagination
                      count={Math.ceil(totalCount / pageSize)}
                      page={page + 1}
                      onChange={(_, newPage) => setPage(newPage - 1)}
                      color="primary"
                    />
                  </Box>
                </Box>
              </Grid>
            </BaseCard>
          </Grid>
          <Dialog open={openDialog} onClose={handleCloseDialog} fullWidth maxWidth="sm">
            <DialogTitle sx={{ m: 0, p: 2 }}>
              User Details
              <IconButton
                aria-label="close"
                onClick={handleCloseDialog}
                sx={{
                  position: 'absolute',
                  right: 8,
                  top: 8,
                  color: (theme) => theme.palette.grey[500],
                }}
              >
                <CloseIcon />
              </IconButton>
            </DialogTitle>

            <DialogContent dividers>
              <Box mt={2}>
                {selectedRow && (
                  <Box
                    display="flex"
                    flexWrap="wrap"
                    gap={3}
                    mt={2}
                    justifyContent="space-between"
                  >
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        User ID
                      </Typography>
                      <Typography variant="h6">{selectedRow.id}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Phone
                      </Typography>
                      <Typography variant="h6">{selectedRow.phone}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Firstname
                      </Typography>
                      <Typography variant="h6">{selectedRow.firstName}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Lastname
                      </Typography>
                      <Typography variant="h6">{selectedRow.lastName}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Balance
                      </Typography>
                      <Typography variant="h6">${selectedRow.balance}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Status
                      </Typography>
                      <Chip label={selectedRow?.idenfy_verified == '1' ? 'Verified' : 'Unverified'} color={selectedRow?.idenfy_verified == '1' ? 'success' : 'warning'} />

                    </Box>
                  </Box>
                )}
              </Box>
            </DialogContent>
          </Dialog>
        </Grid>
      </Box>
    </PageContainer>)
  );
}
