import React, {useState, useEffect} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, EventsService, CustomerService, ResourceService } from "../../services";
import DatePicker from "react-datepicker";
import Select  from 'react-select';
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab, Button, Modal, DropdownButton, Dropdown } from "react-bootstrap";
import { Columns, Download, Filter, PencilSquare, PersonSquare, Plus } from "react-bootstrap-icons";
import { ManageTable, Export } from "../../shared/components";


const EventsMultipleList = () => {
  const navigate = useNavigate();
  const [events, setEvents] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [sorting, setSorting] = useState({key: '', order: ''});
  const [selectedItems, setSelectedItems] = useState([]);
  const [resources, setResources] = useState([]);
  const [fromDate, setFromDate] = useState(new Date());
  const [toDate, setToDate] = useState(new Date(new Date().setMonth(new Date().getMonth() + 6)));
  const [selectedResource, setSelectedResource] = useState(null);
  const [selectedCustomer, setSelectedCustomer] = useState(null);
  const [filteredEvents, setFilteredEvents] = useState(events);
  const [showDeletedItems, setShowDeletedItems] = useState(false);
  const [showFilterDropdown, setShowFilterDropdown] = useState(false);
  const [columns, setColumns] = useState([
    {
      key: 'customer',
      label:'Customer',
      show: true
    },
    {
      key: 'chinese_name',
      label: 'Preferred Name',
      show: true
    },
    {
      key: 'member_type',
      label: 'Member Type',
      show: true
    },
    {
      key: 'eyes_on',
      label: 'Eyes-on',
      show: true
    },
    {
      key: 'doctor',
      label: 'Doctor',
      show: true
    },
    {
      key: 'phone',
      label: 'Phone',
      show: true
    },
    {
      key: 'address',
      label: 'Address',
      show: true
    },
    {
      key: 'translation',
      label: 'Translation',
      show: true
    },
    {
      key: 'newPatient',
      label: 'New Patient',
      show: true
    },
    {
      key: 'needId',
      label: 'Need ID',
      show: true
    },
    {
      key: 'startTime',
      label: 'Start Time',
      show: true
    },
    {
      key: 'transportation',
      label: 'Driver',
      show: true
    },
    {
      key: 'fasting',
      label: 'Fasting',
      show: true
    }
  ]);

  const checkDisability = (customers, event) => {
    const currentCustomer = customers?.find(c => c?.id === event?.data?.customer || c?.name === event?.data?.client_name || c?.name === event?.target_name);
    return currentCustomer?.disability || event?.data?.disability?.toLowerCase() === 'yes' || false;
  };

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

  useEffect(() => {
    if (fromDate && toDate && customers?.length > 0 && resources?.length > 0) {
      EventsService.getAllEvents({ from: EventsService.formatDate(fromDate), to: EventsService.formatDate(toDate) }).then((data) => {
        setEvents(data.data.filter((item) => {
          item.customer = (item?.data?.customer ? (customers.find(c=>c.id === item?.data?.customer)?.name || item?.data?.client_name || '') : (item?.data?.client_name || ''));
          item.doctor = item?.data?.resource ? (resources.find(r=> r.id === item?.data?.resource)?.name || item?.data?.resource_name || '') : (item?.data?.resource_name || '');
          item.phone = item?.data?.resource ? (resources.find(r=> r.id === item?.data?.resource)?.phone || item?.data?.resource_phone || '') : (item?.data?.resource_phone || '');
          item.address = item?.data?.resource ? (resources.find(r=> r.id === item?.data?.resource)?.address || item?.data?.resource_address || '') : (item?.data?.resource_address || '');
          item.translation = item?.data?.interpreter || '';
          item.newPatient = item?.data?.new_patient || '';
          item.needId = item?.data?.need_id || '';
          item.startTime = item?.start_time? `${EventsService.formatDate(new Date(item?.start_time))} ${new Date(item?.start_time).toLocaleTimeString('en-US', { hour: '2-digit', minute: 'numeric', hour12: true })}` : '' ;
          item.transportation = item?.link_event_name || '';
          item.confirmed = item?.confirmed || false;
          item.transMethod = item?.data?.trans_method;
          item.fasting = item?.data?.fasting || '';
          item.disability = item?.data?.disability || false;
          item.member_type = item?.data?.customer ? (customers.find(c => c.id === item?.data?.customer)?.type || '') : '';
          item.chinese_name = item?.data?.customer ? customers.find(c => c.id === item?.data?.customer)?.name_cn : (customers?.find(c=> c?.name === item?.data?.client_name || c?.name === item?.target_name )?.name_cn || '');
          item.eyes_on = checkDisability(customers, item) ? 'Yes' : 'No';
          item.dob = item?.data?.customer ? customers.find(c => c.id === item?.data?.customer)?.birth_date : (item?.data?.client_birth_date || '')
          return item;
        }).filter(item => item.type === 'medical'));
      })
    }
  }, [fromDate, toDate, customers, resources]);

  useEffect(() => {
    setFilteredEvents(events?.filter((event) => {
      if (selectedResource && selectedResource.label !== '' && selectedResource.value !== '') {
        if (selectedResource?.label?.replaceAll(' ', '').replaceAll('＊', '').replaceAll('*', '').includes(event.doctor?.replaceAll(' ', '').replaceAll('＊', '').replaceAll('*', ''))
        || event.doctor?.replaceAll(' ', '').replaceAll('＊', '').replaceAll('*', '').includes(selectedResource?.label?.replaceAll(' ', '').replaceAll('＊', '').replaceAll('*', ''))) {
          return event;
        }
      } else {
        return event;
      }
    }).filter((event => {
      if (selectedCustomer && selectedCustomer !== '' && selectedCustomer.value !== '') {
        if (selectedCustomer?.label?.replaceAll(' ', '').replaceAll('(Eyes-on)', '').replaceAll('(discharged)', '').replaceAll('＊', '').replaceAll('*', '') ===  (event.customer?.replaceAll(' ', '').replaceAll('(discharged)', '').replaceAll('(Eyes-on)', '').replaceAll('＊', '').replaceAll('*', ''))) {
          return event;
        }
      } else {
        return event;
      }
    })));
  }, [selectedResource, selectedCustomer, events]);



  useEffect(() => {
    const newEvents = [...events];
    const sortedEvents = sorting.key === '' ? newEvents : newEvents.sort((a, b) => {
      return a[sorting.key]?.localeCompare(b[sorting.key]);
    });
    setEvents(
      sorting.order === 'asc' ? sortedEvents : sortedEvents.reverse()
    )
  }, [sorting]);

  const confirmEvent = (id) => {
    EventsService.updateEvent(id, {confirmed: true}).then(() => {
      EventsService.getAllEvents({ from: EventsService.formatDate(fromDate), to: EventsService.formatDate(toDate) }).then((data) => {
        setEvents(data.data.filter((item) => {
          item.customer = (item?.data?.customer ? (customers.find(c=>c.id === item?.data?.customer)?.name || item?.data?.client_name || '') : (item?.data?.client_name || ''));
          item.doctor = item?.data?.resource ? (resources.find(r=> r.id === item?.data?.resource)?.name || item?.data?.resource_name || '') : (item?.data?.resource_name || '');
          item.phone = item?.data?.resource ? (resources.find(r=> r.id === item?.data?.resource)?.phone || item?.data?.resource_phone || '') : (item?.data?.resource_phone || '');
          item.address = item?.data?.resource ? (resources.find(r=> r.id === item?.data?.resource)?.address || item?.data?.resource_address || '') : (item?.data?.resource_address || '');
          item.translation = item?.data?.interpreter || '';
          item.newPatient = item?.data?.new_patient || '';
          item.needId = item?.data?.need_id || '';
          item.startTime = item?.start_time? `${EventsService.formatDate(new Date(item?.start_time))} ${new Date(item?.start_time).toLocaleTimeString('en-US', { hour: '2-digit', minute: 'numeric', hour12: true })}` : '' ;
          item.transportation = item?.link_event_name || '';
          item.confirmed = item?.confirmed || false;
          item.fasting = item?.data?.fasting || '';
          item.disability = item?.data?.disability || false;
          item.transMethod = item?.data?.trans_method;
          item.eyes_on = checkDisability(customers, item) ? 'Yes' : 'No';
          item.member_type = item?.data?.customer ? (customers.find(c => c.id === item?.data?.customer)?.type || '') : '';
          item.chinese_name = item?.data?.customer ? customers.find(c => c.id === item?.data?.customer)?.name_cn : (customers?.find(c=> c?.name === item?.data?.client_name || c?.name === item?.target_name )?.name_cn || '');
          item.dob = item?.data?.customer ? customers.find(c => c.id === item?.data?.customer)?.birth_date : (item?.data?.client_birth_date || '')
          return item;
        }).filter(item => item.type === 'medical'));
      })
    });
  }


  const redirectToAdmin = () => {
    navigate(`/medical`)
  }

  const goToEdit = (id) => {
    navigate(`/medical/events/edit/${id}`)
  }

  const goToCreateNew = () => {
    navigate(`/medical/events`)
  }


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

  const getSortingImg = (key) => {
    return sorting.key === key ? (sorting.order === 'asc' ? 'up_arrow' : 'down_arrow') : 'default';
  }

  const sortTableWithField = (key) => {
    let newSorting = {
      key,
      order: 'asc',
    }
    
    if (sorting.key === key && sorting.order === 'asc') {
      newSorting = {...newSorting, order: 'desc'};
    }
    setSorting(newSorting);
  }

  const toggleSelectedAllItems = () => {
    if (selectedItems.length !== filteredEvents.length || selectedItems.length === 0) {
      const newSelectedItems = [...filteredEvents].filter(ev=> ev.status === 'active').map((event) => event.id);
      setSelectedItems(newSelectedItems);
    } else {
      setSelectedItems([]);
    }
  }

  const toggleItem  = (id) => {
    if (selectedItems.includes(id)) {
      const newSelectedItems = [...selectedItems].filter((item) => item !== id);
      setSelectedItems(newSelectedItems);
    } else {
      const newSelectedItems = [...selectedItems, id];
      setSelectedItems(newSelectedItems);
    }
  }

  const checkSelectAll = () => {
    return selectedItems.length === filteredEvents.filter(ev=> ev.status === 'active').length && selectedItems.length > 0;
  }

  const generateMedicalNotificationPdf = () => {
    if (selectedItems?.length <= 0) {
      window.alert("Please select at least one event record")
    } else {
      const inputData = { eventIds: selectedItems };
      EventsService.generatePdf(inputData);
    }
  }

  const generateVisitRecordSheet = async () => {
    if (selectedItems?.length <= 0) {
      window.alert("Please select at least one event record")
    } else {
      const inputData = { eventIds: selectedItems };
      EventsService.generateSheet(inputData);
    }
    
  };

  const generateVisitRecordPDF = async () => {
    if (selectedItems?.length <= 0) {
      window.alert("Please select at least one event record")
    } else {
      const inputData = { eventIds: selectedItems };
      EventsService.generateSheetPDF(inputData);
    }
    
  };

  const generateMedicalNotificationDocs = () => {
    if (selectedItems?.length <= 0) {
      window.alert("Please select at least one event record");
    } else {
      const inputData = { eventIds: selectedItems };
      EventsService.generateDoc(inputData);
    }
  };

  const showDeleted = (value) => {
		setShowDeletedItems(value === 'archivedEvents');
		// Recover all filters
		// setKeyword('');
		setSorting({key: '', order: ''});
		setSelectedItems([]);
	};

  const table = (statusParam) => <div className="list row mb-4">
    <div className="col-md-12">
      <table className="personnel-info-table"> 
        <thead>
          <tr>
            <th className="th-checkbox" ><input type="checkbox" checked={checkSelectAll()} onClick={() => toggleSelectedAllItems()}></input></th>
            <th className="th-index">No.</th>
            {
              columns.filter(col => col.show).map((column, index) => <th className="sortable-header" key={index}>
                {column.label}  <span className="float-right" onClick={() => sortTableWithField(column.key)}><img src={`/images/${getSortingImg(column.key)}.png`}></img></span>
              </th>)
            }
            <th>Customer Date of Birth</th>
            <th>Transportation</th>
            <th></th>
          </tr>
          
        </thead>
        <tbody>
          {
            filteredEvents && filteredEvents.filter(event => event.status === statusParam).map((medicalEvent, index) => <tr key={medicalEvent.id}>
              <td className="td-checkbox"><input type="checkbox" checked={selectedItems.includes(medicalEvent.id)} onClick={()=>toggleItem(medicalEvent?.id)}/></td>
              <td className="td-index">{index + 1}</td>
              {columns.find(col => col.key === 'customer')?.show && <td>{medicalEvent?.customer}</td>}
              {columns.find(col => col.key === 'chinese_name')?.show && <td>{medicalEvent?.chinese_name}</td>}
              {columns.find(col => col.key === 'member_type')?.show && <td>{medicalEvent?.member_type}</td>}
              {columns.find(col => col.key === 'eyes_on')?.show && <td>{medicalEvent?.eyes_on}</td>}
              {columns.find(col => col.key === 'doctor')?.show && <td>{medicalEvent?.doctor}</td>}
              {columns.find(col => col.key === 'phone')?.show && <td>{medicalEvent?.phone}</td>}
              {columns.find(col => col.key === 'address')?.show && <td>{medicalEvent?.address}</td>}
              {columns.find(col => col.key === 'translation')?.show && <td>{medicalEvent?.translation}</td>}
              {columns.find(col => col.key === 'newPatient')?.show && <td>{medicalEvent?.newPatient}</td>}
              {columns.find(col => col.key === 'needId')?.show && <td>{medicalEvent?.needId}</td>}
              {columns.find(col => col.key === 'startTime')?.show && <td>{medicalEvent?.startTime}</td>}
              {columns.find(col => col.key === 'transportation')?.show && <td>{medicalEvent?.transportation}</td>}
              {columns.find(col => col.key === 'fasting')?.show && <td>{medicalEvent?.fasting}</td>}
              <td>{medicalEvent?.dob}</td>
              <td>{medicalEvent?.transMethod}</td>
              <td>{medicalEvent?.confirmed ? 'Confirmed' : <button className="btn btn-primary btn-sm me-2 ms-2" onClick={() => confirmEvent(medicalEvent?.id)}>Confirm</button>}</td>
            </tr>)
          }
        </tbody>
      </table>
    </div>
  </div>;

  const cleanFilterAndClose = () => {
    setSelectedCustomer(null);
    setSelectedResource(null);
    setShowFilterDropdown(false);
  }

  const FilterAndClose = () => {
    setShowFilterDropdown(false);
  }


  const customMenu = React.forwardRef(
    ({ children, style, className, 'aria-labelledby': labeledBy }, ref) => {
      const [value, setValue] = useState('');
  
      return (
        <div
          ref={ref}
          style={style}
          className={className}
          aria-labelledby={labeledBy}
        >
          <h6>Filter By</h6>
          <div className="app-main-content-fields-section margin-sm">
            <div className="me-4">
              <div className="field-label">Customer</div>
              <Select styles={{
                control: (baseStyles, state) => ({
                  ...baseStyles,
                  width: '210px',
                  height: '45px',
                  minHeight: '45px',
                  'padding-top': 0,
                  'padding-bottom': 0,
                  'margin-top': 0,
                  'margin-bottom': 0
                }),
                indicatorSeparator: (baseStyles, state) => ({
                  ...baseStyles,
                  display: 'none'
                }),
                dropdownIndicator: (baseStyles) => ({
                  ...baseStyles,
                  paddingRight: '12px'
                }),
                indicatorsContainer: (baseStyles) => ({
                  ...baseStyles,
                  'margin-top': '-5px'
                }),
                placeholder: (baseStyles) => ({
                  ...baseStyles,
                  'margin-top': '-5px',
                  'font-size': '13px'
                }),
                singleValue: (baseStyles, state) => ({
                  ...baseStyles,
                  'margin-top': '-5px',
                  'font-size': '13px'
                })
              }} value={selectedCustomer || ''} onChange={selectedData => {setSelectedCustomer(selectedData); setSelectedItems([]);}} options={[{value: '', label: ''}, ...customers.filter(customer => customer?.status === 'active' && customer?.type !== 'discharged').map(resource => ({
                value: resource?.id || '',
                label: resource?.name || '',
              }))]}></Select>
            </div>
          </div>
          <div className="app-main-content-fields-section margin-sm">
            <div className="me-4">
              <div className="field-label">Resource</div>
              <Select styles={{
                control: (baseStyles, state) => ({
                  ...baseStyles,
                  width: '210px',
                  height: '45px',
                  minHeight: '45px',
                  'padding-top': 0,
                  'padding-bottom': 0,
                  'margin-top': 0,
                  'margin-bottom': 0
                }),
                indicatorSeparator: (baseStyles, state) => ({
                  ...baseStyles,
                  display: 'none'
                }),
                dropdownIndicator: (baseStyles) => ({
                  ...baseStyles,
                  paddingRight: '12px'
                }),
                indicatorsContainer: (baseStyles) => ({
                  ...baseStyles,
                  'margin-top': '-5px'
                }),
                placeholder: (baseStyles) => ({
                  ...baseStyles,
                  'margin-top': '-20px',
                  'font-size': '13px'
                }),
                singleValue: (baseStyles, state) => ({
                  ...baseStyles,
                  'margin-top': '-20px',
                  'font-size': '13px'
                })
              }} value={selectedResource || ''} onChange={selectedData => {setSelectedResource(selectedData); setSelectedItems([]);}} options={[{value: '', label: ''}, ...resources?.filter(r => r.status === 'active').map(resource => ({
                value: resource?.id || '',
                label: resource?.name || '',
              }))]}></Select>
            </div>
          </div>
          <div className="list row">
            <div className="col-md-12">
              <button className="btn btn-default btn-sm float-right" onClick={() => cleanFilterAndClose()}> Cancel </button>
              <button className="btn btn-primary btn-sm float-right" onClick={() => FilterAndClose()}> Filter </button>
            </div>
          </div>
        </div>
      );
    },
  );
  
  
  return (
    <>
      <div className="list row mb-4 noprint">
        <Breadcrumb>
          <Breadcrumb.Item href="/medical/index">Medical</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Appointment Information (Multi Days)
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
             Medical Event Multiple Days List 
             {/* <button className="btn btn-primary btn-sm" onClick={() => {goToCreateNew()}}>Create New Customer</button> 
             <button className="btn btn-link btn-sm" onClick={() => {redirectToAdmin()}}>Back</button> */}
           </h4> 
        </div>
      </div>
      
      <div className="app-main-content-list-container list-page">
				<div className="app-main-content-list-func-container">
					<Tabs defaultActiveKey="activeEvents" id="requests-tab" onSelect={(k) => showDeleted(k)}>
						<Tab eventKey="activeEvents" title="Active Appointments">
              <div className="app-main-content-fields-section with-function flex-end">
                <div className="me-4">
                  <div className="field-label">From</div>
                  <DatePicker selected={fromDate} onChange={(v) => {setFromDate(v); setSelectedItems([]);}} />
                </div>
                <div className="me-4">
                  <div className="field-label">To</div>
                  <DatePicker selected={toDate} onChange={(v) => {setToDate(v); setSelectedItems([]);}} />
                </div>
              </div>
              {table('active')}
            </Tab>
            <Tab eventKey="archivedEvents" title="Archived Appointments">
              <div className="app-main-content-fields-section with-function flex-end">
                <div className="me-4">
                  <div className="field-label">From</div>
                  <DatePicker selected={fromDate} onChange={(v) => {setFromDate(v); setSelectedItems([]);}} />
                </div>
                <div className="me-4">
                  <div className="field-label">To</div>
                  <DatePicker selected={toDate} onChange={(v) => {setToDate(v); setSelectedItems([]);}} />
                </div>
              </div>
							{table('inactive')}
						</Tab>
          </Tabs>
          <div className="list-func-panel">
						{/* <input className="me-2 with-search-icon" type="text" placeholder="Search" value={keyword}  onChange={(e) => setKeyword(e.currentTarget.value)} /> */}
						{/* <button className="btn btn-primary me-2"><Filter size={16} className="me-2"></Filter>Filter</button> */}
            <Dropdown
              key={'filter-event-multi-list'}
              id="filter-event-multi-list"
              className="me-2"
              show={showFilterDropdown}
              onToggle={(isOpen) => setShowFilterDropdown(isOpen)}
              autoClose={false}
            > 
              <Dropdown.Toggle variant="primary">
                <Filter size={16} className="me-2"></Filter>Filter
              </Dropdown.Toggle>
              <Dropdown.Menu as={customMenu}/> 
            </Dropdown>
						<ManageTable columns={columns} onColumnsChange={setColumns} />
						<button className="btn btn-primary me-2" onClick={() => goToCreateNew()}><Plus size={16}></Plus>Add New Medical Appointment</button>
						<Export 
							columns={columns} 
							data={filteredEvents.filter(event => event.status === (showDeletedItems ? 'inactive' : 'active'))} 
							filename="events-multiple"
							customActions={[
								{ label: 'Medical Notifications Doc', onClick: generateMedicalNotificationDocs },
								{ label: 'Medical Notifications Pdf', onClick: generateMedicalNotificationPdf },
								{ label: 'Visit Record Sheet', onClick: generateVisitRecordSheet },
								{ label: 'Visit Record PDF', onClick: generateVisitRecordPDF }
							]}
						/>
					</div>
        </div>
      </div>
    </>
  )
};

export default EventsMultipleList;