import React from 'react';
import Loader from 'components/Loader';
import { useEffect, useState, useRef, Fragment } from 'react';
import { useTheme } from '@mui/material/styles';
import MainCard from 'components/MainCard';
import axios from 'axios';
import ClearIcon from '@mui/icons-material/Clear';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import { Empty } from 'antd';
import MyLocationIcon from '@mui/icons-material/MyLocation';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import { enqueueSnackbar } from 'notistack';
import { useNavigate } from 'react-router';
import Papa from 'papaparse';

import {
  FormControl,
  InputAdornment,
  Grid,
  Typography,
  Stack,
  Box,
  Button,
  TextField,
  Autocomplete,
  CardActions,
  Chip,
  Avatar,
  Divider,
  Dialog,
  DialogTitle,
  DialogContent,
  Checkbox,
  DialogActions,
  CircularProgress,
  ButtonGroup,
  FormLabel,
  IconButton,
  Drawer,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  CardHeader,
  Card,
  OutlinedInput,
  FormGroup,
  FormControlLabel,
  Table,
  TableContainer,
  TableCell,
  TableBody,
  TableRow,
  Paper,
  TableHead
} from '@mui/material';
import { log } from 'util';

const MultipleOrders = () => {
  const navigate = useNavigate();
  const theme = useTheme();
  const [locaName, setLocoName] = useState('Select Location');
  const [locations, setLocations] = useState([]);
  const [tenantlist, setTenantlist] = useState([]);
  const [loading, setLoading] = useState(false);
  const [btnLoading, setBtnLoading] = useState(false);
  const [appId, setAppId] = useState(0);
  const [isAppLocation, setIsAppLocation] = useState(false);
  const [isBusiness, setIsBusiness] = useState(false);
  const [isClient, setisclient] = useState(false);
  const [tenantLocations, setTenantlocations] = useState([]);
  const userid = localStorage.getItem('userid');
  const [tenantid, setTenantid] = useState();
  const [tid, setTid] = useState(0);
  const [tenanatLocoId, setTenanatLocoId] = useState(localStorage.getItem('locationid'));
  const [tenantlocation, setTenantlocation] = useState('');
  const [isLocation, setIsLocation] = useState(false);
  const [basePrice, setBasePrice] = useState(0);
  const [pricePerKm, setPricePerKm] = useState(0);
  const [minKm, setMinKm] = useState(0);
  const [tenantinfo, setTenantinfo] = useState({});
  const [pickCust, setPickCust] = useState({});
  const [dropCust, setDropCust] = useState([]);
  const [isCustomerOpen, setIsCustomerOpen] = useState(false);
  const [searchCustList, setSearchCustList] = useState('');
  const [customerlist, setCustomerlist] = useState([]);
  const [clientdetail, setClientdetail] = useState([]);
  const [appLocaLat, setAppLocaLat] = useState();
  const [appLocaLng, setAppLocaLng] = useState();
  const [appLocaRadius, setAppLocaRadius] = useState();
  const [startdate, setStartdate] = useState(dayjs().format('MM-DD-YYYY'));
  const [timeslotarr, setTimeslotarr] = useState([]);
  const [showDistance, setShowDistance] = useState(false);
  const [subCat, setSubCat] = useState([]);
  const [subCatName, setSubCatName] = useState('Select ');
  const [subCatId, setSubCatId] = useState(0);
  const [weight, setWeight] = useState('');
  const [selectedCatChip, setSelectedCatChip] = useState(null);
  const [isSms, setIsSms] = useState(0);
  const [starttime, setStatrttime] = useState();
  const [endtime, setEndtime] = useState();
  const [selectedtime, setSelectedtime] = useState('');
  const [distance, setDistance] = useState(0);
  const [alertmessage, setAlertmessage] = useState('');
  const [otherinstructions, setOtherinstructions] = useState('');
  const [totalCharge, setTotalCharge] = useState(0);
  const [admintoken, setAdmintoken] = useState();
  const [tenant, setTenant] = useState(0);
  const [totaldist, settotaldist] = useState(0);
  const [totalAmt, settotalAmt] = useState(0);
  const [users, setUsers] = useState([]);
  const [deliverydatetime, setDeliverydatetime] = useState(dayjs().format('YYYY-MM-DD HH:mm:ss'));

  useEffect(() => {
    if (timeslotarr[0]) {
      let arr = [];
      timeslotarr.map((val) => {
        if (dayjs().diff(dayjs(`${dayjs(startdate).format('MM-DD-YYYY')} ${dayjs(val).format('HH:mm:ss')}`), 'm') <= 0) {
          arr.push(val);
        }
      });
    }
  }, [timeslotarr]);

  // =============================================== || chipStyle ( time slot) || ===============================================
  const chipStyle = (chipLabel) => ({
    cursor: 'pointer',
    backgroundColor: selectedCatChip === chipLabel ? theme.palette.primary.main : 'default',
    color: selectedCatChip === chipLabel ? '#fff' : '',
    '&:hover': {
      backgroundColor: selectedCatChip === chipLabel ? theme.palette.primary.main : theme.palette.primary.light,
      color: '#fff'
    }
  });
  const handleChipClick = (chipLabel) => {
    setSelectedCatChip(chipLabel);
  };

  // =============================================== || opentoast || ===============================================
  const opentoast = (message, variant, time) => {
    enqueueSnackbar(message, {
      variant: variant,
      anchorOrigin: { vertical: 'top', horizontal: 'right' },
      autoHideDuration: time ? time : 1500
    });
    console.log(alertmessage);
  };

  // 🔹 Smart toast wrapper — prevents duplicate toasts for same message within 3 seconds
  let toastCache = {};
  const OpenToastSmart = (message, type = 'info', timeout = 10000) => {
    const key = `${type}-${message}`;
    if (toastCache[key]) return; // skip duplicates
    opentoast(message, type, timeout); // your existing toast/snackbar
    toastCache[key] = true;
    setTimeout(() => delete toastCache[key], 3000); // reset after delay
  };

  // ==============================|| fetchAppLocations ||============================== //
  const fetchAppLocations = async () => {
    try {
      const locationRes = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${userid}`);
      console.log('fetchAppLocations', locationRes.data.details);
      setLocations(locationRes.data.details);
    } catch (err) {
      console.log('locationRes', err);
    }
  };
  useEffect(() => {
    fetchAppLocations();
  }, []);

  // ===================================================== || fetchtenantinfolist || =====================================================

  const fetchtenantinfolist = async (id) => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/tenants/gettenants/?applocationid=${id}&status=active`)

      .then((res) => {
        console.log(res);
        if (res.data.status) {
          let arr = [];
          res.data.details.map((val) => {
            arr.push({
              ...val,
              label: `${val.tenantname}`
            });
          });
          setTenantlist(arr);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  // ============================================= || fetchTenantPricing  || =============================================

  const fetchTenantPricing = async (id) => {
    try {
      const pricingResponse = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantpricing/?tenantid=${id}`);
      console.log('pricingResponse', pricingResponse.data.details);
      setBasePrice(pricingResponse.data.details.baseprice);
      setPricePerKm(pricingResponse.data.details.priceperkm);
      setMinKm(pricingResponse.data.details.minkm);
    } catch (error) {
      console.log('fetchTenantPricing error', error);
    }
  };
  // ============================================= || gettenantlocations (branches) || =============================================
  const gettenantlocations = async (id) => {
    try {
      const res = await axios.get(`${process.env.REACT_APP_URL}/tenants/gettenantlocations/?tenantid=${id}`);
      console.log('gettenantlocations', res.data.details);
      if (res.data.details.length == 1) {
        setIsLocation(true);
        setTenantlocations(res.data.details);
        setPickCust(res.data.details[0]);
        setTenanatLocoId(res.data.details[0].locationid);
        setTenantlocation(res.data.details[0].address); //client address
        setIsBusiness(true);
      } else {
        setTenantlocations(res.data.details);
        setIsBusiness(false); // became true after select from tenanatLocations
      }
    } catch (err) {
      console.log('gettenantlocations', err);
    }
  };
  // ========================================================= || clientdetails || =========================================================
  const clientdetails = async () => {
    try {
      let url =
        searchCustList == ''
          ? `${process.env.REACT_APP_URL}/customers/gettenantcustomers/?tenantid=${tid}&pageno=1&pagesize=10`
          : `${process.env.REACT_APP_URL}/customers/search/?tenantid=${tid}&keyword=${searchCustList}`;
      await axios
        .get(url)
        .then((res) => {
          if (res.data.status) {
            console.log('clientdetails', res.data.details);

            setClientdetail(res.data.details);
            setCustomerlist(res.data.details);
            let arr = [];
            res.data.details.map((val) => {
              arr.push({
                label: `${val.firstname} | ${val.contactno}`,
                ...val
              });
            });
          }
        })
        .catch((err) => {
          console.log(err);
          opentoast('server error', 'warning');
        });
    } catch (err) {
      console.log(err);
    }
  };
  useEffect(() => {
    if (tid) {
      clientdetails();
    }
  }, [searchCustList.length > 3, searchCustList == '', tid]);

  // ========================================================= || calculateTotal(dist , charge) || =========================================================
  const calculateTotal = () => {
    let a1 = 0;
    let a2 = 0;
    dropCust.map((customer) => {
      a1 += customer.distance;
      a2 += customer.totalcharge;
    });
    settotaldist(a1);
    settotalAmt(a2);
  };
  useEffect(() => {
    calculateTotal();
  }, [dropCust]);

  // ========================================================= || handleCheckboxChange || =========================================================
  const handleCheckboxChange = async (event, customer) => {
    if (event.target.checked) {
      // If the checkbox is checked, calculate the distance and add the customer
      try {
        const obj = await calculateDistance(customer);
        const { roundedDistance, totalcharge } = obj;
        // Create a new customer object with the distance property
        const updatedCustomer = {
          ...customer,
          distance: roundedDistance,
          totalcharge: totalcharge
        };

        // Add the updated customer object to dropCust
        setDropCust((prevDropCust) => [...prevDropCust, updatedCustomer]);

        // Log the rounded distance
        console.log(`Rounded Distance: ${roundedDistance} km`);
      } catch (error) {
        console.error('Failed to calculate distance:', error);
      }
    } else {
      // If the checkbox is unchecked, remove the customer from dropCust
      setDropCust((prevDropCust) => {
        return prevDropCust.filter((cust) => cust.customerid !== customer.customerid);
      });
    }
  };
  // ========================================================= || handleCheckboxChange1 || =========================================================
  const handleCheckboxChange1 = async (customer) => {
    setLoading(true);
    try {
      const obj = await calculateDistance(customer);
      const { roundedDistance, totalcharge } = obj;
      // Create a new customer object with the distance property
      const updatedCustomer = {
        ...customer,
        distance: roundedDistance,
        totalcharge: totalcharge
      };

      // Add the updated customer object to dropCust
      setDropCust((prevDropCust) => [...prevDropCust, updatedCustomer]);

      // Log the rounded distance
      console.log(`Rounded Distance: ${roundedDistance} km`);
      setLoading(false);
    } catch (error) {
      console.error('Failed to calculate distance:', error);
    }
  };

  // ========================================================= || calculateDistance || =========================================================

  // 🔹 Main distance calculation function
  const calculateDistance = async (customer) => {
    const service = new google.maps.DistanceMatrixService();

    // Helper: safely get distance matrix
    const getDistanceMatrix = (origins, destinations) => {
      return new Promise((resolve, reject) => {
        2;
        try {
          if (!origins || !destinations) {
            return reject(new Error('Origin or destination data missing.'));
          }

          // if (
          //   typeof origins.latitude !== 'number' ||
          //   typeof origins.longitude !== 'number' ||
          //   typeof destinations.latitude !== 'number' ||
          //   typeof destinations.longitude !== 'number'
          // ) {
          //   return reject(new Error('Invalid coordinates format. Expected numeric latitude/longitude.'));
          // }

          service.getDistanceMatrix(
            {
              origins: [new google.maps.LatLng(origins.latitude, origins.longitude)],
              destinations: [new google.maps.LatLng(destinations.latitude, destinations.longitude)],
              travelMode: 'DRIVING',
              unitSystem: google.maps.UnitSystem.METRIC
            },
            (response, status) => {
              if (status === 'OK') {
                resolve(response);
              } else {
                reject(new Error(`Google API error: ${status}`));
              }
            }
          );
        } catch (err) {
          reject(new Error(`Unexpected error inside DistanceMatrixService: ${err.message}`));
        }
      });
    };

    try {
      // --- Input validation ---
      if (!customer || typeof customer !== 'object') {
        throw new Error('Invalid customer data: expected an object.');
      }

      if (!pickCust || typeof pickCust !== 'object') {
        throw new Error('Origin (pickCust) data missing or invalid.');
      }

      // --- Call Google Maps API ---
      const response = await getDistanceMatrix(pickCust, customer);

      // --- Validate response structure ---
      if (!response.rows?.[0]?.elements?.[0] || !response.rows[0].elements[0].distance?.value) {
        throw new Error('Malformed Distance Matrix response: missing distance value.');
      }

      // --- Compute distance ---
      const distanceInMeters = response.rows[0].elements[0].distance.value;
      const distanceInKilometers = distanceInMeters / 1000;
      const roundedDistance = Math.round(distanceInKilometers);

      // --- Calculate total charge ---
      let totalcharge;
      if (roundedDistance < minKm) {
        totalcharge = basePrice;
      } else {
        totalcharge = (roundedDistance - minKm) * pricePerKm + basePrice;
      }

      setTotalCharge(totalcharge);
      return { roundedDistance, totalcharge };
    } catch (error) {
      // --- Categorized smart error handling ---
      if (error.message.includes('Google API')) {
        console.error('🚨 Google Maps API Error:', error.message);
        OpenToastSmart('Google Maps API Error: ' + error.message, 'error');
      } else if (error.message.includes('Invalid coordinates')) {
        console.error('📍 Invalid coordinate format:', error.message);
        OpenToastSmart('Invalid coordinate format. Check location data.', 'warning');
      } else if (error.message.includes('Malformed Distance Matrix')) {
        console.error('⚠️ Unexpected Google response structure:', error.message);
        OpenToastSmart('Google Distance Matrix returned invalid data.', 'error');
      } else if (error.message.includes('Origin') || error.message.includes('customer')) {
        console.error('❌ Missing or invalid input data:', error.message);
        OpenToastSmart('Missing or invalid input data for distance calculation.', 'warning');
      } else {
        console.error('💥 Unexpected error calculating distance:', error);
        OpenToastSmart('Unexpected error during distance calculation.', 'error');
      }

      throw error; // keeps your current flow intact
    }
  };

  // ==================================================== || fetchTiming || ====================================================
  const fetchTiming = async () => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/utils/getapplocations/?applocationid=${appId}`)
      .then((res) => {
        console.log('fetchTiming', res);
        const { opentime, closetime, latitude, longitude, radius } = res.data.details[0];
        if (res.data.status) {
          setAppLocaLat(latitude);
          setAppLocaLng(longitude);
          setAppLocaRadius(radius);
          setStatrttime(`${dayjs().format('MM-DD-YYYY')} ${opentime}`);
          setEndtime(`${dayjs().format('MM-DD-YYYY')} ${closetime}`);
          console.log('starttime', `${dayjs().format('MM-DD-YYYY')} ${opentime}`);
          console.log('endtime', `${dayjs().format('MM-DD-YYYY')} ${closetime} `);
          let arr = [];
          for (
            let i = `${dayjs().format('MM-DD-YYYY')} ${opentime}`, j = 0;
            dayjs(`${dayjs().format('MM-DD-YYYY')} ${closetime} `).diff(i, 'm') >= 0;
            j++, i = dayjs(i).add(30, 'm')
          ) {
            arr.push(i);
          }
          console.log('setTimeslotarr', arr);
          setTimeslotarr(arr);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  useEffect(() => {
    if (appId) {
      fetchTiming();
    }
  }, [starttime, endtime, appId]);
  // ==================================================== || getsubcategories || ====================================================
  const getsubcategories = async () => {
    await axios
      .get(`${process.env.REACT_APP_URL}/utils/getsubcategories/?moduleid=6`)
      .then((res) => {
        console.log('subcateRes', res.data.details);
        if (res.data.status) {
          setSubCat(res.data.details);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
  useEffect(() => {
    getsubcategories();
  }, []);
  const fetchAppAdminTokens = async () => {
    setLoading(true);
    await axios
      .get(`${process.env.REACT_APP_URL}/utils/getapplocationconfig/?applocationid=${appId}`)
      .then((res) => {
        const userfcmtokemArray = res.data.details.applocationadmins.map((admin) => admin.userfcmtokem); // fcm => firebase cloud messaging
        console.log('fetchAppAdminTokens', res);
        console.log('userfcmtokemArray', userfcmtokemArray);
        if (res.data.status) {
          setAdmintoken(userfcmtokemArray);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };

  useEffect(() => {
    if (starttime && endtime) {
      fetchAppAdminTokens();
    }
  }, [starttime, endtime]);

  useEffect(() => {
    console.log('pickCust', pickCust);
  }, [pickCust]);
  useEffect(() => {
    console.log('dropCust', dropCust);
  }, [dropCust]);
  // ==================================================== || fetchtenantinfo || ====================================================
  const fetchtenantinfo = async () => {
    setLoading(true);
    console.log('tid', tid);

    await axios
      .get(`${process.env.REACT_APP_URL}/tenants/gettenantinfo/?tenantid=${tid}`)
      .then((res) => {
        console.log('fetchtenantinfo', res);
        if (res.data.status) {
          setTenant(res.data.details);
          setTenantid(res.data.details.tenantid);
          fetchAppAdminTokens();
          setSubCatName(res.data.details.subcategoryname);
          setSubCatId(res.data.details.subcategoryid);
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  };
  useEffect(() => {
    if (tid) {
      fetchtenantinfo();
    }
  }, [tid]);
  // ================================================== ||  sendnotifications || ==================================================
  const sendnotifications = async () => {
    setLoading(true);
    await axios
      .post(`${process.env.REACT_APP_URL}/utils/sendnotifications`, {
        priority: 'high',
        registration_ids: admintoken,
        data: {
          accessid: process.env.REACT_APP_RIDER_ACCESS_ID
        },
        notification: {
          title: 'Nearle Merchant',
          body: 'An Order has been placed successfully,kindly process the same',
          sound: 'ring'
        }
      })
      .then((res) => {
        console.log(res);
        if (res.data.message == 'Success') {
          enqueueSnackbar('Notification sent Successfully', {
            variant: 'success',
            anchorOrigin: { vertical: 'top', horizontal: 'right' },
            autoHideDuration: 1000
          });
        }
        setLoading(false);
      })
      .catch((err) => {
        console.log(err);
        enqueueSnackbar(err.message, {
          variant: 'error',
          anchorOrigin: { vertical: 'top', horizontal: 'right' },
          autoHideDuration: 1000
        });
        setLoading(false);
      });
  };

  // const handleFileUpload = (event) => {
  //   const file = event.target.files[0];
  //   if (file) {
  //     Papa.parse(file, {
  //       header: true,
  //       dynamicTyping: true,
  //       complete: function (results) {
  //         console.log('Parsed Data: ', results.data);
  //         setUsers(results.data);
  //       },
  //       error: function (error) {
  //         console.error('Error parsing CSV file: ', error);
  //       }
  //     });
  //   }
  // };
  const handleFileUpload = (event) => {
    try {
      const file = event.target.files?.[0];

      // 1️⃣ Validate file existence
      if (!file) {
        console.warn('No file selected.');
        return;
      }

      // 2️⃣ Validate file type (optional but recommended)
      if (!file.name.toLowerCase().endsWith('.csv')) {
        console.error('Invalid file type. Please upload a CSV file.');
        return;
      }

      // 3️⃣ Parse safely with Papa
      Papa.parse(file, {
        header: true,
        dynamicTyping: true,
        skipEmptyLines: true,
        complete: (results) => {
          try {
            // Check parsing metadata

            if (results.errors?.length) {
              opentoast(results.errors, 'warning');
              console.warn('PapaParse reported errors:', results.errors);
            }

            if (!results.data || results.data.length === 0) {
              console.warn('CSV file is empty or has no valid rows.');
              opentoast('CSV file is empty or has no valid rows.', 'warning');
              setUsers([]); // reset to avoid stale data
              return;
            }

            console.log('Parsed Data:', results.data);
            setUsers(results.data);
          } catch (parseError) {
            opentoast(parseError, 'warning');
            console.error('Error processing parsed CSV data:', parseError);
          }
        },
        error: (error) => {
          opentoast(error, 'warning');

          console.error('Error parsing CSV file:', error);
        }
      });
    } catch (err) {
      console.error('Unexpected error during file upload:', err);
    }
  };

  // =============================================== ||  createorders  || ===============================================
  const createorders = async () => {
    const arr = dropCust.map((customer) => ({
      applocationid: pickCust.applocationid,
      cancellled: '',
      //   categoryid: +tenant.categoryid,
      configid: 9,
      customerid: 0,
      deliveryaddress: customer.address || '',
      deliverycharge: +customer.totalcharge || 0,
      deliverycity: customer.city || '',
      deliverycontactno: customer.contactno.toString() || '',
      deliverycustomer: customer.firstname || '',
      deliveryid: +customer.customerid,
      deliverylandmark: customer.landmark || '',
      deliverylat: customer.latitude.toString(),
      deliverylocation: customer.suburb || '',
      deliverylocationid: customer.deliverylocationid || 0,
      deliverylong: customer.longitude.toString(),
      // deliverytime: `${dayjs(startdate).format('YYYY-MM-DD')} `,
      deliverytime: `${dayjs(startdate).format('YYYY-MM-DD')} ${dayjs(selectedtime.$d).format('HH:mm:ss')}`,
      // deliverytime: deliverydatetime,
      deliverytype: 'B',
      delivered: '',
      itemcount: 1,
      kms: customer.distance.toString() || 0,
      locationid: +pickCust.locationid,
      // moduleid: +pickCust.moduleid,
      moduleid: 6,
      orderamount: +customer.totalcharge || 0,
      ordercharges: 0.0,
      orderdate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      orderheaderid: 0,
      orderid: '', //
      ordernotes: otherinstructions,
      orderstatus: 'created',
      ordervalue: +customer.totalcharge || 0,
      partnerid: pickCust.partnerid,
      partneruserid: +userid,
      paymentstatus: 1,
      paymenttype: 42,
      pending: '',
      pickupaddress: pickCust.address || '',
      pickupcity: pickCust.city || '',
      pickupcontactno: pickCust.contactno || '',
      pickupcustomer: pickCust.locationname || '',
      pickuplandmark: pickCust.landmark || '',
      // pickuplat: pickCust.locationlatitude.toString(),
      pickuplat: pickCust.latitude,
      pickuplocation: pickCust.suburb || '',
      pickuplocationid: pickCust.locationid || 0,
      pickuplong: pickCust.longitude,
      // pickuplong: pickCust.locationlong.toString(),
      processing: '',
      ready: '',
      remarks: '',
      //   smsdelivery: isSms,
      //   subcategoryid: +subCatId,
      taxamount: 0.0,
      tenantid: pickCust.tenantid,
      tenantuserid: 0
    }));
    console.log('arr', arr);

    if (!tid) {
      opentoast('Choose Client ', 'warning');
    }
    //  else if (!tenantinfo.address) {
    //   opentoast('Choose Pickup Location', 'warning');
    // } else if (!clientinfo.address) {
    //   opentoast('Choose Drop Location', 'warning');
    // } else if (!selectedtime) {
    //   opentoast('Choose Schedule Time', 'warning');
    // }
    else {
      setLoading(true);
      await axios
        .post(`${process.env.REACT_APP_URL}/orders/createorders`, arr)
        .then((res) => {
          if (res.data.status) {
            enqueueSnackbar('Order Created Successfully', {
              variant: 'success',
              anchorOrigin: { vertical: 'top', horizontal: 'right' },
              autoHideDuration: 1000
            });
            if (admintoken) {
              sendnotifications();
            }
            navigate('/orders');
          } else {
            opentoast(res.data.message, 'warning');
          }
          setLoading(false);
          console.log(res);
        })
        .catch((err) => {
          console.log(err);
          setLoading(false);
        });
    }
  };
  const [fileName, setFileName] = useState('');

  const onFileChange = (event) => {
    console.log('event', event);
    console.log('event[0]', event.target.files[0]);

    const file = event.target.files[0];
    if (file) {
      setFileName(file.name);
      handleFileUpload(event); // Call the parent component's handler
    }
  };
  return (
    <>
      {loading && <Loader />}
      <Grid
        container
        spacing={3}
        sx={{
          position: 'sticky',
          top: '60px',
          bgcolor: theme.palette.background.default,
          zIndex: 100,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'start',
          alignItems: 'center',
          spacing: 5
        }}
      >
        <Grid item xs={12} sx={{ width: '100%', mt: -1 }}>
          <Stack>
            <Typography variant="h3"> Create Multiple Order</Typography>
          </Stack>
        </Grid>
        <Grid item xs={12} sx={{ width: '100%', mt: -2 }}>
          <MainCard sx={{ height: '100%' }}>
            <Grid container spacing={3} sx={{}}>
              {/* ===================================================== || Choose location  || ===================================================== */}
              <Grid item xs={12} sm={4}>
                <Autocomplete
                  fullWidth
                  id="combo-box-demo"
                  label={locaName}
                  options={locations || []}
                  getOptionLabel={(option) => `${option.locationname}`}
                  renderInput={(params) => <TextField {...params} label={'Choose Location'} focused />}
                  onChange={(event, value, reason) => {
                    if (reason === 'clear') {
                      fetchtenantinfolist(0);
                      setAppId(0);
                      setLocoName('Select  Location');
                      setIsAppLocation(false);
                      setIsBusiness(false);
                      setisclient(false);
                      setDropCust([]);
                      setPickCust([]);
                    } else {
                      console.log(value);
                      fetchtenantinfolist(value.applocationid);
                      setAppId(value.applocationid);
                      setLocoName(value.locationname);
                      setIsAppLocation(true);
                      setisclient(false);
                      setDropCust([]);
                      setPickCust([]);
                    }
                  }}
                />{' '}
              </Grid>
              {/* ===================================================== || Choose client  || ===================================================== */}
              <Grid item xs={12} sm={4}>
                <Autocomplete
                  fullWidth
                  disabled={appId == 0 || !isAppLocation}
                  id="free-solo-demo"
                  sx={{}}
                  options={tenantlist || []}
                  renderInput={(params) => <TextField {...params} label="Choose Client" focused />}
                  onChange={(e, val, reason) => {
                    if (val) {
                      setTenantid(val.tenantid);
                      console.log('Client', val);
                      fetchTenantPricing(val.tenantid);
                      gettenantlocations(val.tenantid);
                      setTid(val.tenantid);
                      setisclient(true);
                      setDropCust([]);
                    } else {
                      setTenantinfo({});

                      setTenantid('');
                    }
                    if (reason == 'clear') {
                      setisclient(false);
                    }
                  }}
                />{' '}
              </Grid>
              {/* ===================================================== ||Business Location || ===================================================== */}
              <Grid item xs={12} sm={4}>
                {tenantLocations.length == 1 ? (
                  <TextField
                    disabled={!isAppLocation || !isClient}
                    variant="outlined"
                    fullWidth
                    label={'Business Location'}
                    value={tenantLocations[0].locationname}
                    focused
                    sx={{}}
                    InputProps={{
                      style: { color: theme.palette.primary.main },
                      startAdornment: (
                        <InputAdornment position="start">
                          <MyLocationIcon color="primary" />
                        </InputAdornment>
                      )
                    }}
                  />
                ) : (
                  <Autocomplete
                    fullWidth
                    disabled={!isAppLocation || !isClient}
                    id="combo-box-demo"
                    options={tenantLocations || []}
                    getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
                    renderInput={(params) => <TextField {...params} label="Select Business Locations" focused color="primary" />}
                    sx={{}}
                    onChange={(event, value, reason) => {
                      if (value) {
                        console.log('Business Locations', value);
                        console.log('locationid', value.locationid);
                        setTenanatLocoId(value.locationid);
                        setTid(value.tenantid);
                        setTenantlocation(value.address);
                        setIsLocation(true);
                        setIsBusiness(true);
                        setPickCust(value);
                      }
                      if (reason == 'clear') {
                        setIsLocation(false);
                        setIsBusiness(false);
                      }
                    }}
                  />
                )}
              </Grid>
            </Grid>
          </MainCard>
        </Grid>
        {/* ===================================================== || Pickup || ===================================================== */}
        <Grid item xs={12} sx={{ width: '100%', mt: 0 }}>
          <Grid container xs={12}>
            <Grid item xs={12}>
              {isBusiness && (
                <Box display="flex" alignItems="center" sx={{}}>
                  <TextField
                    fullWidth
                    value={`${pickCust.locationname}  (${pickCust.address})`}
                    InputProps={{
                      readOnly: true,
                      style: { fontSize: '1rem', fontWeight: 'bold', color: theme.palette.primary.main }
                    }}
                  />
                </Box>
              )}
            </Grid>
            {/* ================================================= || Time || ================================================= */}
            <Fragment>
              <Grid item xs={12}>
                <Stack display={'flex'} flexDirection={'row'} justifyContent={'end'}>
                  <Stack>
                    <Typography variant="h5">Date</Typography>
                    <LocalizationProvider dateAdapter={AdapterDayjs} sx={{}}>
                      <DatePicker
                        format="DD-MM-YYYY"
                        onChange={(e) => {
                          setDeliverydatetime(dayjs(e).format('YYYY-MM-DD HH:mm:ss'));
                          setStartdate(e);
                          let dateres11 = dayjs().diff(dayjs(`${dayjs(e).format('YYYY-MM-DD')}`), 'd');
                          console.log('dateres11');
                          console.log(dateres11);
                          setSelectedtime('');
                          if (dateres11 <= 0) {
                            console.log('startdate', e);
                            setStartdate(e);

                            let arr = [];
                            timeslotarr.map((val) => {
                              if (dayjs().diff(dayjs(`${dayjs(e).format('MM-DD-YYYY')} ${dayjs(val).format('HH:mm:ss')}`), 'm') <= 0) {
                                arr.push(val);
                              }
                            });
                          } else {
                            setAlertmessage('choose Upcoming Date');
                            opentoast('choose Upcoming Date', 'warning');
                            setStartdate(NaN);
                          }
                        }}
                        value={dayjs(startdate)}
                        sx={{ width: 'auto', mt: 0 }}
                        disablePast
                      />
                    </LocalizationProvider>
                  </Stack>
                </Stack>
                {timeslotarr.length > 0 && (
                  <MainCard sx={{ mt: 2 }}>
                    <Grid container>
                      <Grid item xs={12}>
                        <>
                          <Typography variant="h5" sx={{ my: 2 }}>
                            Time
                          </Typography>
                          <MainCard
                            sx={{
                              mt: 1,
                              overflowY: 'scroll',
                              '&::-webkit-scrollbar': {
                                width: '3px', // Width of vertical scrollbar
                                height: '10px' // Height of horizontal scrollbar
                              },
                              '&::-webkit-scrollbar-thumb': {
                                backgroundColor: '#65387A' // Color of the scrollbar thumb
                              }
                            }}
                          >
                            <Grid container spacing={2}>
                              {timeslotarr.map((val, index) => {
                                if (
                                  dayjs().diff(dayjs(`${dayjs(startdate).format('MM-DD-YYYY')} ${dayjs(val).format('HH:mm:ss')}`), 'm') <= 0
                                ) {
                                  return (
                                    <Fragment key={index}>
                                      <Grid item>
                                        <Chip
                                          key={index}
                                          sx={{ cursor: 'pointer' }}
                                          color={dayjs(selectedtime).format('HH:mm') == dayjs(val).format('HH:mm') ? 'primary' : 'default'}
                                          label={dayjs(val).format('hh:mm A')}
                                          onClick={() => {
                                            console.log('selectedtime', val);
                                            setSelectedtime(val);
                                          }}
                                          // onClick={() => {
                                          //   if (distance > appLocaRadius) {
                                          //     setOpen(true);
                                          //   } else if (showDistance) {
                                          //     console.log('selectedtime', val);
                                          //     setSelectedtime(val);
                                          //   } else {
                                          //     opentoast('Out of city limit', 'error');
                                          //   }
                                          // }}
                                        />
                                      </Grid>
                                    </Fragment>
                                  );
                                }
                              })}
                            </Grid>
                          </MainCard>
                        </>
                      </Grid>
                    </Grid>
                  </MainCard>
                )}
              </Grid>
            </Fragment>
          </Grid>
        </Grid>

        {/* ===================================================== || Drop  || ===================================================== */}

        <Grid item xs={12} sx={{ width: '100%', mt: 0 }}>
          <MainCard
            sx={{ height: '100%', p: 2 }}
            title={`Drop (${dropCust?.length || 0})`}
            secondary={
              <Stack direction={'row'} spacing={3} sx={{ mb: 2 }}>
                {isBusiness && (
                  <Box display="flex" flexDirection="column" alignItems="center" justifyContent="center">
                    <Box display="flex" flexDirection="row" alignItems="center" justifyContent="center">
                      {fileName && (
                        <Typography variant="body2" color="textSecondary" sx={{ marginRight: 2 }}>
                          Selected file: {fileName}
                        </Typography>
                      )}
                      <input accept=".csv" id="contained-button-file" type="file" style={{ display: 'none' }} onChange={onFileChange} />
                      <label htmlFor="contained-button-file">
                        <Button variant="contained" color="primary" component="span">
                          Upload CSV
                        </Button>
                      </label>
                    </Box>
                  </Box>
                )}
                {users.length >= 1 && (
                  <Button
                    variant="contained"
                    size="small"
                    color="primary"
                    sx={{
                      ...(!dropCust?.length && {
                        '@keyframes blink': {
                          '0%': { opacity: 1 },
                          '50%': { opacity: 0.3 },
                          '100%': { opacity: 1 }
                        },
                        animation: 'blink 1s infinite'
                      })
                    }}
                    onClick={() => {
                      users.map((customer, index) => {
                        console.log(index, customer);
                        handleCheckboxChange1(customer);
                      });
                    }}
                  >
                    Continue
                  </Button>
                )}
                <Button
                  variant="outlined"
                  size="small"
                  sx={{
                    '&:hover': {
                      bgcolor: theme.palette.primary.main,
                      color: 'white'
                    }
                  }}
                  onClick={() => {
                    if (!isLocation) {
                      opentoast('Select Business Location', 'warning');
                    } else {
                      setIsCustomerOpen(true);
                      setSearchCustList('');
                    }
                  }}
                >
                  Select Customers
                </Button>
              </Stack>
            }
          >
            <TableContainer component={Paper}>
              <Table sx={{ minWidth: 650 }} aria-label="simple table">
                <TableHead>
                  <TableRow>
                    <TableCell>S.No</TableCell>
                    <TableCell>Customer</TableCell>
                    <TableCell>Address</TableCell>
                    <TableCell>Kms</TableCell>
                    <TableCell align="right">Charge</TableCell>
                    <TableCell align="center">Action</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {dropCust.map((customer, index) => (
                    <TableRow key={index}>
                      <TableCell>{index + 1}</TableCell>
                      <TableCell>{customer.firstname}</TableCell>
                      {/* <TableCell>{customer.ReceiverName}</TableCell> */}
                      <TableCell>{customer.address}</TableCell>
                      <TableCell>{customer.distance}</TableCell>
                      <TableCell align="right">{`₹${customer.totalcharge}.00`}</TableCell>
                      <TableCell align="center">
                        {
                          <>
                            <CloseOutlined
                              style={{ cursor: 'pointer', color: 'red' }}
                              onClick={(event) => handleCheckboxChange(event, customer)}
                            />
                          </>
                        }
                      </TableCell>
                    </TableRow>
                  ))}
                  {dropCust.length != 0 && (
                    <TableRow>
                      <TableCell>Total</TableCell>
                      <TableCell></TableCell>
                      <TableCell></TableCell>
                      <TableCell>
                        <Typography variant="h5">{`${totaldist} `}</Typography>
                      </TableCell>

                      <TableCell align="right">
                        <Typography variant="h5">{`₹${totalAmt}.00`}</Typography>
                      </TableCell>
                      <TableCell></TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </TableContainer>
          </MainCard>
        </Grid>

        <Grid item xs={12} sx={{ width: '100%', mt: -2 }}>
          {/* ================================================= || Notes || ================================================= */}
          <MainCard sx={{ mt: 2, p: 3 }} title={'Notes'}>
            <Grid container>
              <Grid item xs={12}>
                <TextField
                  focused
                  id="outlined-multiline-static"
                  sx={{ width: '100%', height: '100%', mb: 2 }}
                  multiline
                  rows={1}
                  placeholder="Notes"
                  value={otherinstructions}
                  onChange={(e) => setOtherinstructions(e.target.value)}
                />
              </Grid>
              <Stack direction="row" justifyContent={'end'} sx={{ mt: 2, width: '100%' }}>
                <Button
                  disabled={dropCust.length == 0}
                  size="medium"
                  variant="outlined"
                  onClick={() => {
                    setLoading(true);
                    setBtnLoading(true);
                    createorders();
                    setTimeout(() => {
                      setLoading(false);
                      setBtnLoading(false);
                    }, 2000);
                  }}
                  sx={{
                    '&:hover': {
                      transform: 'scale(1.05)',
                      transition: 'transform 0.3s ease'
                    }
                  }}
                >
                  {btnLoading ? <CircularProgress color="primary" size={20} thickness={10} /> : 'Create'}
                </Button>
              </Stack>
            </Grid>
          </MainCard>
        </Grid>
      </Grid>
      {/* ============================================= || saved address Dialog || ============================================= */}
      <Dialog
        open={isCustomerOpen}
        onClose={() => {
          setIsCustomerOpen(false);
        }}
        fullWidth
        sx={{ minWidth: 'lg' }}
      >
        <DialogTitle sx={{ bgcolor: theme.palette.primary.main, color: 'white' }}>
          <Stack>
            <Typography variant="h4"> {`Select Drop Customers (${dropCust.length || 0})`}</Typography>
            <FormControl
              sx={{
                width: '100%',
                mt: 1
              }}
            >
              <Stack spacing={2} sx={{ py: 0.2 }}>
                <OutlinedInput
                  fullWidth
                  id="input-search-header"
                  placeholder="Search"
                  value={searchCustList}
                  onChange={(e) => setSearchCustList(e.target.value)}
                  sx={{
                    '& .MuiOutlinedInput-input': {
                      p: '10.5px 0px 12px'
                    },
                    bgcolor: 'white'
                  }}
                  startAdornment={
                    <InputAdornment position="start">
                      <SearchOutlined style={{ fontSize: 'small' }} />
                    </InputAdornment>
                  }
                  endAdornment={
                    <IconButton
                      sx={{ visibility: searchCustList ? 'visible' : 'hidden' }}
                      onClick={() => {
                        setSearchCustList('');
                      }}
                    >
                      <ClearIcon />
                    </IconButton>
                  }
                  autoComplete="off"
                />
              </Stack>
            </FormControl>
          </Stack>
        </DialogTitle>
        <Divider />
        <DialogContent sx={{ p: 2.5 }}>
          {customerlist.length == 0 ? (
            <Stack spacing={2} direction={'row'} alignItems={'center'} justifyContent={'center'} sx={{ minHeight: 600, maxHeight: 600 }}>
              <Empty />
            </Stack>
          ) : (
            <Stack spacing={2} sx={{ minHeight: 600, maxHeight: 600 }}>
              {customerlist &&
                customerlist.map((customer, index) => (
                  <FormGroup key={index}>
                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={dropCust.some((cust) => cust.customerid === customer.customerid)} // Set the checked state of the checkbox based on whether the customer is in `dropCust`
                          onChange={(event) => handleCheckboxChange(event, customer)}
                        />
                      }
                      label={
                        <div style={{ width: '100%' }}>
                          <Typography variant="subtitle1" sx={{ textAlign: 'left' }}>
                            {`${customer.firstname} (${customer.contactno})`}
                          </Typography>

                          <Typography variant="body2" color="secondary" sx={{ textAlign: 'left' }}>
                            {customer.address}
                          </Typography>
                        </div>
                      }
                    />
                  </FormGroup>
                ))}
            </Stack>
          )}
        </DialogContent>
        <Divider />
        <DialogActions sx={{ p: 2.5 }}>
          <Button
            color={dropCust.length == 0 ? 'error' : 'primary'}
            variant="outlined"
            sx={{
              '&:hover': {
                bgcolor: dropCust.length == 0 ? 'red' : theme.palette.primary.main,
                color: 'white'
              }
            }}
            onClick={() => {
              setIsCustomerOpen(false);
            }}
          >
            {dropCust.length == 0 ? 'Close' : 'Continue'}
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
};

export default MultipleOrders;
