import React, { useState, useEffect } from "react";
import { useSelector,useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import { selectAllRoutes, transRoutesSlice, vehicleSlice, selectTomorrowAllRoutes, selectAllActiveDrivers, selectAllActiveVehicles, transRouteTemplatesSlice,  selectAllActiveRouteTemplates, selectInboundRouteTemplates, selectOutboundRouteTemplates } from "./../../store";
import { Modal, Button, Breadcrumb, Tabs, Tab  } from "react-bootstrap";
import RouteCustomerEditor from "./RouteCustomerEditor";
import { AuthService } from "../../services";
import moment from 'moment';

const CreateRoute = () => {
  const params = new URLSearchParams(window.location.search);
  const allRoutes = useSelector(selectAllRoutes);
  const tomorrowRoutes = useSelector(selectTomorrowAllRoutes);
  const drivers = useSelector(selectAllActiveDrivers);
  const vehicles = useSelector(selectAllActiveVehicles);
  const routeTemplates = useSelector(selectAllActiveRouteTemplates);
  const inboundTemplates = useSelector(selectInboundRouteTemplates);
  const outboundTemplates = useSelector(selectOutboundRouteTemplates);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { createRoute} = transRoutesSlice.actions;
  const { updateVehicle} = vehicleSlice.actions;
  const { createRouteTemplate } = transRouteTemplatesSlice.actions;
  const [routeName, setRouteName] = useState('');
  const [newDriver, setNewDriver] = useState('');
  const [newVehicle, setNewVehicle] = useState('');
  // Only accept valid route types from URL param, default to 'inbound'
  const urlRouteType = params.get('type');
  const [newRouteType, setNewRouteType] = useState(
    urlRouteType === 'inbound' || urlRouteType === 'outbound' ? urlRouteType : 'inbound'
  );
  const [showAddCheckItem, setShowAddCheckItem] = useState(false);
  const [showCopyCheckItem, setShowCopyCheckItem] = useState(false);
  const [newChecklistItems, setNewChecklistItems] = useState([]);
  const [selectedRouteChecklistToCopy, setSelectedRouteChecklistToCopy] = useState({});
  const currentVehicle = vehicles.find((vehicle) => vehicle.id === newVehicle);
  const [newCustomerList, setNewCustomerList] = useState([]);
  const [saveAsTemplate, setSaveAsTemplate] = useState(false);
  const [useRouteTemplate, setUseRouteTemplate] = useState(undefined);
  const [currentRoute, setCurrentRoute] = useState(undefined);
  const [errorMessage, setErrorMessage] = useState(undefined);
  const [disableSave, setDisableSave] = useState(false);

  useEffect(() => {
    if (!AuthService.canAddOrEditRoutes()) {
      window.alert('You haven\'t login yet OR this user does not have access to this page. Please change an admin account to login.')
      AuthService.logout();
      navigate(`/login`);
    }
  }, []);

  useEffect(() => {
    if (useRouteTemplate) {
      const currentTemplate = routeTemplates.find((template) => template.id === useRouteTemplate);
      setRouteName(currentTemplate.name);
      setNewDriver(currentTemplate.driver);
      setNewVehicle(currentTemplate.vehicle);
      setNewRouteType(currentTemplate.type);
      setNewCustomerList(currentTemplate.route_customer_list);
      setCurrentRoute(currentTemplate);
    } else {
      setRouteName('');
      setNewDriver('');
      setNewVehicle('');
      // Only accept valid route types from URL param, default to 'inbound'
      const urlType = params.get('type');
      setNewRouteType(urlType === 'inbound' || urlType === 'outbound' ? urlType : 'inbound');
      setNewCustomerList([]);
    }
    setErrorMessage(undefined);
  }, [useRouteTemplate])

  const redirectToSchedule = () => {
    const date =params.get('date');
    const searchParams = date && date!=='tomorrow'? `?dateSchedule=${date}` : '';
    navigate(`/trans-routes/schedule${searchParams}`);
  }

  const redirectToDashboard = () => {
    const date =params.get('date');
    navigate(`/trans-routes/dashboard?dateSchedule=${date}`);
  }

  const goToTemplateList = () => {
    navigate(`/trans-routes/templates${params.get('type')?`?type=${params.get('type')}`: ''}${params.get('date')? `&date=${params.get('date')}` : ''}`);
  }

  const validateRoute = () => {
    const errors = [];
    
    // Required fields validation
    if (!routeName || routeName.trim() === '') {
      errors.push('Route Name');
    }
    if (!newRouteType || newRouteType === '') {
      errors.push('Route Type');
    }
    if (!newDriver || newDriver === '') {
      errors.push('Driver');
    }
    if (!newVehicle || newVehicle === '') {
      errors.push('Vehicle');
    }
    
    if (errors.length > 0) {
      window.alert(`Please fill in the following required fields:\n${errors.join('\n')}`);
      return false;
    }
    return true;
  };

  const saveRoute = () => {
    if (!disableSave) {
      if (!validateRoute()) {
        return;
      }
      setDisableSave(true);
      const now = new Date();
      let scheduleDate =  ((now.getMonth() > 8) ? (now.getMonth() + 1) : ('0' + (now.getMonth() + 1))) + '/' + ((now.getDate() > 9) ? now.getDate() : ('0' + now.getDate())) + '/' + now.getFullYear();
      if (params.get('date') === 'tomorrow') {
        now.setDate(now.getDate() + 1);
        scheduleDate =  ((now.getMonth() > 8) ? (now.getMonth() + 1) : ('0' + (now.getMonth() + 1))) + '/' + ((now.getDate() > 9) ? now.getDate() : ('0' + now.getDate())) + '/' + now.getFullYear();
      } else {
        if (params.get('date')) {
          scheduleDate = moment(params.get('date')).format('MM/DD/YYYY');
        }
      }
      
      //const scheduleDate = ((now.getMonth() > 8) ? (now.getMonth() + 1) : ('0' + (now.getMonth() + 1))) + '/' + ((now.getDate() > 9) ? now.getDate() : ('0' + now.getDate())) + '/' + now.getFullYear();
      const data = Object.assign({}, {name: routeName, route_customer_list: newCustomerList, driver: newDriver, vehicle: newVehicle, type: newRouteType, schedule_date: scheduleDate, start_mileage: currentVehicle.mileage });
      const payload = {
        data
      };
      if (params.get('date') === 'tomorrow') {
        payload.fetchTomorrow = true;
      } else {
        if (params.get('date')) {
          payload.fetchDate = moment(params.get('date')).format('MM/DD/YYYY');
        }
        payload.fetchToday = true;
      }
      if (saveAsTemplate) {
        const templatePayload = Object.assign({}, {
          name: routeName, 
          route_customer_list: newCustomerList, 
          driver: newDriver, 
          vehicle: newVehicle, 
          type: newRouteType,
          status: 'active'
        });
        dispatch(createRouteTemplate({data: templatePayload}))
      }
      dispatch(createRoute(payload));
      setTimeout(() => {
        setDisableSave(false);
        if (params.get('date')) {
          redirectToSchedule();
        } else {
          redirectToDashboard();
        }
      }, 2000)
    }
    
    
  }

  const addItemToArray = () => {
    const arr = [...newChecklistItems, ''];
    setNewChecklistItems(arr);
  }

  const saveChecklistItems = () => {
    const data = Object.assign({}, currentVehicle, {checklist: newChecklistItems});
    dispatch(updateVehicle({ id: currentVehicle.id, data }));
    setShowAddCheckItem(false);
  }

  const copyChecklistItems = () => {
    const data = Object.assign({}, currentVehicle, {checklist: vehicles.find(vehicle => vehicle.id === selectedRouteChecklistToCopy.vehicle)?.checklist});
    dispatch(updateVehicle({ id: currentVehicle.id, data }));
    setShowCopyCheckItem(false);
  }

  const closeAddCheckItemModal = () => {
    setNewChecklistItems([])
    setShowAddCheckItem(false);
  }

  const showAddCheckItemModal = () => {
    setNewChecklistItems(currentVehicle.checklist)
    setShowAddCheckItem(true);
  }

  const closeCopyCheckItemModal = () => {
    setSelectedRouteChecklistToCopy({});
    setShowCopyCheckItem(false);
  }

  const showCopyCheckItemModal = () => {
    setShowCopyCheckItem(true);
  }
  
  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/trans-routes/dashboard">Transportation</Breadcrumb.Item>
          <Breadcrumb.Item href="/trans-routes/dashboard">
            Transportation Routes
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            Create New Route
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
             Create New Route <button className="btn btn-link btn-sm" onClick={() => {redirectToDashboard()}}>Back</button>
           </h4> 
        </div>
      </div>

      <div className="app-main-content-list-container form-page">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="routeOverview" id="route-view-tab">
						<Tab eventKey="routeOverview" title="Route Information">
              <div className="multi-columns-container">
                <div className="column-container">
                  <div className="column-card">
                    <h6 className="text-primary">Route Details</h6>
                   
                      {/* {((params.get('type')==="inbound" && inboundTemplates?.length>0) ||(params.get('type')==="outbound" && outboundTemplates?.length>0)) &&  <div className="app-main-content-fields-section"><div className="me-4">
                        <div className="field-label">
                          Use Existed Template
                        </div>
                        <select value={useRouteTemplate} onChange={e => setUseRouteTemplate(e.currentTarget.value)}>
                          <option value={''}></option>
                          {
                            (params.get('type') === 'inbound' && inboundTemplates?.length>0) ? inboundTemplates.map(template => <option value={template.id} key={template.id}>{template.name}</option>) : ((params.get('type') === 'outbound' && outboundTemplates?.length>0) ? outboundTemplates.map(template => <option value={template.id} key={template.id}>{template.name}</option>): <></>)
                          }
                        </select>

                      </div></div>} */}
                    
                    <div className="app-main-content-fields-section">
                      <div className="me-4">
                        <div className="field-label">Route Name
                          <span className="required">*</span>
                        </div>
                        <input type="text" value={routeName || ''} onChange={e => setRouteName(e.target.value)}/>
                      </div>
                      <div className="me-4">
                        <div className="field-label">Vehicle
                          <span className="required">*</span>
                        </div>
                        <select value={newVehicle} onChange={e => setNewVehicle(e.target.value)}>
                          <option value=""></option>
                          {vehicles.map((vehicle) => (<option key={vehicle.id} value={vehicle.id}>{vehicle.vehicle_number}</option>))}
                        </select>
                      </div>
                    </div>
                    <div className="app-main-content-fields-section">
                      <div className="me-4">
                        <div className="field-label">Driver
                          <span className="required">*</span>
                        </div>
                        <select value={newDriver} onChange={e => setNewDriver(e.target.value)}>
                          <option value=""></option>
                          {drivers.map((driver) => <option key={driver.id} value={driver.id}>{driver.name}</option>)}
                        </select>
                      </div>
                      <div className="me-4">
                        <div className="field-label">Route Type
                          <span className="required">*</span>
                        </div>
                        <select value={newRouteType} onChange={e => setNewRouteType(e.target.value)}>
                          <option value="inbound">Inbound</option>
                          <option value="outbound">Outbound</option>
                        </select>
                      </div>
                    </div>
                    {/* <div className="app-main-content-fields-section">
                      Save As Template: <input type="checkbox" value={saveAsTemplate} checked={saveAsTemplate === true} onChange={e => setSaveAsTemplate(!saveAsTemplate)}/>
                    </div> */}
                  </div>
                  <div className="column-card adjust">
                    <div className="col-md-12 mb-4">
                      <RouteCustomerEditor currentRoute={currentRoute} setNewCustomerList={setNewCustomerList}></RouteCustomerEditor>
                    </div>
                  </div>
                  <div className="list row mb-5">
                    <div className="col-md-12 col-sm-12 col-xs-12">
                      
                      <button className="btn btn-default btn-sm float-right" onClick={() => redirectToDashboard()}> Cancel </button>
                      <button className="btn btn-primary btn-sm float-right" disabled={disableSave} onClick={() => saveRoute()}> Save </button>
                    </div>
                    {errorMessage && <div className="col-md-12 col-sm-12 col-xs-12 alert alert-danger mt-4">{errorMessage}</div>}
                    
                  </div>
                </div>
                <div className="column-container">
                  { newVehicle && newVehicle !== '' && <div className="column-card mb-4">
                    <h6 className="text-primary">Vehicle Information</h6>
                    <div className="app-main-content-fields-section short">
                      <div className="field-body">
                        <div className="field-label">Vehicle Number</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.vehicle_number}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Seating Capacity</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.capacity}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Mileage</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.mileage}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Make</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.make}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Model</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.model}</div>
                      </div>
                    </div>
                    <div className="app-main-content-fields-section short">
                      <div className="field-body">
                        <div className="field-label">License Plate</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.tag}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Year</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.year}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">GPS ID</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.gps_tag}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">EZPass</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.ezpass}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Vin</div>
                        <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.vin || ''}</div>
                      </div>
                    </div>
                  </div>}
                  {
                    newDriver && newDriver !== '' && <div className="column-card">
                      <h6 className="text-primary">Driver Information</h6>
                      <div className="text-primary">Personal Details</div>
                      <div className="app-main-content-fields-section short">
                        <div className="field-body">
                          <div className="field-label">Driver Name</div>
                          <div className="field-value">{drivers.find(item => item.id === newDriver)?.name}</div>
                        </div>
                        <div className="field-body">
                          <div className="field-label">Preferred Name</div>
                          <div className="field-value">{drivers.find(item => item.id === newDriver)?.name_cn}</div>
                        </div>
                        <div className="field-body">
                          <div className="field-label">Job Title</div>
                          <div className="field-value">{drivers.find(item => item.id === newDriver)?.title}</div>
                        </div>
                        <div className="field-body">
                          <div className="field-label">Job Status</div>
                          <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.employment_status}</div>
                        </div>
                        
                      </div>
                      <div className="app-main-content-fields-section short">
                        <div className="field-body">
                          <div className="field-label">Driver Capacity</div>
                          <div className="field-value">{drivers.find(item => item.id === newDriver)?.driver_capacity}</div>
                        </div>
                        <div className="field-body">
                          <div className="field-label">Phone Number</div>
                          <div className="field-value">{drivers.find(item => item.id === newDriver)?.phone}</div>
                        </div>
                        <div className="field-body">
                          <div className="field-label">Email</div>
                          <div className="field-value">{vehicles.find(item => item.id === newVehicle)?.email}</div>
                        </div>
                        
                      </div>
                    </div>
                  }
                </div>
              </div>
            </Tab>
          </Tabs>
        </div>
      </div>

      <Modal show={showAddCheckItem} onHide={() => closeAddCheckItemModal()}>
        <Modal.Header closeButton>
          <Modal.Title>Add New Checklist Item</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <>
            {newChecklistItems.map((item, index) => (<div className="mb-4" key={index}><input type="text" value={item} onChange={(e) => setNewChecklistItems([...newChecklistItems].map((a, index1) => {if (index1 === index) {return e.target.value;} return a;}))}/>
            <button className="btn btn-link btn-sm" onClick={(e) => setNewChecklistItems([...newChecklistItems].filter((value, index1) => index1 != index))}>Remove</button>
            </div>))}
            <button className="btn btn-link" onClick={() => addItemToArray()}>+Add New Item</button>
          </>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => closeAddCheckItemModal()}>
            Close
          </Button>
          <Button variant="primary" onClick={() => saveChecklistItems()}>
            Save Checklist Items
          </Button>
        </Modal.Footer>
      </Modal>
      <Modal show={showCopyCheckItem} onHide={() => closeCopyCheckItemModal()}>
        <Modal.Header closeButton>
          <Modal.Title> Click on Route to Select</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <>
           {[...allRoutes, ...tomorrowRoutes].map((route) => {
             return (<div className={`card-container ${route.id === selectedRouteChecklistToCopy.id ? 'selected': ''}`} key={route.id} onClick={() => setSelectedRouteChecklistToCopy(route)}>
               <div>{route.name}</div>
               <div>
                  {vehicles.find((a) => a.id === route.vehicle)?.checklist?.map((item, index) => <small key={index} className="me-2">{item}</small>)}
               </div>
             </div>);
           })}
          </>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={() => closeCopyCheckItemModal()}>
            Close
          </Button>
          <Button variant="primary" onClick={() => copyChecklistItems()}>
            Copy Checklist Items
          </Button>
        </Modal.Footer>
      </Modal>
    </>
    
  );
};

export default CreateRoute;