import React, { useEffect, useState, useRef } from 'react';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { Empty } from 'antd';

import {
  Grid,
  Button,
  Divider,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TablePagination,
  TableRow,
  Tabs,
  Tab,
  Typography,
  Box,
  OutlinedInput,
  InputAdornment,
  IconButton,
  Tooltip,
  Dialog,
  DialogTitle,
  DialogContent,
  Stack,
  Chip
} from '@mui/material';
import axios from 'axios';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom';
import VisibilityIcon from '@mui/icons-material/Visibility';
import { useTheme } from '@mui/material/styles';
import { DateRangePicker } from 'mui-daterange-picker';
import { addDays, addMonths, addWeeks, addYears, endOfMonth, endOfWeek, endOfYear, startOfMonth, startOfWeek, startOfYear } from 'date-fns';
import Loader from 'components/Loader';
import { DownloadOutlined, PrinterFilled } from '@ant-design/icons';
import ReactToPrint from 'react-to-print';
// import nearleLogo from '../../assets/images/nearleLogo.png';
import { DashboardOutlined } from '@ant-design/icons';
import { HiHandThumbDown, HiHandThumbUp } from 'react-icons/hi2';
import LoadingIcons from 'react-loading-icons';

import AddIcon from '@mui/icons-material/Add';
import MainCard from 'components/MainCard';
import { SearchOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import ClearIcon from '@mui/icons-material/Clear';

const columns = [
  { id: 'sno', label: 'sno' },
  { id: 'client', label: 'client' },
  { id: 'invoice ', 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' }
];
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 [content, setcontent] = React.useState('one');
  const [opendate, setOpendate] = useState(false);
  const [deliveryList, setDeliveryList] = useState([]);
  const [predialog, setpredialog] = useState(false);
  const [selected, setselected] = useState({});
  const componentRef = useRef(null);
  const [billStatus, setBillStatus] = useState(0);
  const [isloader, setIsLoader] = useState(false);
  const [insightdata, setinsightdata] = useState(false);
  const [search, setSearch] = useState('');
  const tenid = localStorage.getItem('tenantid');
  const textFieldRef = useRef(null);
  /* ============================================= || handleKeyPress (ctrl+k)| ============================================= */

  useEffect(() => {
    const handleKeyPress = (event) => {
      if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
        event.preventDefault();

        textFieldRef.current.focus();
      }
      if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
        // Remove focus from the TextField
        textFieldRef.current.blur();
      }
    };
    document.addEventListener('keydown', handleKeyPress);

    return () => {
      document.removeEventListener('keydown', handleKeyPress);
    };
  }, []);

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

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

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

  /* ============================================= || fetchinvoiceinsight| ============================================= */
  const fetchinvoiceinsight = async () => {
    try {
      const insightResponse = await axios.get(`${process.env.REACT_APP_URL}/invoice/getinvoiceinsight/?tenantid=${tenid}`);
      console.log('insightResponse', insightResponse.data.details);
      setinsightdata(insightResponse.data.details);
    } catch (error) {
      console.log('insightResponse', error);
    }
  };
  useEffect(() => {
    fetchinvoiceinsight();
  }, []);

  /* ============================================= || fetchdeliverylist| ============================================= */
  const fetchdeliverylist = async () => {
    setIsLoader(true);
    console.log('billstatus', billStatus);
    try {
      let url = `${process.env.REACT_APP_URL}/invoice/getallinvoice/?billstatus=${billStatus}&tenantid=${tenid}`;
      const deliveyResponse = await axios.get(url);
      console.log('fetchdeliverylist', deliveyResponse.data.details);
      setDeliveryList(deliveyResponse.data.details);
      setIsLoader(false);
    } catch (error) {
      console.log('fetchdeliverylist', error);
    }
  };
  useEffect(() => {
    fetchdeliverylist();
  }, [billStatus]);
  useEffect(() => {
    console.log('selected', selected);
  }, [selected]);

  const filteredList = () => {
    let filterdata = deliveryList.filter((data) => data.invoiceno.toLowerCase().includes(search.toLowerCase()));
    setDeliveryList(filterdata);
  };
  useEffect(() => {
    filteredList();
  }, [search]);
  return (
    <>
      {isloader && <Loader />}
      <Grid container>
        <Grid item>
          <Typography variant="h3">Invoice</Typography>
        </Grid>
      </Grid>
      <Grid container spacing={3} sx={{ mt: 0 }}>
        {' '}
        <Grid
          item
          xs={12}
          lg={3}
          sm={6}
          sx={{ cursor: 'pointer' }}
          onClick={() => {
            setValue(0);
            setBillStatus(0);
            setcontent('one');
          }}
        >
          <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);
            setcontent('two');
          }}
        >
          <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);
            setcontent('three');
          }}
        >
          <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);
            setcontent('four');
          }}
        >
          <HoverSocialCard
            primary="Paid"
            secondary={insightdata.paidcount}
            color={theme.palette.success.main}
            iconPrimary={HiHandThumbUp}
          />
        </Grid>
      </Grid>
      {/* ============================================= || Invoice Table || ============================================= */}
      <MainCard
        content={false}
        title={
          <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);
                    setcontent('one');
                  }}
                />
                <Tab
                  label="Open"
                  {...a11yProps(1)}
                  onClick={() => {
                    setValue(1);
                    setBillStatus(1);
                    setcontent('two');
                  }}
                />
                <Tab
                  label="Overdue"
                  {...a11yProps(2)}
                  onClick={() => {
                    setValue(2);
                    setBillStatus(2);
                    setcontent('three');
                  }}
                />
                <Tab
                  label="Paid"
                  {...a11yProps(3)}
                  onClick={() => {
                    setValue(3);
                    setBillStatus(3);
                    setcontent('four');
                  }}
                />
              </Tabs>
            </Grid>
            <Grid item xs={3} sx={{ display: 'flex', justifyContent: 'end' }}>
              <Stack sx={{ mr: 2 }}>
                <OutlinedInput
                  inputRef={textFieldRef}
                  id="input-search-header"
                  placeholder="Search (ctrl+k)"
                  value={search}
                  onChange={(e) => {
                    setSearch(e.target.value);
                    if (e.target.value == '') {
                      fetchdeliverylist();
                    }
                  }}
                  sx={{
                    '& .MuiOutlinedInput-input': {
                      p: '1.5px 0px 1px'
                    },
                    width: '100%'
                  }}
                  //   style={{ margin: "15px 20px" }}
                  startAdornment={
                    <InputAdornment position="start">
                      <SearchOutlined
                        style={{
                          fontSize: 'medium',
                          fontWeight: 'bolder'
                        }}
                      />
                    </InputAdornment>
                  }
                  endAdornment={
                    <IconButton
                      sx={{ visibility: search ? 'visible' : 'hidden' }}
                      onClick={() => {
                        fetchdeliverylist();
                      }}
                    >
                      <ClearIcon style={{ fontSize: 'medium', color: '#65387A' }} />
                    </IconButton>
                  }
                />
              </Stack>
              {/* <Tooltip title="Order Filter">
                <IconButton
                  color="secondary"
                  variant="light"
                  sx={{
                    color: "text.primary",
                    bgcolor: "grey.200",
                    mr: 2,
                  }}
                  aria-haspopup="true"
                  onClick={() => setOpendate(true)}
                >
                  <FilterList />
                </IconButton>
              </Tooltip> */}
            </Grid>
          </Grid>
        }
        // secondary={<CSVExport data={rows} filename={"sticky-table-data.csv"} />}
        sx={{ mt: 3 }}
      >
        <CustomTabPanel value={value} index={value}>
          <TableContainer
            sx={{
              maxHeight: 430,
              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>
                {deliveryList.length == 0 ? (
                  <>
                    <TableCell colSpan={8}>
                      <Stack width={'100%'} direction={'row'} justifyContent={'center'}>
                        <Empty />
                      </Stack>
                    </TableCell>
                  </>
                ) : (
                  deliveryList.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((item, index) => (
                    // <TableRow
                    //   sx={{ py: 3 }}
                    //   hover
                    //   role="checkbox"
                    //   tabIndex={-1}
                    //   key={row.code}
                    // >
                    //   {columns.map((column) => {
                    //     const value = row[column.id];
                    //     return (
                    //       <TableCell key={column.id} align={column.align}>
                    //         {column.format && typeof value === "number"
                    //           ? column.format(value)
                    //           : value}
                    //       </TableCell>
                    //   );
                    //   })}

                    // </TableRow>
                    <TableRow key={index}>
                      <TableCell>{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).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).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">
                        <IconButton
                          sx={{
                            '&:hover': {
                              color: theme.palette.primary.main
                            }
                          }}
                          onClick={() => {
                            setIsLoader(true);
                            console.log('selected', item);
                            setselected(item);
                            setTimeout(() => {
                              setIsLoader(false);
                              // setpredialog(true);
                              navigate('/invoice/preview', {
                                state: item
                              });
                            }, 500);
                          }}
                        >
                          <VisibilityIcon fontSize="small" />
                        </IconButton>{' '}
                      </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>
    </>
  );
};

export default Invoice;
