"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,
  Snackbar
} 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 CustomTextField from "@/app/components/forms/theme-elements/CustomTextField";

type SnackbarState = {
  open: boolean;
  severity: 'success' | 'error' | 'warning' | 'info';
  message: string;
};

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 [games, setGames] = 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 [snackbar, setSnackbar] = useState<SnackbarState>({ open: false, severity: 'success', message: '' });

  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 [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [showApproveDialog, setShowApproveDialog] = useState(false)
  const searchParams = useSearchParams();

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


  // Handle approve confirmation dialog open
  const handleApproveClick = () => {
    setShowApproveDialog(true);
  };

  // Cancel approve and return to previous view
  const handleCancelApprove = () => {
    setShowApproveDialog(false);
    setUsername("");
    setPassword("");
  };

  // Handle final save
  const handleSaveApprove = async () => {
    setIsLoading(true);
    try {
      // ✅ Replace this with your actual approve function
      // await new Promise((resolve) => setTimeout(resolve, 1000));
      const token = sessionData?.token ?? '';
      console.log("Approved:", { id: selectedRow.id, username, password });
      const payload = {
        kioskId: kioskId,
        id: selectedRow?.id,
        username: username,
        password: password
      }
      const response = await axios.post('https://kapi.logiclane.tech/api/kiosk/approveCreation', payload, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })
      if (response?.data?.status !== 'error') {
        setIsLoading(false);
        setShowApproveDialog(false);
        handleCloseDialog();
        setUsername("");
        setPassword("");
        setSnackbar({ open: true, severity: 'success', message: 'Account created successfully' });
        await fetchGames()

      } else {
        setIsLoading(false);
        console.error(response?.data?.message);
        setSnackbar({ open: true, severity: 'warning', message: 'Unexpected response from server' });
        await fetchGames()

      }

    } catch (err) {
      console.error(err);
      setIsLoading(false);
    }
  };

  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/getCreationsByGameRequested`, payload);
      if (response?.data?.status !== 'error') {
        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]);


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

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

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

  };

  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 }) => (
      //   <Typography
      //     // variant="h6"
      //     fontWeight={500}
      //   > {row.original.phone}</Typography>

      // ),
      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>
      ),
    }),
    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={() => {
            setSelectedRow(row.original);
            setOpenDialog(true);
          }}
        >
          View
        </Button>
      ),

    },

  ];

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

  return (

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

            <BaseCard title={`Creations - ${game?.name ?? 'Loading...'}`} 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>
                  <Snackbar open={snackbar.open} autoHideDuration={3000} onClose={() => setSnackbar(s => ({ ...s, open: false }))}>
                    <Alert severity={snackbar.severity} onClose={() => setSnackbar(s => ({ ...s, open: false }))}>
                      {snackbar.message}
                    </Alert>
                  </Snackbar>
                </Box>

              </Grid>

            </BaseCard>
          </Grid>
          {/* Main Dialog */}
          <Dialog open={openDialog && !showApproveDialog} 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"
                    alignItems="center"
                  >
                    <Box flex="1 1 30%">
                      <Typography variant="body2" color="textSecondary">
                        Requested
                      </Typography>
                      <Typography variant="h6">{getTimeAgo(new Date(selectedRow.created_at))}</Typography>
                    </Box>
                    <Box flex="1 1 30%">
                      <Typography variant="body2" color="textSecondary">
                        Customer
                      </Typography>
                      <a href={`viewUser/${selectedRow?.KioskUser?.id}?kioskId=${kioskId}`} style={{ textDecoration: 'none', color: '#5D87FF' }}>
                        <Typography
                          fontWeight={500}>
                          {selectedRow?.KioskUser?.firstName + " " + selectedRow?.KioskUser?.lastName}
                        </Typography>
                      </a>
                    </Box>
                    <Box flex="1 1 30%">
                      <Typography variant="body2" color="textSecondary">
                        Game
                      </Typography>
                      <Typography variant="h6">{game?.name}</Typography>
                    </Box>

                    <Box flex="1 1 100%" display="flex" justifyContent="flex-end" gap={2}>
                      <Button
                        onClick={handleApproveClick}
                        disabled={isLoading}
                        variant="contained"
                        color="success"
                      >
                        {isLoading ? "Processing..." : "Approve"}
                      </Button>

                      <Button
                        color="error"
                        variant="contained"
                        disabled={isLoading}
                        onClick={() => console.log("Rejected:", selectedRow.id)}
                      >
                        Reject
                      </Button>
                    </Box>
                  </Box>
                )}
              </Box>
            </DialogContent>
          </Dialog>

          {/* Approve Confirmation Dialog */}
          <Dialog open={showApproveDialog} onClose={handleCancelApprove} fullWidth maxWidth="xs">
            <DialogTitle sx={{ m: 0, p: 2 }}>
              Approve Creation
              <IconButton
                aria-label="close"
                onClick={handleCancelApprove}
                sx={{
                  position: "absolute",
                  right: 8,
                  top: 8,
                  color: (theme) => theme.palette.grey[500],
                }}
              >
                <CloseIcon />
              </IconButton>
            </DialogTitle>

            <DialogContent dividers>
              <Box display="flex" flexDirection="column" gap={2} mt={1}>
                <TextField
                  label="Username"
                  placeholder="Enter username"
                  fullWidth
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                />

                <TextField
                  label="Password"
                  placeholder="Enter password"
                  type="text"
                  fullWidth
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                />

                <Box display="flex" justifyContent="flex-end" gap={2} mt={2}>
                  <Button
                    variant="outlined"
                    onClick={handleCancelApprove}
                    disabled={isLoading}
                  >
                    Cancel
                  </Button>

                  <Button
                    variant="contained"
                    color="success"
                    onClick={handleSaveApprove}
                    disabled={isLoading || !username || !password}
                  >
                    {isLoading ? "Saving..." : "Save"}
                  </Button>
                </Box>
              </Box>
            </DialogContent>
          </Dialog>
        </Grid>

      </Box>
    </PageContainer>)
  );
}
