"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 [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 searchParams = useSearchParams();
  const kioskId = searchParams?.get("kioskId") ?? searchParams?.get("kiosk_id");

  const handleApprove = async () => {
    setIsLoading(true);

    try {
      const token = sessionData?.token ?? '';
      const id = selectedRow?.id;
      const txnType = selectedRow?.txnType;
      const payload = {
        id: id
      }
      let response = null;
      if (txnType == 'deposit') {
        response = await axios.post('https://kapi.logiclane.tech/api/kiosk/approveDeposit', payload, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
      }
      else {
        response = await axios.post('https://kapi.logiclane.tech/api/kiosk/approveRedeem', payload, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
      }
      if (response?.data?.status !== 'error') {
        setIsLoading(false);
        setSelectedRow('')
        setOpenDialog(false)
        fetchGames();
      }
    } catch (error: any) {
      setIsLoading(false);

      console.log('error', error?.message)
    }
  }
  const handleReject = async () => {
    setIsLoading(true);

    try {
      const token = sessionData?.token ?? '';
      const id = selectedRow?.id;
      const txnType = selectedRow?.txnType;

      const payload = {
        id: id
      }
      let response = null;
      if (txnType == 'deposit') {
        response = await axios.post('https://kapi.logiclane.tech/api/kiosk/rejectDeposit', payload, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
      }
      else {
        response = await axios.post('https://kapi.logiclane.tech/api/kiosk/rejectRedeem', payload, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });
      }
      if (response?.data?.status !== 'error') {
        setIsLoading(false);
        setSelectedRow('')
        setOpenDialog(false)
        fetchGames();
      }
    } catch (error: any) {
      setIsLoading(false);

      console.log('error', error?.message)
    }
  }
  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/getTransactions`, payload);
      if (response?.data?.status !== 'error') {
        setTxns(response.data.txns || []);

        // 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 getTimeAgo = (date: any, onlyTime: boolean = false) => {
    if (!date || !date.getTime() || isNaN(date.getTime())) return '--';
    const now = new Date();
    const diffMinutes = Math.round(
      (now.getTime() - date.getTime()) / (1000 * 60)
    );

    if (onlyTime) {
      if (diffMinutes < 60) {
        return `${diffMinutes} minutes ago`;
      } else {
        const diffHours = Math.floor(diffMinutes / 60);
        return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
      }
    }

    // Show all time differences
    if (diffMinutes < 60) {
      return `${diffMinutes} minutes ago`;
    }

    const diffHours = Math.floor(diffMinutes / 60);
    if (diffHours < 24) {
      return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
    }

    const diffDays = Math.floor(diffHours / 24);
    if (diffDays < 30) {
      return `${diffDays} day${diffDays > 1 ? "s" : ""} ago`;
    }

    const diffMonths = Math.floor(diffDays / 30);
    if (diffMonths < 12) {
      return `${diffMonths} month${diffMonths > 1 ? "s" : ""} ago`;
    }

    const diffYears = Math.floor(diffMonths / 12);
    return `${diffYears} year${diffYears > 1 ? "s" : ""} ago`;
  };

  const columnHelper = createColumnHelper<EnTableType>();

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

      ),
    }),
    columnHelper.accessor("created_at", {
      header: () => "Time",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > {getTimeAgo(new Date(row.original?.created_at))}</Typography>

      ),
    }),
    columnHelper.accessor("firstName", {
      header: () => "Customer",
      cell: ({ row }: any) => (
        <a href={`viewUser/${row?.original?.KioskUser?.id}?kioskId=${kioskId}`} style={{ textDecoration: 'none', color: '#5D87FF' }}>
          <Typography
            fontWeight={500}>
            {row.original?.KioskUser?.firstName + " " + row.original?.KioskUser?.lastName}
          </Typography>

        </a>
      ),
      // cell: ({ row }) => (
      //   <Typography
      //     // variant="h6"
      //     fontWeight={500}
      //   > {row.original?.KioskUser?.firstName + " " + row.original?.KioskUser?.lastName}</Typography>

      // ),
    }),
    columnHelper.accessor("txnType", {
      header: () => "Type",
      cell: ({ row }) => {
        const type = row?.original?.txnType || "";
        const formattedType = type.charAt(0).toUpperCase() + type.slice(1);

        // Define colors based on type
        let color = "#9e9e9e"; // default grey
        if (type === "deposit") color = "#4caf50"; // green
        else if (type === "cashout") color = "#f44336"; // red
        else if (type === "redeem") color = "#2196f3"; // blue
        else if (type === "cash") color = "orange"; // orange


        return (
          <Typography fontWeight={600} sx={{ color }}>
            {formattedType}
          </Typography>
        );
      },
    }),
    columnHelper.accessor("game", {
      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>
      ),
    }),
    columnHelper.accessor("amount", {
      header: () => "Amount",
      cell: ({ row }) => {
        const type = row?.original?.txnType || "";
        const amount = row?.original?.amount || 0;

        // Define color based on txnType
        let color = "#9e9e9e"; // default grey
        if (type === "deposit") color = "#4caf50"; // green
        else if (type === "cashout") color = "#f44336"; // red
        else if (type === "redeem") color = "#2196f3"; // blue
        else if (type === "cash") color = "orange"; // orange


        return (
          <Typography fontWeight={600} sx={{ color }}>
            ${amount}
          </Typography>
        );
      },
    }),
    columnHelper.accessor("status", {
      header: () => "Status",
      cell: ({ row }) => (
        <Typography
          // variant="h6"
          fontWeight={500}
        > <Chip label={row?.original?.status == '1' ? 'Completed' : (row?.original?.status == '2' ? 'Rejected' : 'Pending')} color={row?.original?.status == '1' ? 'success' : (row?.original?.status == '2' ? 'error' : 'warning')} /></Typography>
      ),
    }),
    {
      accessorKey: 'id',
      header: 'View',
      cell: ({ row }: any) => (
        <Button
          onClick={() => {
            // console.log(row.original)
            // setSelectedRow(row.original);
            // setOpenDialog(true);
            router.push(`/transaction/${row.original.id}?kiosk_id=${kioskId}&type=${row.original.txnType}`)
          }}
        >
          View
        </Button>
      ),

    }
  ];

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

  return (

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

            <BaseCard title="Transactions" 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, pr: 6 }}>
              {selectedRow?.txnType
                ? selectedRow.txnType.charAt(0).toUpperCase() +
                selectedRow.txnType.slice(1)
                : ""}{" "}
              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>
              {selectedRow && (
                <Box mt={1}>
                  <Box
                    display="flex"
                    flexWrap="wrap"
                    gap={3}
                    justifyContent="space-between"
                  >
                    {/* Request ID */}
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Request ID
                      </Typography>
                      <Typography variant="h6">{selectedRow?.id}</Typography>
                    </Box>

                    {/* Amount */}
                    <Box flex="1 1 45%">
                      <Typography variant="body2" color="textSecondary">
                        Amount
                      </Typography>
                      <Typography variant="h6">${selectedRow?.amount}</Typography>
                    </Box>
                    {/* Amount */}
                    {selectedRow?.txnType === "cashout" && selectedRow?.cassetteBreakdown.length > 0 && (
                      <Box flex="1 1 45%">
                        <Typography variant="body2" color="textSecondary">
                          Notes
                        </Typography>

                        {selectedRow.cassetteBreakdown.map((cb: any, index: any) => (
                          <Typography key={index} variant="h6">
                            {cb.label}
                          </Typography>
                        ))}
                      </Box>
                    )}
                    {selectedRow?.txnType == "cash" &&
                      <Box flex="1 1 45%">
                        <Typography variant="body2" color="textSecondary">
                          Denomination (NV200)
                        </Typography>
                        <Typography variant="h6">${parseInt(selectedRow?.denomination)}</Typography>
                      </Box>
                    }
                    {/* Game and Username (only if not cashout) */}
                    {selectedRow?.txnType !== "cashout" && selectedRow?.txnType !== "cash" && (
                      <>
                        <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>

                  {/* Action Buttons (Approve / Reject) */}
                  {selectedRow?.status === "0" && (
                    <Box mt={4} display="flex" justifyContent="flex-end">
                      <Box display="flex" gap={2}>
                        <Button
                          variant="contained"
                          color="error"
                          onClick={handleReject}
                          disabled={isLoading}
                        >
                          {isLoading ? "Processing..." : "Reject"}
                        </Button>

                        <Button
                          variant="contained"
                          color="success"
                          onClick={handleApprove}
                          disabled={isLoading}
                        >
                          {isLoading ? "Processing..." : "Approve"}
                        </Button>
                      </Box>
                    </Box>
                  )}
                  <Box flex="1 1 45%" sx={{ mt: 2 }}>
                    <Typography variant="body2" color="textSecondary">
                      Status
                    </Typography>
                    <Typography variant="h6">
                      <Chip label={selectedRow?.status == '1' ? 'Completed' : (selectedRow?.status == '2' ? 'Rejected' : 'Pending')} color={selectedRow?.status == '1' ? 'success' : (selectedRow?.status == '2' ? 'error' : 'warning')} />
                    </Typography>
                  </Box>
                </Box>
              )}
            </DialogContent>
          </Dialog>
          
        </Grid>
      </Box>
    </PageContainer >)
  );
}
