"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 moment from 'moment-timezone';

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 [totalPages, setTotalPages] = useState(0)

  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
      }
      let url = sessionData?.role == 'Super' ? `/api/getTransactions` : `/api/getTransactionsByUser`
      const response = await axios.post(url, payload);
      if (response?.data?.status !== 'error') {
        setTxns(response.data.transactions || []);
        setTotalCount(response.data.total || 0);
        setTotalPages(response.data.totalPages || 0);
      }
    } 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 SERVER_TZ = "UTC";
  // const SERVER_TZ = "Asia/Kolkata";

  const getTimeAgo = (value: any) => {
    if (!value) return "--";

    let input;

    if (value instanceof Date) {
      // 🔥 CRITICAL FIX:
      // Undo browser timezone conversion and reattach server TZ
      const wallClock = moment(value).format("YYYY-MM-DD HH:mm:ss");

      input = moment.tz(
        wallClock,
        "YYYY-MM-DD HH:mm:ss",
        SERVER_TZ
      );
    } else {
      // string from API → treat as server time
      input = moment.tz(
        value,
        "YYYY-MM-DD HH:mm:ss",
        SERVER_TZ
      );
    }

    const now = moment.tz(SERVER_TZ);

    const diffMinutes = now.diff(input, "minutes");
    const diffHours = now.diff(input, "hours");
    const diffDays = now.diff(input, "days");

    if (diffMinutes < 1) return "just now";
    if (diffMinutes < 60) return `${diffMinutes} minutes ago`;
    if (diffHours < 24) return `${diffHours} hours ago`;
    return `${diffDays} days ago`;
  };
  // const getTimeAgo = (value: any) => {
  //   if (!value) return "--";

  //   let input;

  //   if (value instanceof Date) {
  //     // value is already an absolute instant → just convert timezone
  //     input = moment(value).tz(SERVER_TZ);
  //   } else {
  //     // value is a string without timezone → parse AS server time
  //     input = moment.tz(
  //       value,
  //       "YYYY-MM-DD HH:mm:ss",
  //       SERVER_TZ
  //     );
  //   }

  //   const now = moment.tz(SERVER_TZ);

  //   const diffMinutes = now.diff(input, "minutes");
  //   const diffHours = now.diff(input, "hours");
  //   const diffDays = now.diff(input, "days");

  //   if (diffMinutes < 1) return "just now";
  //   if (diffMinutes < 60) return `${diffMinutes} minutes ago`;
  //   if (diffHours < 24) return `${diffHours} hours ago`;
  //   return `${diffDays} days ago`;
  // };

  // const getTimeAgo = (value: any, onlyTime: boolean = false) => {
  //   if (!value) return "--";

  //   // Treat incoming time as LOCAL time (DO NOT force UTC)
  //   let input = moment(value, "YYYY-MM-DD HH:mm:ss", true);

  //   if (!input.isValid()) {
  //     input = moment(value);
  //     if (!input.isValid()) return "--";
  //   }

  //   // Compare against local "now"
  //   const now = moment();

  //   const diffMinutes = now.diff(input, "minutes");
  //   const diffHours = now.diff(input, "hours");
  //   const diffDays = now.diff(input, "days");

  //   if (diffMinutes < 1) return "just now";

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

  //   if (diffMinutes < 60) return `${diffMinutes} minutes ago`;
  //   if (diffHours < 24) return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
  //   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 getTimeAgo = (value: any, onlyTime: boolean = false) => {
  //   console.log("Raw input:", value);
  //   console.log("Server thinks txn time is:", moment(value).format());
  //   console.log("Parsed as UTC:", moment.utc(value).format());
  //   if (!value) return "--";

  //   // Force DB format into UTC explicitly
  //   let input = moment.utc(value, "YYYY-MM-DD HH:mm:ss", true);

  //   if (!input.isValid()) {
  //     // fallback for JS Date or ISO string
  //     const fallback = moment.utc(value);
  //     if (!fallback.isValid()) return "--";
  //     input = fallback;
  //   }

  //   const now = moment.utc();

  //   console.log("Parsed (UTC):", input.toISOString());
  //   console.log("Now (UTC):", now.toISOString());

  //   const diffMinutes = now.diff(input, "minutes");
  //   const diffHours = now.diff(input, "hours");
  //   const diffDays = now.diff(input, "days");

  //   console.log("Diff (minutes):", diffMinutes);
  //   console.log("Diff (hours):", diffHours);
  //   console.log("Diff (days):", diffDays);

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

  //   if (diffMinutes < 60) {
  //     return `${diffMinutes} minutes ago`;
  //   }

  //   if (diffHours < 24) {
  //     return `${diffHours} hour${diffHours > 1 ? "s" : ""} ago`;
  //   }

  //   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<any>();

  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 fontWeight={500}>
          {getTimeAgo(row.original?.created_at)}
        </Typography>
      ),
    }),
    columnHelper.accessor((row: any) => row?.admin?.first, {
      id: "employee",
      header: () => "Employee",
      cell: ({ row }: any) => (
        // <a href={`viewUser/${row?.original?.admin?.id}?kioskId=${kioskId}`} style={{ textDecoration: 'none', color: '#5D87FF' }}>
        <Typography
          fontWeight={500}>
          {row.original?.admin?.first + " " + row.original?.admin?.last}
        </Typography>

        // </a>
      ),

    }),
    columnHelper.accessor((row: any) => row?.method, {
      id: "method",
      header: () => "Method",
      cell: ({ row }: any) => (

        <Typography
          fontWeight={500}>
          {row.original?.method
            ? row.original.method.charAt(0).toUpperCase() + row.original.method.slice(1)
            : ''}
        </Typography>

      ),
    }),
    columnHelper.accessor("type", {
      header: () => "Type",
      cell: ({ row }) => {
        const type = row?.original?.type || "";
        const amount = row?.original?.amount || 0;
        // console.log(type)
        // Define color based on txnType
        let color = "#9e9e9e"; // default grey
        if (type === "1") color = "#4caf50"; // green
        else if (type === "2") color = "#f44336"; // red
        else if (type === "redeem") color = "#2196f3"; // blue
        else if (type === "cash") color = "orange"; // orange


        return (
          <Typography fontWeight={600} sx={{ color }}>
            {type == "1" ? 'Deposit' : 'Withdraw'}
          </Typography>
        );
      },
    }),
    columnHelper.accessor("amount", {
      header: () => "Amount",
      cell: ({ row }) => {
        const type = row?.original?.type || "";
        const amount = row?.original?.amount || 0;
        // console.log(type)
        // Define color based on txnType
        let color = "#9e9e9e"; // default grey
        if (type === "1") color = "#4caf50"; // green
        else if (type === "2") 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}`)
          }}
        >
          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={totalPages}
                      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 >)
  );
}
