import React, {useState, useEffect} from "react";
import { useDispatch } from "react-redux";
import { transRoutesSlice } from "../../store";
import RouteCard from "./RouteCard";
import { Modal, Button } from "react-bootstrap";
import { CUSTOMER_TYPE, PERSONAL_ROUTE_STATUS, PICKUP_STATUS } from "../../shared";
import { AuthService } from "../../services";
import moment from 'moment';

const RoutesSection = ({transRoutes, copyList, sectionName, drivers, vehicles, canAddNew, addText, copyText, redirect, routeType, isTemplate, templateId, showCheckedInText = true, showRouteHeaderButtons = false, clearAllRoutesAction = null}) => {
  const [showCopyModal, setShowCopyModal] = useState(false);
  const [routesOptions, setRouteOptions] = useState([]);
  const [newRoute, setNewRoute] = useState(undefined);
  const [newName, setNewName] = useState('');
  const [seniors, setSeniors] = useState([]);
  const dispatch = useDispatch();
  const { createRoute } = transRoutesSlice.actions;
  const params = new URLSearchParams(window.location.search);
  const scheduleDate = params.get('dateSchedule');

  const normalizeCustomerType = (value) => `${value || ''}`.trim().toLowerCase().replace(/\s+/g, '_');
  const isMemberLikeType = (value) => {
    const normalizedType = normalizeCustomerType(value);
    return normalizedType === '' || [CUSTOMER_TYPE.MEMBER, CUSTOMER_TYPE.SELF_PAY].includes(normalizedType);
  };
  const isVisitorType = (value) => normalizeCustomerType(value) === CUSTOMER_TYPE.VISITOR;

  useEffect(() => {
    const getSeniors = () => {
      const seniors = [];
      if (transRoutes) {
        for (const transRoute of transRoutes) {
          for (const customer of transRoute.route_customer_list) {
            const customerId = customer?.customer_id;
            const hasSameCustomer = seniors.some((item) => item?.customer_id === customerId);
            if (!hasSameCustomer && customer.customer_pickup_status !== PICKUP_STATUS.SCHEDULE_ABSENT && customer.customer_route_status !== PERSONAL_ROUTE_STATUS.DISABLED) {
              seniors.push(customer);
            }
          }
        }
      }
      
      setSeniors(seniors);
    }
    getSeniors();
  }, [transRoutes]);

  const openCopyModal = () => {
    setRouteOptions(copyList);
    setShowCopyModal(true);
  }

  const closeCopyModal = () => {
    setRouteOptions([]);
    setNewRoute(undefined);
    setNewName('');
    setShowCopyModal(false);
  }

  const saveRoute = () => {
    if (newRoute && newName) {
      const payload = Object.assign({}, copyList.find((item) => item.id === newRoute), { type: routeType, name: newName});
      delete payload.id;
      const customers = payload.route_customer_list.slice().sort((a, b) => b.customer_pickup_order - a.customer_pickup_order);
      let n = 0;
      for (let i=0; i< customers.length -1 ; i++) {
        if (i === 0) {
          customers[i] = Object.assign({}, customers[i], {customer_pickup_order_new: n});
        }
        if (customers[i+1].customer_pickup_order === customers[i].customer_pickup_order) {
          customers[i+1] = Object.assign({}, customers[i+1], {customer_pickup_order_new: n});
        } else {
          n++;
          customers[i+1] = Object.assign({}, customers[i+1], {customer_pickup_order_new: n});
        }
      }
      const customersPayload = customers.map(customer => {
        let newCustomer = {
          ...customer,
          customer_pickup_order: customer.customer_pickup_order_new
        }
        delete newCustomer.customer_pickup_order_new;
        return newCustomer;
      });
      const finalPayload = Object.assign({}, payload, {route_customer_list: customersPayload});
      const fetchParam = scheduleDate ? { fetchDate: moment(scheduleDate).format('MM/DD/YYYY') } : {fetchTomorrow: true};
      dispatch(createRoute(Object.assign({}, {data: finalPayload}, fetchParam)));
      closeCopyModal();
    }
  }

  


  return (
    <>
      <div
        className={`text-primary ${canAddNew ? 'mb-2' : ''} d-flex align-items-center ${showRouteHeaderButtons ? 'justify-content-start' : 'justify-content-between'}`}
        style={showRouteHeaderButtons ? { gap: '12px', flexWrap: 'wrap' } : {}}
      >
        <h6 className={`${showRouteHeaderButtons ? 'me-1' : 'me-4'} mb-0`}>
          {`${sectionName}: `} <span className="route-stats">{ 
            (sectionName.includes('Inbound') ||
            sectionName.includes('Outbound')) &&
            (`${seniors.filter(item => isMemberLikeType(item?.customer_type) && ![PERSONAL_ROUTE_STATUS.UNEXPECTED_ABSENT, PERSONAL_ROUTE_STATUS.SCHEDULED_ABSENT].includes(item?.customer_route_status))?.length} Members   ${seniors.filter(item=> isVisitorType(item?.customer_type) && ![PERSONAL_ROUTE_STATUS.UNEXPECTED_ABSENT, PERSONAL_ROUTE_STATUS.SCHEDULED_ABSENT].includes(item?.customer_route_status))?.length} Visitors${sectionName.includes('Inbound') && showCheckedInText ? ` ${seniors.filter(item => item?.customer_route_status === PERSONAL_ROUTE_STATUS.IN_CENTER)?.length} checked in` : ''}`)}</span>
        </h6>
        <div className="d-flex align-items-center" style={{ gap: '10px' }}>
          {canAddNew && (
            showRouteHeaderButtons ? (
              <button className="btn btn-outline-secondary" onClick={() => { if (routeType) {redirect(routeType)} else {redirect()}}}>
                {addText}
              </button>
            ) : (
              <small className="me-4" onClick={() => { if (routeType) {redirect(routeType)} else {redirect()}}}>
                <a>{addText}</a>
              </small>
            )
          )}
          {copyText && (
            showRouteHeaderButtons ? (
              <button className="btn btn-outline-secondary" onClick={() => {openCopyModal()}}>
                {copyText}
              </button>
            ) : (
              <small onClick={() => {openCopyModal()} }>
                <a>{copyText}</a>
              </small>
            )
          )}
          {clearAllRoutesAction && showRouteHeaderButtons && (
            <button className="btn btn-outline-secondary" onClick={clearAllRoutesAction}>
              Clear All Routes
            </button>
          )}
        </div>
      </div>
      {
        transRoutes && (<>
          <div className="all-routes-container">
            {
              transRoutes.map((r) => Object.assign({}, r, {vehicleNumber: vehicles?.find((v) => r.vehicle === v.id)?.vehicle_number || 0})).sort((a, b) => a?.vehicleNumber - b?.vehicleNumber).map((route, index) => <div key={route.id} className="route-card-container"><RouteCard routeIndex={index} transRoute={route} drivers={drivers} vehicles={vehicles} isTemplate={isTemplate} templateId={templateId}/></div>)
            }
          </div>
        </>)
      }
      {
        AuthService.canViewDrivers() && !transRoutes && drivers && (<>
          <div className="list row">
            {
              drivers.map((driver) => <div key={driver.id} className="col-md-3 col-sm-6 col-xs-12"><RouteCard driver={driver}/></div>)
            }
          </div>
        </>)
      }
      {
        AuthService.canViewVechiles() && !transRoutes && vehicles && (<>
          <div className="list row">
            {
              vehicles.map((vehicle) => <div key={vehicle.id} className="col-md-3 col-sm-6 col-xs-12"><RouteCard vehicle={vehicle}/></div>)
            }
          </div>
        </>)
      }
      <Modal show={showCopyModal} onHide={() => closeCopyModal()}>
        <Modal.Header closeButton>
          <Modal.Title>Copy Route</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <>
            <div className="mb-4">Select an Existed Route: <select value={newRoute} onChange={(e) => {setNewRoute(e.currentTarget.value)}}>
              <option value=""></option>
              {routesOptions.map((item) => <option key={item.id} value={item.id}>{item.name}</option>)}
            </select></div>
            <div>Type in New Route Name: <input type="text" value={newName} onChange={(e) => {setNewName(e.currentTarget.value)}} /></div>
          </>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => closeCopyModal()}>
            Close
          </Button>
          <Button variant="primary" onClick={() => saveRoute()}>
            Save Route
          </Button>
        </Modal.Footer>
      </Modal>
    </>
    
  );
};

export default RoutesSection;