import React, {useState, useEffect} from "react";
// import { useDispatch } from "react-redux";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
// import { customerSlice } from "./../../store";
import { AuthService, CustomerService, EventsService, ResourceService } from "../../services";
import Select from 'react-select';
import { Button, Modal } from "react-bootstrap";
import DatePicker from "react-datepicker";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";

const UpdateEvent = () => {
  const navigate = useNavigate();
  const urlParams = useParams();
  const [searchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState(searchParams.get('tab') || 'eventInfo');
  const [currentEvent, setCurrentEvent] =  useState(undefined);
	const [medicalResource, setMedicalResource] = useState(undefined);
  const [currentResource, setCurrentResource] = useState(undefined);
  const [resources, setResources] = useState([]);
  const [filteredResources, setFilteredResources] = useState([]);
  const [resourceType, setResourceType] = useState('');
  const [customers, setCustomers] = useState([]);
  const [customerName, setCustomerName] = useState(undefined);
  const [currentCustomer, setCurrentCustomer] = useState(undefined);
  const [startTime, setStartTime] = useState('');
  const [title, setTitle] = useState('');
	const [description, setDescription] = useState('');
  const [newPatient, setNewPatient] = useState('');
  const [confirmed, setConfirmed] = useState('');
  const [fasting, setFasting] = useState('');
  const [interpreter, setInterpreter] = useState('');
  const [docOrder, setDocOrder] = useState('');
  const [disability, setDisability] = useState('');
  const [needId, setNeedId] = useState('');
  const [needMedicationList, setNeedMedicationList] = useState('');
  const [disabilitySupport, setDisabilitySupport] = useState('');
  const [notes, setNotes] = useState('');
  const [color, setColor] = useState('');
  const [reason, setReason] = useState('');
  const [otherRequirement, setOtherRequirement] = useState('');
  const [todayEvents, setTodayEvents] = useState([]);
  const [transportationInfo, setTransportationInfo] = useState(undefined);
  const [hideCreateFields, setHideCreateFields] = useState(false);
  const [timeData, setTimeData] = useState([]);
  const [transMethod, setTransMethod] = useState('');
  const [showResourceModal, setShowResourceModal] = useState(false);
  const [keyword, setKeyword] = useState('');
  
  const isSite3 = window.location.hostname.includes('worldshine3.mayo.llc') || window.location.hostname.includes('site3');
  const params = new URLSearchParams(window.location.search);
  const redirectToCalendar = () => {
		navigate(`/medical/events/calendar`);
  }

  const redirectTo = (id) => {
    if (params.get('from') === 'calendar') {
      redirectToCalendar()
    } else {
      if (params.get('from') === 'create') {
        redirectToCalendar()
      } else {
        if (params.get('event')) {
          redirectToCalendar()
        } else {
          navigate(`/medical/events/list`);
        }
      }
    }
  }

  const redirectToView = () => {
		navigate(`/medical/events/${urlParams.id}`);
  }

  const validateEvent = () => {
    const errors = [];
    
    // Required fields validation
    if (!currentCustomer || !currentCustomer.id) {
      errors.push('Customer');
    }
    if (!currentResource || !currentResource.id) {
      errors.push('Provider');
    }
    if (!startTime) {
      errors.push('Appointment Time');
    }
    
    if (errors.length > 0) {
      window.alert(`Please fill in the following required fields:\n${errors.join('\n')}`);
      return false;
    }
    return true;
  };

  const saveEvent = () => {
    if (!validateEvent()) {
      return;
    }
    
    let newEventDataClientAndResource = {};
    let newEventClientAndResource = {};
    if (currentCustomer) {
      newEventDataClientAndResource = Object.assign({}, newEventDataClientAndResource, {
        customer: currentCustomer.id,
        client_name: currentCustomer.name,
        client_pharmacy: currentCustomer.pharmacy,
        client_pcp: currentCustomer.care_provider,
        client_birth_date: currentCustomer.birth_date,
        client_seating: currentCustomer.seating
      });
      newEventClientAndResource = Object.assign({}, newEventClientAndResource, {
        target_type: currentCustomer.type,
        target_uuid: currentCustomer.id,
        target_name: currentCustomer.name
      })
    }
    if (currentResource) {
      newEventDataClientAndResource = Object.assign({}, newEventDataClientAndResource, {
        resource: currentResource.id,
        resource_type: currentResource.type,
        resource_name: currentResource.name,
        resource_phone: currentResource.phone,
        resource_contact: currentResource.contact,
        resource_address: currentResource.address,
        resource_city: currentResource.city,
        resource_state: currentResource.state,
      });
      newEventClientAndResource = Object.assign({}, newEventClientAndResource, {
        source_type: currentResource.type,
        source_uuid: currentResource.id,
        source_name: currentResource.name,
      })
    }
    
    const newEventData = {
      ...currentEvent.data,
      // legacy fields end
      // We still wanna keep the legacy fields below
      new_patient: newPatient,
      confirmed: confirmed,
      fasting: fasting,
      interpreter: interpreter,
      doc_order: docOrder,
      need_id: needId,
      need_med_list: needMedicationList,
      notes: notes,
      reason: reason,
      other: otherRequirement,
      disability: disability,
      disability_support: disabilitySupport,
      trans_method: transMethod,
      ...newEventDataClientAndResource
    }
    
    const newEvent = {
      ...currentEvent,
      data: newEventData,
      title: title,
      descrption: description,
      color: color,
      notes: notes,
      start_time: new Date(startTime),
      stop_time: new Date(startTime),
      edit_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
      edit_date: new Date(),
      edit_history: currentEvent?.edit_history? [...currentEvent.edit_history, { employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }] : [{ employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }],
      ...newEventClientAndResource
    }
    if (params.get('event')) {
      if (currentCustomer && currentResource)
      EventsService.createNewEvent(newEvent).then(data => redirectTo());
    } else {
      if (params.get('from') === 'create') {
        if (currentCustomer && currentResource) {
          EventsService.updateEvent(urlParams.id, newEvent).then(data => redirectTo());
        }
      } else {
        EventsService.updateEvent(urlParams.id, newEvent).then(data => redirectTo());
      }
    }
  };

  const filterResourceListByKeyword = (item) => {
    if (keyword.length > 0) {
      const newKeyword = keyword.toLowerCase();
      return item?.name.toLowerCase()?.includes(newKeyword) || item?.address?.toLowerCase()?.includes(newKeyword) || item?.specialty?.toLowerCase()?.includes(newKeyword);
    } else {
      return true;
    }
  }

  const filterResourcesListBySpecialty = (item) => {
    if (resourceType.length > 0) {
      return item?.type === resourceType;
    } else {
      return true;
    }
  }
  

  useEffect(() => {
    if (!AuthService.canAccessLegacySystem()) {
      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`);
    }
    if (params.get('from') === 'create') {
      setHideCreateFields(true);
    }
    Promise.all([ResourceService.getAll(), CustomerService.getAllCustomers(), EventsService.getTimeData()]).then(([resourcesData, customersData, timeDatas]) => {
      setResources(resourcesData.data);
      setFilteredResources(resourcesData.data);
      setCustomers(customersData.data);
      setTimeData(timeDatas.data);
      if (!currentEvent) {
        if (params.get('event')) {
          setCurrentEvent(JSON.parse(params.get('event')));
        } else {
          EventsService.getEvent(urlParams.id).then(eventData => {
            setCurrentEvent(eventData.data);
            EventsService.getAllEvents({date: EventsService.formatDate(new Date(eventData.data.start_time))}).then(eventsData => {
              setTodayEvents(eventsData.data)
              const targetedEvent = eventsData.data.find(item => item.id === urlParams.id)
              setTransportationInfo(EventsService.getTransportationInfo(eventsData.data, targetedEvent, timeData));
            })
          })
        }
        
        
      }
    })
  }, []);

  useEffect(() => {
    const newResources = [...resources];
    
    if (resourceType && resourceType !== '') {
      setFilteredResources(newResources?.filter(item => item.type === resourceType));
    }
  }, [resourceType])

  const onCustomerChange = (selectedCustomer) => {
    setCustomerName(selectedCustomer);
    setCurrentCustomer(customers.find(customer => customer.id === selectedCustomer.value))
  }

  const onResourceChange = (selectedResource) => {
    setMedicalResource(selectedResource);
    setCurrentResource(resources.find(resource => resource.id === selectedResource.value));
  }

  

  useEffect(() => {
    if (currentEvent) {
      if (!currentEvent.data.customer) {
        CustomerService.getClient(currentEvent.target_uuid).then((data) => {
          const legacyClient = data?.data;
          const mappingCustomer = customers.find((item) => item.email === legacyClient.email && item.username === legacyClient.username);
          setCustomerName({value: mappingCustomer.id, label: mappingCustomer.name});
          setCurrentCustomer(mappingCustomer);
          
        });
      } else {
        setCustomerName({value: currentEvent.data.customer, label: customers.find(item => item.id === currentEvent.data.customer)?.name});
        setCurrentCustomer(customers.find(item => item.id === currentEvent.data.customer));
      }
      setMedicalResource({ value: currentEvent.data.resource || currentEvent.source_uuid, label: resources.find(item => item.id === currentEvent.source_uuid)?.name });
      setCurrentResource(resources.find(item => item.id === currentEvent.source_uuid));
      setStartTime(new Date(currentEvent.start_time));
      setTitle(currentEvent.title);
      setColor(currentEvent.color);
      setDescription(currentEvent.description);
      setNewPatient(currentEvent.data.new_patient);
      setConfirmed(currentEvent.data.confirmed);
      setFasting(currentEvent.data.fasting);
      setInterpreter(currentEvent.data.interpreter);
      setDocOrder(currentEvent.data.doc_order);
      setDisability(currentCustomer?.disability ? 'yes' : (currentEvent.data.disability));
      setDisabilitySupport(currentEvent.data.disability_support);
      setNeedId(currentEvent.data.need_id);
      setNeedMedicationList(currentEvent.data.need_med_list);
      setNotes(currentEvent.data.notes);
      setReason(currentEvent.data.reason);
      setOtherRequirement(currentEvent.data.other);
      setTransMethod(currentEvent?.data?.trans_method);
    }
    
  }, [currentEvent]);

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/medical/index">Medical</Breadcrumb.Item>
          <Breadcrumb.Item href="/medical/events/list">
            Medical Appointment Information
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            { params.get('event') ? 'Create Medical Event from Request' : 'Update Medical Event'}
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>{ params.get('event') ? 'Create Medical Event from Request' : 'Update Medical Event'} <button className="btn btn-link btn-sm" onClick={() => {redirectTo()}}>Back</button></h4> 
        </div>
      </div>

      <div className="app-main-content-list-container form-page">
				<div className="app-main-content-list-func-container">
					<Tabs activeKey={activeTab} onSelect={(k) => setActiveTab(k)} id="event-tab">
						{ !hideCreateFields && <Tab eventKey="eventClientInfo" title="Appointment Customer And Time Information">
              <div className="multi-columns-container">
                <div className="column-container">
                  <div className="column-card">
                    <h6 className="text-primary">Customer And Appointment Time</h6>
                    <div className="app-main-content-fields-section">
                      <div className="me-4">
                        <div className="field-label">Customer
                          <span className="required">*</span>
                        </div>
                        <Select styles={{
                          control: (baseStyles) => ({
                            ...baseStyles,
                            width: '350px',
                            borderRadius: '8px'
                          }),
                          indicatorSeparator: () => ({
                            display: 'none'
                          }),
                          dropdownIndicator: (baseStyles) => ({
                            ...baseStyles,
                            paddingRight: '8px',
                            color: '#333',
                            '&:hover': { color: '#000' }
                          }),
                          valueContainer: (baseStyles) => ({
                            ...baseStyles,
                            height: '43px',
                            padding: '0 8px',
                          }),
                          input: (baseStyles) => ({
                            ...baseStyles,
                            margin: '0px',
                            padding: '0px',
                            height: '30px',
                            width: '290px'
                          }),
                          placeholder: (baseStyles) => ({
                            ...baseStyles,
                            fontSize: '13px'
                          }),
                          singleValue: (baseStyles) => ({
                            ...baseStyles,
                            margin: '0px',
                            fontSize: '13px'
                          })
                        }} value={customerName || ''} onChange={selectedCustomer => onCustomerChange(selectedCustomer)} options={[{value: '', label: ''}, ...customers.filter(customer => customer?.status === 'active' && customer?.type !== 'discharged').map(customer => ({
                          value: customer?.id || '',
                          label: customer?.name || ''
                        }))]}></Select>
                      </div>
                      <div className="me-4">
                        <div className="field-label">Appointment Time
                          <span className="required">*</span>
                        </div>
                        <DatePicker
                          selected={startTime}
                          onChange={setStartTime}
                          showTimeInput
                          timeInputLabel="Time:"
                          dateFormat="MM/dd/yyyy, HH:mm"
                        ></DatePicker>
                      </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={() => redirectTo()}> Cancel </button>
                        <button className="btn btn-primary btn-sm float-right" onClick={() => saveEvent()}> Save </button>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="column-container">
                  <div className="column-card">
                  {
                    currentCustomer && <>
                      <h6 className="text-primary">Customer Information</h6>
                        <div className="app-main-content-fields-section short">
                          <div className="field-body">
                            <div className="field-label">Customer Name</div> 
                            <div className="field-value">{currentCustomer?.name || ''}</div>
                          </div>
                          <div className="field-body">
                            <div className="field-label">Preferred Name</div> 
                            <div className="field-value">{currentCustomer?.name_cn || ''}</div>
                          </div>
                          <div className="field-body">
                            <div className="field-label">Pharmacy</div> 
                            <div className="field-value">{currentCustomer?.pharmacy || ''}</div>
                          </div>
                        </div>
                        <div className="app-main-content-fields-section short">
                          <div className="field-body">
                            <div className="field-label">Care Provider</div> 
                            <div className="field-value">{currentCustomer?.care_provider || ''}</div>
                          </div>
                          <div className="field-body">
                            <div className="field-label">Birthday</div> 
                            <div className="field-value">{currentCustomer?.birth_date || ''}</div>
                          </div>
                          <div className="field-body">
                            <div className="field-label">Note</div> 
                            <div className="field-value">{currentCustomer?.note || ''}</div>
                          </div>
                        </div>
                    </>
                  }
                  </div>
                </div>
              </div>
            </Tab>}
            <Tab eventKey="eventInfo" title="Medical Appointment Information">
              <div className="multi-columns-container">
                <div className="column-container">
                  <div className="column-card">
                  <h6 className="text-primary">Appointment Details</h6>
                  <div className="app-main-content-fields-section">
                    <div className="me-4">
                      <div className="field-label">Provider
                        <span className="required">*</span>
                      </div>
                      {currentResource ? 
                      (<><span>{currentResource?.name}</span> <span><button className="btn btn-link btn-sm me-2 mb-2" onClick={()=> setShowResourceModal(true)}>Update</button></span></>)  : 
                      (currentEvent?.data?.resource_name ? <><span>{currentEvent?.data?.resource_name}</span> <span><button className="btn btn-link btn-sm me-2 mb-2" onClick={()=> setShowResourceModal(true)}>Update</button></span></> : <button className="btn btn-link btn-sm me-2 mb-2" onClick={()=> setShowResourceModal(true)}>Please click here to add provider</button>)}
                    </div>
                    <div className="me-4">
                      <div className="field-label">Label
                        <span className="required">*</span>
                      </div>
                      <select value={color} onChange={e => setColor(e.target.value)}>
                        <option value=""></option>
                        {
                          EventsService.colorOptions?.map((item) => <option value={item?.value}>{item?.label}</option>)
                        }
                      </select>
                    </div>
                  </div>
                  <h6 className="text-primary">Customer Information</h6>
                  <div className="app-main-content-fields-section">
                    <div className="me-4">
                      <div className="field-label">New Patient
                      </div>
                      <select value={newPatient} onChange={e => setNewPatient(e.target.value)}>
                        <option value=""></option>
                        <option value="yes">Yes</option>
                        <option value="no">No</option>
                      </select>
                    </div>
                    <div className="me-4">
                      <div className="field-label">Doctor's Order
                      </div>
                      <select value={docOrder} onChange={e => setDocOrder(e.target.value)}>
                        <option value=""></option>
                        <option value="yes">Yes</option>
                        <option value="no">No</option>
                      </select>
                    </div>
                    <div className="me-4">
                      <div className="field-label">Fasting Required
                      </div>
                      <select value={fasting} onChange={e => setFasting(e.target.value)}>
                        <option value=""></option>
                        <option value="empty_stomach">Empty Stomach</option>
                        <option value="clear_liquid">Clear Liquid</option>
                      </select>
                    </div>
                  </div>
                  <div className="app-main-content-fields-section">
                    <div className="me-4">
                      <div className="field-label">ID Needed
                      </div>
                      <select value={needId} onChange={e => setNeedId(e.target.value)}>
                        <option value=""></option>
                        <option value="yes">Yes</option>
                        <option value="no">No</option>
                      </select>
                    </div>
                    <div className="me-4">
                      <div className="field-label">Need Medication List
                      </div>
                      <select value={needMedicationList} onChange={e => setNeedMedicationList(e.target.value)}>
                        <option value=""></option>
                        <option value="yes">Yes</option>
                        <option value="no">No</option>
                      </select>
                    </div>
                  </div>
                  <h6 className="text-primary">Assistance</h6>
                  <div className="app-main-content-fields-section">
                    <div className="me-4">
                      <div className="field-label">Language Support
                        <span className="required">*</span>
                      </div>
                      <select value={interpreter} onChange={e => setInterpreter(e.target.value)}>
                        <option value=""></option>
                        {
                          EventsService.interpreterLevelOptions?.map((item) => <option value={item?.value}>{item?.label}</option>)
                        }
                      </select>
                    </div>
                    <div className="me-4">
                      <div className="field-label">Transportation Support
                      </div>
                      <select value={transMethod} onChange={e => setTransMethod(e.target.value)}>
                        <option value=""></option>
                        {
                          EventsService.transportationTypeOptions?.map((item) => <option key={item?.value} value={item?.value}>{item?.label}</option>)
                        }
                      </select>
                    </div>
                  </div>
                  <h6 className="text-primary">Additional Information</h6>
                  <div className="app-main-content-fields-section">
                    <div className="me-4">
                      <div className="field-label">Notes
                      </div>
                      <textarea value={notes || ''} onChange={e => setNotes(e.target.value)}/> 
                    </div>
                    <div className="me-4">
                      <div className="field-label">Reason
                      </div>
                      <textarea value={reason || ''} onChange={e => setReason(e.target.value)}/>
                    </div>
                    <div className="me-4">
                      <div className="field-label">Other Requirements
                      </div>
                      <textarea value={otherRequirement || ''} onChange={e => setOtherRequirement(e.target.value)}/>
                    </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={() => redirectTo()}> Cancel </button>
                      <button className="btn btn-primary btn-sm float-right" onClick={() => saveEvent()}> Save </button>
                    </div>
                  </div>
                  </div>
                </div>
                <div className="column-container">
                  {currentResource && <div className="column-card">
                    <h6 className="text-primary">Provider Info</h6>
                    <div className="app-main-content-fields-section short">
                      <div className="field-body">
                        <div className="field-label">Name</div>
                        <div className="field-value">{currentResource?.name || currentEvent?.data?.resource_name || ''}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Specialty</div>
                        <div className="field-value">{currentResource?.specialty || ''}</div>
                      </div>
                      
                    </div>
                    <div className="app-main-content-fields-section short">
                      <div className="field-body">
                        <div className="field-label">Phone</div>
                        <div className="field-value">{currentResource?.phone || currentEvent?.data?.resource_phone || ''}</div>
                      </div>
                      <div className="field-body">
                        <div className="field-label">Contact</div>
                        <div className="field-value">{currentResource?.contact || currentEvent?.data?.resource_contact || ''}</div>
                      </div>
                    </div>
                    <div className="app-main-content-fields-section short">
                      <div className="field-body">
                        <div className="field-label">Address</div>
                        <div className="field-value">{currentResource?.address || currentEvent?.data?.resource_address || ''}</div>
                      </div>
                    </div>
                  </div>}
                </div>
                  
              </div>
            </Tab>
          </Tabs>
        </div>
      </div>
      <Modal show={showResourceModal} fullscreen={true} onHide={() => setShowResourceModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Select the Provider</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <div className="app-main-content-fields-section">
            <div className="mb-4 me-4">
              <div className="field-label">Type in Keyword to Filter</div>
              <input type="text" value={keyword} onChange={e => setKeyword(e.target.value)}/>
            </div>
            <div className="mb-4 me-4">
              <div className="field-label">Filter By Provider Type</div>
              <select value={resourceType} onChange={e => setResourceType(e.target.value)}>
                <option value=""></option>
                <option value="doctor">Doctor</option>
                <option value="pharmacy">Pharmacy</option>
                <option value="hospital">Hospital</option>
                <option value="surgical center">Surgical Center</option>
                <option value="government agency">Government Agency</option>
                <option value="other">Other</option>
              </select>
            </div>
          </div>
          <table className="personnel-info-table mb-4"> 
            <thead>
              <tr className="sortable-header">
                <th>Name</th>
                <th>Specialty</th>
                <th>Address</th>
                <th>Office Name</th>
                <th>Branch Name</th>
                <th>City</th>
                <th>State</th>
                <th>Zipcode</th>
                <th></th>
              </tr>
              
            </thead>
            <tbody>
              {
                resources?.filter(r=> r.status === 'active')?.filter((item => filterResourceListByKeyword(item)))?.filter(item => filterResourcesListBySpecialty(item)).map(resource => <tr key={resource.id}>
                  <td>{`${resource?.name || ''}${resource?.name ? '-': ''}${resource?.name_original || ''}${resource?.name_original ? '-': ''}${resource?.name_branch || ''}`}</td>
                  <td>{resource?.specialty}</td>
                  <td>{resource?.address}</td>
                  <td>{resource?.name_original}</td>
                  <td>{resource?.name_branch}</td>
                  <td>{resource?.city}</td>
                  <td>{resource?.state}</td>
                  <td>{resource?.zipcode}</td>
                  <td style={{'min-width': '220px'}}>{ resource?.id === currentResource?.id ? 'Selected' : (<Button variant="primary" className="me-2" size="sm" onClick={() => {setCurrentResource(resource); setShowResourceModal(false)}}>Select</Button>)}</td>
                </tr>)
              }
            </tbody>
          </table>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="primary" onClick={() => setShowResourceModal(false)}>
            Complete And Close
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
};

export default UpdateEvent;