"use client";
import * as React from "react";
import {
  TableContainer,
  Table,
  TableRow,
  TableCell,
  TableBody,
  Avatar,
  Typography,
  TableHead,
  Chip,
  Box,
  AvatarGroup,
  Grid,
  Button,
  TextField,
  Pagination,
  LinearProgress,
} from "@mui/material";
import { Stack } from "@mui/system";

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";
import axios from "axios";

const basics = basicsTableData;

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("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
  //       color="primary"
  //       variant="contained"
  //       onClick={() => {
  //         // setSelectedRow(row.original);
  //         // setOpenDialog(true);
  //       }}
  //     >
  //       View
  //     </Button>
  //   )
  // }
];

const TableBasicReact = ({ userId, sessionData, user }: any) => {
  // const [totalCount, setTotalCount] = React.useState<number>(0);
  // console.log(totalCount)
  const [isLoading, setIsLoading] = React.useState<Boolean>(false);
  const [searchTerm, setSearchTerm] = React.useState<any>('');
  const [globalFilter, setGlobalFilter] = React.useState<any>('');
  const [txns, setTxns] = React.useState<any>([])
  const [totalCount, setTotalCount] = React.useState<any>([])
  const fetchTxns = async () => {
    try {
      setIsLoading(true);
      const token = sessionData?.token;
      const phone = user?.phone;
      const payload = {
        phone,
        token,
        page: page + 1,
        limit: pageSize,
        search: searchTerm,
        id: userId
      }
      const response = await axios.post(`/api/getTransactionsByUser`, 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 [page, setPage] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(10);
  // const [data, _setData] = React.useState<any>(() => [...basics]);

  React.useEffect(() => {
    if (sessionData?.token && user?.phone) {
      fetchTxns()
    }
  }, [sessionData?.token, user?.phone, page, pageSize, searchTerm])

  // React.useEffect(() => {
  //   fetchTxns()
  // }, [sessionData?.token,user?.phone])
  React.useEffect(() => {
    const handler = setTimeout(() => {
      setSearchTerm(globalFilter); // update debounced value
    }, 500); // adjust delay here

    return () => {
      clearTimeout(handler); // cancel previous timeout on new keystroke
    };
  }, [globalFilter]);
  const handleSearch = (e: any) => {
    console.log(e.target.value)
    const value = e.target.value;
    setGlobalFilter(value);
  };

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


  return (
    (
      <>
        {isLoading && <LinearProgress />}

        <BaseCard title="Transactions" searchBar={
          <TextField
            fullWidth
            variant="outlined"
            placeholder="Search..."
            value={globalFilter}
            onChange={handleSearch}
          />
        }>
          <Grid container spacing={3}>
            <Grid size={12}>
              <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>
          </Grid>
        </BaseCard>
      </>
    )
  );
};

export default TableBasicReact;


