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, EventsService, ResourceService } from "../../services";
import Select from 'react-select';
import DatePicker from "react-datepicker";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";

const CreateEvent = () => {
  const navigate = useNavigate();
	// const [medicalResource, setMedicalResource] = useState(undefined);
  // const [currentResource, setCurrentResource] = useState(undefined);
  const [resources, setResources] = 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 [reason, setReason] = useState('');
  // const [otherRequirement, setOtherRequirement] = useState('');
  // const [todayEvents, setTodayEvents] = useState([]);
  // const [transportationInfo, setTransportationInfo] = useState(undefined);
  
 
  const params = new URLSearchParams(window.location.search);
  const redirectToCalendar = () => {
		navigate(`/medical/events/calendar`);
  }

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

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

  const goToNext = (id) => {
    navigate(`/medical/events/edit/${id}?from=create`)
  }

  const validateEvent = () => {
    const errors = [];
    
    // Required fields validation
    if (!currentCustomer || !currentCustomer.id) {
      errors.push('Customer');
    }
    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;
    }
    
    console.log('customer', currentCustomer);
    // console.log('resource', currentResource);
    
    const newEventData = {
      customer: currentCustomer.id,
      // resource: currentResource.id,
      client_name: currentCustomer.name,
      client_pharmacy: currentCustomer.pharmacy,
      client_pcp: currentCustomer.care_provider,
      client_birth_date: currentCustomer.birth_date,
      client_seating: currentCustomer.seating,
      // 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,
      // // 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: currentCustomer.disability? 'yes' : 'no',
      // disability_support: disabilitySupport
    }
    
    const newEvent = {
      data: newEventData,
      // title: title,
      // descrption: description,
      // notes: notes,
      start_time: new Date(startTime),
      type: 'medical',
      // stop_time: new Date(startTime),
      // source_type: currentResource.type,
      // source_uuid: currentResource.id,
      // source_name: currentResource.name,
      target_type: currentCustomer.type,
      target_uuid: currentCustomer.id,
      target_name: currentCustomer.name,
      create_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
      create_date: new Date(),
      edit_by: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name,
      edit_date: new Date(),
      edit_history:[{ employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }]
    }
    navigate(`/medical/events/create-from-request?event=${encodeURIComponent(JSON.stringify(newEvent))}`)
    // EventsService.createNewEvent(newEvent).then(data => goToNext(data.data?.id));
  };
  

  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);
      setCustomers(customersData.data);
    })
  }, []);

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

  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>
            Create New Medical Appointment
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>Create New Medical Appointment <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 defaultActiveKey="eventClientInfo" id="event-tab">
          <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>
          </Tabs>
        </div>
      </div>
    </>
  );
};

export default CreateEvent;