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

const CreateEventRequest = () => {
  const navigate = useNavigate();
  const [resources, setResources] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [currentCustomer, setCurrentCustomer] = useState(undefined);
	const [customerDisplay, setCustomerDisplay] = useState('');
	const [medicalResource, setMedicalResource] = useState(undefined)
	const [currentResource, setCurrentResource] = useState(undefined);
	const [resourceType, setResourceType] = useState('');
	const [source, setSource] = useState('');
	const [np, setNp] = useState('');
	const [symptom, setSymptom] = useState('');
	const [transportation, setTransportation] = useState('');
	const [showResourceModal, setShowResourceModal] = useState(false);
  const [keyword, setKeyword] = useState('');
	const [filteredResources, setFilteredResources] = useState([]);
	// const [upload, setUpload] = useState('');
	// const [uploadOther, setUploadOther] = useState('');
	const [type, setType] = useState('');
  
 
  // const params = new URLSearchParams(window.location.search);
  const goToRequestList = () => {
		navigate(`/medical/event-request/list`);
  }

	const redirectTo = () => {
		navigate(`/medical/index`);
	}


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

  const saveEventRequest = () => {
    if (!validateEventRequest()) {
      return;
    }
    
    const newEventRequest = {
      customer_id: currentCustomer?.id,
			customer_display: `${currentCustomer?.name} - ${currentCustomer?.name_cn} - ${currentCustomer?.birth_date}`,
			source,
			symptom,
			resource: currentResource?.id,
			resource_display: currentResource?.name,
      transportation,
			np,
			upload: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
			type,
			status: 'active',
      create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
      create_date: new Date(),
			edit_history:[{ employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }]
    }

    console.log('new Event Request', newEventRequest);
    EventRequestsService.createNewEventRequest(newEventRequest).then(data => goToRequestList());
  };
  

  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`);
    }
    Promise.all([ResourceService.getAll(), CustomerService.getAllCustomers()]).then(([resourcesData, customersData]) => {
      setResources(resourcesData.data);
			setFilteredResources(resourcesData.data);
      setCustomers(customersData.data);
    })
  }, []);

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

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

	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;
    }
  }

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

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/medical/index">Medical</Breadcrumb.Item>
          <Breadcrumb.Item href="/medical/event-request/list">
            Appointment Request Information
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            Create New Appointment Request
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>Create New Appointment Request <button className="btn btn-link btn-sm" onClick={() => {goToRequestList()}}>Back</button></h4> 
        </div>
      </div>
      <div className="app-main-content-list-container">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="requestInfo" id="request-tab">
						<Tab eventKey="requestInfo" title="Appointment Request Information">
              <h6 className="text-primary">Patient And Doctor Info</h6>
              <div className="app-main-content-fields-section">
                <div className="me-4">
									<div className="field-label">Patient
										<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={customerDisplay || ''} onChange={selectedCustomer => onCustomerChange(selectedCustomer)} options={[{value: '', label: ''}, ...customers.filter(customer => customer?.status === 'active' && customer?.type !== 'discharged').map(customer => ({
                    value: customer?.id || '',
                    label: `${customer?.name} - ${customer?.name_cn} - ${customer?.birth_date}` || ''
                  }))]}></Select>
								</div>
                <div className="me-4">
									<div className="field-label">Doctor
										<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></>)  : (<button className="btn btn-link btn-sm me-2 mb-2" onClick={()=> setShowResourceModal(true)}>Please click here to add resources</button>)}
								</div>
              </div>
              <h6 className="text-primary">Appointment Request Information</h6>
							<div className="app-main-content-fields-section">
                <div className="me-4">
									<div className="field-label">Source
										<span className="required">*</span>
									</div>
									<select value={source} onChange={e => setSource(e.target.value)}>
                    <option value=""></option>
                    {EventRequestsService.sourceList.map((item) => <option value={item.value}>{item.label}</option>)}
                  </select>
								</div>
                <div className="me-4">
									<div className="field-label">Type
										<span className="required">*</span>
									</div>
									<select value={type} onChange={e => setType(e.target.value)}>
                    <option value=""></option>
                    <option value="New">New</option>
                    <option value="Reschedule">Reschedule</option>
                    <option value="Cancel">Cancel</option>
                    <option value="Transportation Change">Transportation Change</option>
                    <option value="Emergency">Emergency</option>
                    <option value="Option 6">Option 6</option>
                  </select>
								</div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
									<div className="field-label">Symptom 和特殊要求
									</div>
									<textarea value={symptom || ''} onChange={e => setSymptom(e.target.value)}/>
								</div>
              </div>
              <div className="app-main-content-fields-section">
                <div className="me-4">
									<div className="field-label">Transportation
									</div>
									<select value={transportation} onChange={e => setTransportation(e.target.value)}>
                    <option value=""></option>
                    <option value="by own">By Own</option>
                    <option value="televisit">Televisit</option>
                    <option value="pickup only">Pickup Only</option>
                    <option value="dropoff only">Dropoff Only</option>
                    <option value="Center Transportation">By Center Transportation</option>
                    <option value="client does not need to go">Client Does Not Need To Go</option>
                  </select>
								</div>
                <div className="me-4">
									<div className="field-label">NP
									</div>
									<select value={np} onChange={e => setNp(e.target.value)}>
                    <option value=""></option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </select>
								</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={() => saveEventRequest()}> Submit </button>
                  
                </div>
              </div>
            </Tab>
          </Tabs>
        </div>
      </div>
      <Modal show={showResourceModal} fullscreen={'xxl-down'} onHide={() => setShowResourceModal(false)}>
        <Modal.Header closeButton>
          <Modal.Title>Select the Resource</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 Resource 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></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 style={{'min-width': '220px'}}>{ resource?.id === currentResource?.id ? 'Selected' : (<Button variant="link" 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 CreateEventRequest;