import React from 'react';
import { useState } from 'react';
import TitleCard from 'pages/titleCard';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { useTheme } from '@mui/material/styles';
import { Outlet, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import { DashboardOutlined } from '@ant-design/icons';
import { HiHandThumbDown, HiHandThumbUp } from 'react-icons/hi2';
import LoadingIcons from 'react-loading-icons';
import { useQuery } from '@tanstack/react-query';
import { fetchinvoiceinsight, fetchdeliverylist } from 'pages/api/api';
import VisibilityIcon from '@mui/icons-material/Visibility';
import {
  Grid,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  Tabs,
  Tab,
  Typography,
  Box,
  IconButton,
  Tooltip,
  Stack
} from '@mui/material';
import Loader from 'components/Loader';
import MainCard from 'components/MainCard';
import { Empty } from 'antd';
import DateFilterDialog from 'components/DateFilterDialog';
import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton';

const columns = [
  { id: 'sno', label: 'sno' },
  { id: 'client', label: 'client' },
  { id: 'invoiceid', label: 'Invoice Id' },

  {
    id: 'invoice date',
    label: 'invoice date',
    align: 'left'
    // format: (value) => value.toLocaleString("en-US"),
  },
  {
    id: 'due date',
    label: 'due date',
    align: 'left'
    // format: (value) => value.toLocaleString("en-US"),
  },
  {
    id: 'itemcount',
    label: 'Count',
    align: 'left'
    // format: (value) => typeof value === "number" && value.toFixed(2),
  },

  { id: 'amount', label: 'amount', align: 'right' },
  { id: 'action', label: 'action', align: 'center' }
];

// table data

function CustomTabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} aria-labelledby={`simple-tab-${index}`} {...other}>
      {value === index && (
        <Box sx={{ p: 3 }}>
          <Typography>{children}</Typography>
        </Box>
      )}
    </div>
  );
}

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`
  };
}
function formatNumberToRupees(value) {
  return new Intl.NumberFormat('en-IN', {
    style: 'currency',
    currency: 'INR',
    minimumFractionDigits: 2
  }).format(value);
}
const Invoice = () => {
  const theme = useTheme();
  const navigate = useNavigate();
  const [page, setPage] = React.useState(0);
  const [rowsPerPage, setRowsPerPage] = React.useState(10);
  const [value, setValue] = React.useState(0);
  const [billStatus, setBillStatus] = useState(0);
  let [isloader, setIsLoader] = useState(false);
  const [open, setOpen] = useState(false);

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

  const handleChangeRowsPerPage = (event) => {
    setRowsPerPage(+event?.target?.value);
    setPage(0);
  };

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  /* ============================================= || fetchinvoiceinsight| ============================================= */
  const {
    data: insightdata,
    isLoading: isInsightLoading,
    isError: isInsightError,
    error: insightError
  } = useQuery({
    queryKey: ['invoiceInsight'], // Meaningful query key
    queryFn: fetchinvoiceinsight,
    refetchInterval: 300000 // Auto-fetch every 5 minutes
  });
  /* ============================================= || fetchdeliverylist| ============================================= */

  const {
    data: deliveryList,
    isLoading: isDeliveryLoading,
    isError: isDeliveryError,
    error: deliveryError
  } = useQuery({
    queryKey: [billStatus], // Include billStatus in query key
    queryFn: fetchdeliverylist,
    refetchInterval: 300000 // Auto-fetch every 5 minutes
  });
  const isLoading = isInsightLoading || isDeliveryLoading;
  const isError = isInsightError || isDeliveryError;
  const errorMessage = insightError?.message || deliveryError?.message;

  if (isError) {
    return errorMessage;
  }

  return (
    <>
      {(isloader || isLoading) && <Loader />}
      {/* ============================================= || TitleCard || ============================================= */}
      <TitleCard title="Invoice" />

      {/* ============================================= || Hover Social Card  || ============================================= */}
      <Grid container spacing={3}>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: 'pointer' }}
          onClick={() => {
            setValue(0);
            setBillStatus(0);
          }}
        >
          <HoverSocialCard
            primary="All"
            secondary={insightdata?.totalcount}
            iconPrimary={DashboardOutlined}
            color={theme.palette.primary.main}
          />
        </Grid>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: 'pointer' }}
          onClick={() => {
            setValue(1);
            setBillStatus(1);
          }}
        >
          <HoverSocialCard
            primary="0pen"
            secondary={insightdata?.pendingcount}
            iconPrimary={LoadingIcons.ThreeDots}
            color={theme.palette.error.main}
          />
        </Grid>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: 'pointer' }}
          onClick={() => {
            setValue(2);
            setBillStatus(2);
          }}
        >
          <HoverSocialCard
            primary="Overdue"
            secondary={insightdata?.overduecount}
            iconPrimary={HiHandThumbDown}
            color={theme.palette.warning.main}
          />
        </Grid>
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: 'pointer' }}
          onClick={() => {
            setValue(3);
            setBillStatus(3);
          }}
        >
          <HoverSocialCard
            primary="Paid"
            secondary={insightdata?.paidcount}
            color={theme.palette.success.main}
            iconPrimary={HiHandThumbUp}
          />
        </Grid>
      </Grid>
      {/* ============================================= || Invoice Table || ============================================= */}
      <Stack sx={{ border: '1px solid', borderColor: 'bg.main', p: 3, mt: 3 }}>
        <Grid container sx={{}}>
          <Grid item xs={9} sx={{}}>
            <Tabs value={value} onChange={handleChange} aria-label="basic tabs example" sx={{ mt: -1, mb: -2 }}>
              <Tab
                label="All"
                {...a11yProps(0)}
                onClick={() => {
                  setValue(0);
                  setBillStatus(0);
                }}
              />
              <Tab
                label="Open"
                {...a11yProps(1)}
                onClick={() => {
                  setValue(1);
                  setBillStatus(1);
                }}
              />
              <Tab
                label="Overdue"
                {...a11yProps(2)}
                onClick={() => {
                  setValue(2);
                  setBillStatus(2);
                }}
              />
              <Tab
                label="Paid"
                {...a11yProps(3)}
                onClick={() => {
                  setValue(3);
                  setBillStatus(3);
                }}
              />
            </Tabs>
          </Grid>
        </Grid>
      </Stack>
      <MainCard content={false}>
        <CustomTabPanel value={value} index={value}>
          <TableContainer
            sx={{
              // maxHeight: 430,
              // maxHeight: '55vh',
              mt: -3,
              '&::-webkit-scrollbar': {
                width: '4px', // Width of vertical scrollbar
                height: '4px' // Height of horizontal scrollbar
              },
              '&::-webkit-scrollbar-thumb': {
                backgroundColor: '#65387A' // Color of the scrollbar thumb
              }
            }}
          >
            <Table stickyHeader aria-label="sticky table" sx={{}}>
              <TableHead
                sx={{
                  '& th': {
                    borderTop: `1px solid ${theme.palette.divider}`,
                    borderBottom: `2px solid ${theme.palette.divider} !important`
                  }
                }}
              >
                <TableRow>
                  {columns.map((column) => (
                    <TableCell
                      sx={{
                        minWidth: column.minWidth,
                        position: 'sticky !important'
                      }}
                      key={column.id}
                      align={column.align}
                    >
                      {column.label}
                    </TableCell>
                  ))}
                </TableRow>
              </TableHead>
              <TableBody>
                {isDeliveryLoading && <OrdersTableSkeleton col={3} />}
                {deliveryList?.length == 0 ? (
                  <TableRow>
                    <TableCell colSpan={8}>
                      <Empty />
                    </TableCell>
                  </TableRow>
                ) : (
                  deliveryList?.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((item, index) => (
                    <TableRow key={index}>
                      <TableCell>{page * rowsPerPage + index + 1}</TableCell>
                      <TableCell>
                        <Typography>{item.tenantname} </Typography>

                        <Typography variant="caption" color={'secondary'}>
                          {item.contactperson}{' '}
                        </Typography>
                      </TableCell>
                      <TableCell>
                        <Typography variant="caption">{item.invoiceno} </Typography>
                      </TableCell>
                      <TableCell>
                        <stack direction={'column'}>
                          <Typography variant="caption">{dayjs(item.transactiondate).format('DD-MM-YYYY')}</Typography>
                          <br />
                          <Typography variant="caption">{dayjs(item.transactiondate).utc().format('hh:mm a')}</Typography>
                        </stack>
                      </TableCell>
                      <TableCell>
                        <stack direction={'column'}>
                          <Typography variant="caption">{dayjs(item.duedate).format('DD-MM-YYYY')}</Typography>
                          <br />
                          <Typography variant="caption">{dayjs(item.duedate).utc().format('hh:mm a')}</Typography>
                        </stack>
                      </TableCell>

                      <TableCell>
                        {' '}
                        <Typography variant="caption">{item.itemcount} </Typography>
                      </TableCell>
                      <TableCell align="right">
                        <Typography variant="caption">{formatNumberToRupees(item.totalamount)}</Typography>
                      </TableCell>
                      <TableCell align="center">
                        <Tooltip title="Preview" placement="right">
                          <IconButton
                            sx={{
                              '&:hover': {
                                color: theme.palette.primary.main
                              }
                            }}
                            onClick={() => {
                              setIsLoader(true);
                              console.log('selected', item);

                              setTimeout(() => {
                                setIsLoader(false);

                                navigate('/nearle/invoice/preview', {
                                  state: item
                                });
                              }, 500);
                            }}
                          >
                            <VisibilityIcon fontSize="small" />
                          </IconButton>
                        </Tooltip>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </TableContainer>
        </CustomTabPanel>

        <Divider />
        {/* table pagination */}
        <TablePagination
          rowsPerPageOptions={[5, 10, 25, 100]}
          component="div"
          count={deliveryList?.length}
          rowsPerPage={rowsPerPage}
          page={page}
          onPageChange={handleChangePage}
          onRowsPerPageChange={handleChangeRowsPerPage}
        />
      </MainCard>
      {/* ============================================= || Date Dialog|| ============================================= */}
      <DateFilterDialog
        open={open}
        onClose={() => setOpen(false)}
        onSelect={(range) => {
          setStartdate(range.startDate);
          setEnddate(range.endDate);
          setDatestatus(range.label);
          console.log('Selected Date Range:', range);
        }}
      />

      <Outlet />
    </>
  );
};

export default Invoice;
