import React, { useEffect } from 'react';
import { useTheme } from '@mui/material/styles';
import MainCard from 'components/MainCard';
import { Link as RouterLink } from 'react-router-dom';
import SalesChart from './OrdersSalesChart';
import LoadingIcons from 'react-loading-icons';
import { HiHandThumbDown, HiHandThumbUp } from 'react-icons/hi2';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { ThemeMode } from 'config';
import { DashboardOutlined } from '@ant-design/icons';
import { Avatar, Grid, Link, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Typography } from '@mui/material';
import { useQuery } from '@tanstack/react-query';

import { fetchOrderSummary, fetchLocationSummary } from './api';

import Loader from 'components/Loader';
import TitleCard from 'components/TitleCard';

const Orders = () => {
  const theme = useTheme();
  const stc = require('string-to-color');

  /* ============================================= || fetchLocationSummary || ============================================= */

  const {
    data: locationSummarydata,
    isLoading: isLoadingLocationSummary
    // isError: isErrorLocationSummary, //true or false
    // error: locationSummaryError
  } = useQuery({
    queryKey: ['locationSummary'],
    queryFn: fetchLocationSummary
  });
  useEffect(() => {
    console.log('locationSummarydata', locationSummarydata);
  }, [locationSummarydata]);

  /* ============================================= || fetchOrderSummary || ============================================= */

  const {
    data: orderSummarydata,
    isLoading: isLoadingOrderSummary
    // isError: isErrorOrderSummary, //true or false
    // error: orderSummaryError
  } = useQuery({
    queryKey: ['orderSummary'],
    queryFn: fetchOrderSummary
  });

  if (isLoadingOrderSummary || isLoadingLocationSummary) {
    return <Loader />;
  }

  // if (isErrorOrderSummary) {
  //   return 'An error has occurred:(isErrorOrderSummary) ' + orderSummaryError.message;
  // }
  // if (isErrorLocationSummary) {
  //   return 'An error has occurred:(isErrorLocationSummary) ' + locationSummaryError.message;
  // }

  return (
    <>
      <TitleCard title="Orders"> </TitleCard>
      {/* ============================================= || Hover Social Card  || ============================================= */}
      <Grid container spacing={3} sx={{ mt: -3 }}>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Orders"
            secondary={orderSummarydata?.total || 0}
            iconPrimary={DashboardOutlined}
            color={theme.palette.primary.main}
          />
        </Grid>{' '}
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Delivered"
            secondary={orderSummarydata?.delivered || 0}
            iconPrimary={HiHandThumbUp}
            color={theme.palette.success.main}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Pending"
            secondary={orderSummarydata?.pending || 0}
            iconPrimary={LoadingIcons.ThreeDots}
            color={theme.palette.mode === ThemeMode.DARK ? theme.palette.secondary.lighter : theme.palette.warning.main}
          />
        </Grid>
        <Grid item xs={12} custom400={6} sm={3}>
          <HoverSocialCard
            primary="Cancelled"
            secondary={orderSummarydata?.cancelled || 0}
            iconPrimary={HiHandThumbDown}
            color={theme.palette.error.main}
          />
        </Grid>
      </Grid>
      <Grid container spacing={3} sx={{ mt: 2 }}>
        {/* ============================================= || left column|| ============================================= */}
        <Grid item xs={12} sm={8}>
          <MainCard
            elevation={0}
            title="Orders Status"
            content={false}
            secondary={
              <Link component={RouterLink} to="/reports/ordersdetails" color="primary">
                View all
              </Link>
            }
          >
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ pl: 3 }}>Zones</TableCell>
                    <TableCell sx={{ textAlign: 'right' }}>Orders</TableCell>
                    <TableCell sx={{ textAlign: 'right' }}>Delivered</TableCell>
                    <TableCell sx={{ textAlign: 'right' }}>Pending</TableCell>
                    <TableCell sx={{ textAlign: 'right' }}>Cancelled</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {locationSummarydata?.map((zone, index) => (
                    <TableRow hover key={index}>
                      <TableCell sx={{ pl: 3, minWidth: 0 }}>
                        <Grid container spacing={2} alignItems="center" wrap="nowrap">
                          <Grid item>
                            <Avatar sx={{ backgroundColor: stc(zone.locationname?.slice(0, 2)) }}>{zone.locationname?.charAt(0)}</Avatar>
                          </Grid>
                          <Grid item xs zeroMinWidth>
                            <Typography
                              align="left"
                              variant="subtitle1"
                              noWrap
                              sx={{
                                overflow: 'hidden',
                                textOverflow: 'ellipsis'
                              }}
                            >
                              {zone.locationname}
                            </Typography>
                          </Grid>
                        </Grid>
                      </TableCell>

                      <TableCell
                        sx={{
                          textAlign: { xs: 'left', sm: 'right' },
                          pt: { xs: 1, sm: 0 },
                          wordBreak: 'break-word'
                        }}
                      >
                        {zone.total}
                      </TableCell>

                      <TableCell sx={{ textAlign: 'right' }}>{zone.delivered}</TableCell>
                      <TableCell sx={{ textAlign: 'right' }}>{zone.pending}</TableCell>
                      <TableCell sx={{ textAlign: 'right' }}>{zone.cancelled}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </MainCard>
        </Grid>
        {/* ============================================= || right column || ============================================= */}
        <Grid item xs={12} sm={4}>
          <MainCard
            title="Delivered Orders "
            content={false}
            secondary={
              <Link component={RouterLink} to="/reports/ordersdetails" color="primary">
                View all
              </Link>
            }
          >
            <TableContainer>
              <Table>
                <TableHead>
                  <TableRow>
                    <TableCell sx={{ pl: 3, textAlign: 'left' }}>Zones</TableCell>
                    <TableCell sx={{ textAlign: 'right' }}>Delivered</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {locationSummarydata?.map((zone, index) => (
                    <TableRow hover key={index}>
                      <TableCell sx={{ pl: 3 }}>
                        <Grid container spacing={2} alignItems="center">
                          <Grid item>
                            <Avatar sx={{ backgroundColor: stc(zone.locationname?.slice(0, 2)) }}> {zone?.locationname.charAt(0)}</Avatar>
                          </Grid>
                          <Grid item xs zeroMinWidth>
                            <Typography align="left" variant="subtitle1">
                              {zone?.locationname}
                            </Typography>{' '}
                          </Grid>
                        </Grid>
                      </TableCell>

                      <TableCell sx={{ textAlign: 'right' }}>{zone?.delivered}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </TableContainer>
          </MainCard>
        </Grid>
      </Grid>
      {/* ============================================= || Orders chart|| ============================================= */}
      <Grid container spacing={3} sx={{ mt: 2 }}>
        <Grid item xs={12}>
          <SalesChart />
        </Grid>
      </Grid>
    </>
  );
};

export default Orders;
