import React, { useEffect, useMemo, useState} from "react";
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  CircularProgress,
  Grid,
  Box,
  Button,
  Typography,
  TextField,
  MenuItem,
  InputAdornment,
  Card,
  Divider
} from "@mui/material";

import { Tooltip as MuiTooltip } from '@mui/material';
import { useNotifier } from "../../../Core/Notifier";
import { useStyles } from "../../../theme/appStyles";
import { useNavigate, useParams } from "react-router-dom";
import { CiSearch } from "react-icons/ci";
import DeleteOutlineSharpIcon from "@mui/icons-material/DeleteOutlineSharp";
import EditSharpIcon from "@mui/icons-material/EditSharp";
import Pagination from "../../../Components/Pagination";
import axios from "axios";
import CheckCircleIcon from '@mui/icons-material/CheckCircle';
import { useLocation } from "react-router-dom";
import InfoIcon from '@mui/icons-material/Info';  

interface Deposit {
  id: number;
  amount: string;
  user_id: number;
  created_at: string;
  date: string;
  is_approved: boolean; 
  remarks: string;
}

const Index = () => {
  const classes = useStyles();
  const navigate = useNavigate();
  const { projectId } = useParams();
   const [deposit, setDeposit] = useState<Deposit[]>([]); 
  const { showErrorMessage, showMessage } = useNotifier();
  const API_URL = process.env.REACT_APP_API_URL;
  const [searchQuery, setSearchQuery] = useState(""); 
  const [page, setPage] = useState(0);
  const [rowsPerPage, setRowsPerPage] = useState(50);
  // const { state } = useLocation();
  // const person = state?.userId; 
const personData = sessionStorage.getItem("personData");
const person = personData ? JSON.parse(personData) : null;
  
  const [tooltipOpen, setTooltipOpen] = React.useState<Record<number, boolean>>({});


   const personDeposits = deposit.filter((d) => d.user_id === person?.id); 

  const personTotalDeposit = personDeposits?.filter((d) => d.is_approved)
    .reduce((acc, curr) => acc + Number(curr.amount), 0);

     const fetchDeposit = async () => {
      try {
        const response = await axios.get(`${API_URL}/view-deposit/${projectId}`);
        setDeposit(response.data); // Set the fetched data to state
        // console.log(response.data);
      } catch (error) {
        console.error("Failed to load expenses", error);
      }
    };


    useEffect(() => {
      fetchDeposit();
    }, [API_URL]);

 
  const handleChangePage = (event: unknown, newPage: number) => {
    setPage(newPage);
  };
  
  

const handleTooltipOpen = (id: number) => {
  if (window.innerWidth > 768) {
    setTooltipOpen((prev) => ({ ...prev, [id]: true })); // Open tooltip on hover for desktop
  }
};

const handleTooltipClose = (id: number) => {
  if (window.innerWidth > 768) {
    setTooltipOpen((prev) => ({ ...prev, [id]: false })); // Close tooltip on hover leave for desktop
  }
};

const handleMobileTooltipToggle = (id: number) => {
  if (window.innerWidth <= 768) {
    setTooltipOpen((prev) => ({
      ...prev,
      [id]: !prev[id], // Toggle the open state for the specific tooltip
    })); // Toggle open/close on tap for mobile
  }
};


  return (
    <Card className={classes.card}>
      <Grid
        container
        justifyContent={"space-between"}
        spacing={5}
        sx={{ borderBottom: 2, padding: 2 }}
        className={classes.titleGrid}
      >
        
        <Grid item lg={12} md={12} sm={12} xs={12} pt={2} alignContent={"center"}>
         <Box
  sx={{
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "center",
    p: 3,
    borderRadius: 2,
    boxShadow: 3,
    backgroundColor: "#f9f9f9",
   
  }}
>
  <Typography
    variant="h5"
    sx={{ fontWeight: "600", color: "#333", mb: 1 }}
  >
    Deposits {person ? `– ${person.driverFirstName} ${person.driverLastName}` : ""}
  </Typography>

  <Divider sx={{ width: "80%", mb: 2 }} />

  <Typography
    variant="h3"
    sx={{
      fontWeight: "bold",
      color: "#4CAF50",
      letterSpacing: "1px",
    }}
  >
    ${personTotalDeposit.toFixed(2)}
  </Typography>

  <Typography
    variant="subtitle2"
    sx={{ color: "#888", mt: 1 }}
  >
    Total Deposit Amount
  </Typography>
</Box>

        </Grid>

        
        <Grid
          item
          lg={8}
          md={8}
          sm={8}
          xs={8}
          sx={{ display: "flex", justifyContent: "flex-end" }}
        >
          <Grid
            container
            spacing={1}
            justifyContent="flex-end"
            sx={{ display: "flex" }}
          >
             
            {/* <Grid item>
              <TextField
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <CiSearch className={classes.searchWidgetIcon} />
                    </InputAdornment>
                  ),
                  classes: {
                    root: classes.formControlList,
                  },
                }}
                fullWidth
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Expense Name .."
                sx={{ width: "100%" }}
                size="small"
              />
            </Grid> */}
           
            {/* <Grid item>
              <Button
                variant="contained"
                className={classes.addButton}
                onClick={handleAddExpenseCategoryClick}
              >
                Add Expense Category
              </Button>

            </Grid> */}

         


            
          </Grid>
        </Grid>
      </Grid>

     

      <Grid item lg={12} md={12} sm={12} xs={12}>
        <Card sx={{ padding: 3 }}>
        <TableContainer>
        <Table className={classes.table}>
        <TableHead className={classes.tableHeaderRow}>
              <TableRow className={classes.tableRowHover}>
             <TableCell className={classes.tablheader}>Date</TableCell>
                                 <TableCell className={classes.tablheader}>Amount</TableCell>
                                 <TableCell className={classes.tablheader}>Status</TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
                {personDeposits.length === 0 ? (
                                  <TableRow>
                                    <TableCell colSpan={3} align="center" className={classes.tablCell}>
                                      No Data Available
                                    </TableCell>
                                  </TableRow>
                                ) : (
                                  personDeposits
                                  .sort((a, b) => {
                                    const dateA = new Date(a.date).getTime();
                                    const dateB = new Date(b.date).getTime();
                                
                                    // First sort by date (descending)
                                    if (dateB !== dateA) {
                                      return dateB - dateA;
                                    }
                                
                                    // If the dates are the same, sort by ID (ascending)
                                    return b.id - a.id;
                                  }).
                                  map((depositItem, idx) => (
                                    <TableRow key={idx}>
                                      <TableCell scope="row" className={classes.tablCell}>
                                        {new Date(depositItem.date).toLocaleDateString()}
                                      </TableCell>
                                      <TableCell scope="row" className={classes.tablCell}>
                                        ${depositItem.amount}
                                        {depositItem.remarks ? (
                      <MuiTooltip
                        title={depositItem.remarks}
                        arrow
                        open={tooltipOpen[depositItem.id] || false}
                        onOpen={() => handleTooltipOpen(depositItem.id)}
                        onClose={() => handleTooltipClose(depositItem.id)}
                        disableInteractive
                      >
                        <InfoIcon
                          sx={{
                            color: '#2196F3',
                            cursor: 'pointer',
                            fontSize: '1.1rem',
                            marginLeft: '8px',
                            verticalAlign: 'middle',
                          }} 
                          onClick={()=>handleMobileTooltipToggle(depositItem.id)} // Mobile: tap to toggle
                          onTouchStart={()=>handleMobileTooltipToggle(depositItem.id)}  
                        />
                      </MuiTooltip>
                    ) : null}
                                      </TableCell>
                                      <TableCell scope="row" className={classes.tablCell}>
                                        {depositItem.is_approved ? (
                                          <CheckCircleIcon sx={{ color: 'green', backgroundColor: '#d4edda', borderRadius: '50%' }} />
                                        ) : (
                                          <CheckCircleIcon sx={{ color: 'red', backgroundColor: '#f8d7da', borderRadius: '50%' }} />
                                        )}
                                      </TableCell>
                                    </TableRow>
                                  ))
                                )}
            </TableBody>
          </Table>

          <Grid
            spacing={5}
            p={"18px"}
            py={4}
            justifyContent={"end"}
            container
            textAlign={"center"}
            alignContent={"center"}
            alignItems={"center"}
          >
            <Grid
              sx={{
                textAlign: "end",
                justifyContent: "flex-end",
                alignItems: "flex-end",
              }}
            >
             
         <Pagination
        count={Math.ceil(personDeposits.length / rowsPerPage)}
        page={page}
        rowsPerPage={rowsPerPage}
        onPageChange={handleChangePage}
      />
          </Grid>
        </Grid>
        
    </TableContainer>
           
        
        </Card>
      </Grid>

    </Card>
       

  );
};

export default Index;
