"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';
import { IconReload, IconSend, IconSend2 } from "@tabler/icons-react";


export default function Dashboard() {
  const [searchTerm, setSearchTerm] = useState('');
  const [searchTerm2, setSearchTerm2] = useState('');
  const [openVerifyModal, setOpenVerifyModal] = useState(false);

  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 [totalTxnCount, setTotalTxnCount] = useState<any>([])

  const [creations, setCreations] = useState<any>([])

  const [game, setGame] = useState<any>();
  const [user, setUser] = useState<any>();
  const params = useParams();
  const id = params.id;
  const [openDialog, setOpenDialog] = useState(false)
  const [selectedRow, setSelectedRow] = useState<any>(null);

  const [totalCount, setTotalCount] = useState<number>(0);

  const [page, setPage] = useState(0);
  const [pageSize, setPageSize] = useState(10);
  const [globalFilter, setGlobalFilter] = useState<any>('');
  const [globalFilter2, setGlobalFilter2] = useState<any>('');

  const [page2, setPage2] = useState(0);
  const [pageSize2, setPageSize2] = useState(10);

  const [sorting, setSorting] = useState([{ id: 'created_at', desc: true }]);

  const searchParams = useSearchParams();
  const kioskId = searchParams?.get("kioskId") ?? searchParams?.get("kiosk_id");

  const fetchUser = async () => {
    try {
      setIsLoading(true);
      const token = sessionData?.token;
      const payload = {
        token,
        userId: id
      }
      const response = await axios.post(`/api/viewUser`, payload);
      if (response?.data?.status !== 'error') {
        setUser(response?.data?.data || {});
        setCreations(response?.data?.data?.KioskCreations || [])
      }
    } catch (error: any) {
      console.error(error.message);
    } finally {
      setIsLoading(false);
    }

  };
  const fetchTxns = async () => {
    try {
      setIsLoading(true);
      const token = sessionData?.token;
      const phone = user?.phone;
      const payload = {
        phone,
        token,
        page: page2 + 1,
        limit: pageSize2,
        search: searchTerm2,
        id: id
      }
      const response = await axios.post(`/api/getTransactionsByUser`, payload);
      if (response?.data?.status !== 'error') {
        setTxns(response.data.txns || []);

        // setGames(response?.data?.creations || []);
        setTotalTxnCount(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) {
      fetchUser()

    }
  }, [sessionData?.token, sessionData?.admin_id, page, pageSize, searchTerm]);


  // useEffect(() => {
  //   if (sessionData?.token && sessionData?.admin_id && user?.phone) {
  //     fetchTxns()
  //   }
  // }, [sessionData?.token, sessionData?.admin_id, user?.phone, page2, pageSize2, searchTerm2]);

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

  };
  const handleSearch2 = (e: any) => {
    console.log(e.target.value)
    const value = e.target.value;
    setGlobalFilter2(value);

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

    return () => {
      clearTimeout(handler); // cancel previous timeout on new keystroke
    };
  }, [globalFilter]);
  useEffect(() => {
    const handler = setTimeout(() => {
      setSearchTerm2(globalFilter2); // update debounced value
    }, 500); // adjust delay here

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

  const remakeCreation = async () => {
    try {
      setIsLoading(true);
      const game = selectedRow?.Game ?? {};
      const phone = user?.phone ?? '';
      const token = sessionData?.token ?? '';

      const payload = {
        game,
        phone
      }
      const response = await axios.post('/api/remakeCreation', payload, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      if (response?.data?.status !== 'error') {
        setIsLoading(false)
        setOpenDialog(false);
        fetchUser();
      } else {
        setIsLoading(false)
      }

    } catch (error: any) {
      setIsLoading(false)

      console.log(error?.message)
    }
  }

  const columnHelper = createColumnHelper<EnTableType>();

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

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

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

      ),
    }),

    {
      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: creations,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });
  const handleVerify = async () => {
    try {
      setIsLoading(true)
      const token = sessionData?.token ?? '';
      const payload = {
        token,
        id: user?.id
      }
      const response = await axios.post('/api/verifyUser', payload, {
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      })
      if (response?.data?.status !== 'error') {
        setOpenVerifyModal(false)
        fetchUser();
      }
    } catch (error: any) {
      console.log(error?.message)
    }
    finally {
      setIsLoading(false)
    }
  }
  return (

    (
      <PageContainer title={`View User - ${isLoading ? 'Loading...' : user?.firstName + ' ' + user?.lastName}`} description="User details">
        <BaseCard title={`User - ${isLoading ? 'Loading...' : user?.firstName + ' ' + user?.lastName}`} >
          <Box
            display="flex"
            flexWrap="wrap"
            gap={2}
            mt={2}
            justifyContent="space-between"
          >
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                User ID
              </Typography>
              <Typography variant="h6">{isLoading ? 'Loading...' : user?.id}</Typography>
            </Box>
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Phone
              </Typography>
              <Typography variant="h6">{isLoading ? 'Loading...' : user?.phone}</Typography>
            </Box>
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Firstname
              </Typography>
              <Typography variant="h6">{isLoading ? 'Loading...' : user?.firstName}</Typography>
            </Box>
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Lastname
              </Typography>
              <Typography variant="h6">{isLoading ? 'Loading...' : user?.lastName}</Typography>
            </Box>
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Balance
              </Typography>
              <Typography variant="h6">${isLoading ? '...' : user?.balance}</Typography>
            </Box>
            <Box flex="1 1 45%">
              <Typography variant="body2" color="textSecondary">
                Status
              </Typography>
              <Chip label={isLoading ? 'Loading...' : user?.idenfy_verified == '1' ? 'Verified' : 'Unverified'} color={user?.idenfy_verified == '1' ? 'success' : 'warning'} />

            </Box>
            {user && user?.idenfy_verified !== '1' && (
              <Box flex="1 1 45%">
                <Typography variant="body2" color="textSecondary">
                  Verify
                </Typography>
                <Button

                  onClick={() => {

                    // setSelectedRow(row.original);
                    setOpenVerifyModal(true);
                  }}
                >
                  Verify
                </Button>
              </Box>
            )}
          </Box>
        </BaseCard>
        <br />
        {isLoading && <LinearProgress />}

        <BaseCard title="Creations" 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={Math.random()}>
                        {headerGroup.headers.map((header) => (
                          <TableCell key={Math.random()}>
                            <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={Math.random()}>
                        {row.getVisibleCells().map((cell) => (
                          <TableCell key={Math.random()}>
                            {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>
          <Dialog open={openVerifyModal} onClose={() => setOpenVerifyModal(false)} >
            <DialogTitle>Verify User</DialogTitle>
            <DialogContent>
              <Typography sx={{ mt: 1 }}>
                Are you sure you want to verify this user?
              </Typography>
            </DialogContent>
            <DialogActions>
              <Button onClick={() => setOpenVerifyModal(false)} disabled={isLoading}>Cancel</Button>
              <Button variant="contained" color="success" onClick={handleVerify} disabled={isLoading}>
                {/* Yes, Verify */}
                {isLoading ? 'Processing...' : 'Yes Verify'}
              </Button>
            </DialogActions>
          </Dialog>
          <Dialog open={openDialog} onClose={handleCloseDialog} fullWidth maxWidth="sm">
            <DialogTitle sx={{ m: 0, p: 2 }}>
              Creation 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">
                        Request Id
                      </Typography>
                      <Typography variant="h6">{selectedRow?.id}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Game
                      </Typography>
                      <Typography variant="h6">{selectedRow?.Game?.name}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Username
                      </Typography>
                      <Typography variant="h6">{selectedRow.gameuser}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Password
                      </Typography>
                      <Typography variant="h6">{selectedRow.gamepass}</Typography>
                    </Box>
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Remake
                      </Typography>
                      <Button
                        disabled={isLoading}
                        onClick={() => { remakeCreation() }}
                      >
                        <IconReload />&nbsp;{isLoading ? 'Processing...' : 'Remake'}
                      </Button>
                    </Box>

                  </Box>
                )}
              </Box>
            </DialogContent>
          </Dialog>
        </BaseCard>
        <br />

        <TableBasicReact userId={id} sessionData={sessionData} user={user} />

      </PageContainer>
    )
  );
}
