import React, {useState, useEffect} from "react";
import { useNavigate } from "react-router-dom";
import { AuthService, EventsService, CustomerService, ResourceService, EventRequestsService } from "../../services";
import { Spinner, Breadcrumb, BreadcrumbItem, Tabs, Tab } from "react-bootstrap";
import { Columns, Download, Filter, PencilSquare, PersonSquare, Plus } from "react-bootstrap-icons";
import { ManageTable, Export } from "../../shared/components";

const EventRequestList = () => {
  const navigate = useNavigate();
  const [eventRequests, setEventRequests] = useState([]);
  const [customers, setCustomers] = useState([]);
  const [resources, setResources] = useState([]);
  const [sorting, setSorting] = useState({key: '', order: ''});
	const [showDone, setShowDone] = useState(false);
  const [comments, setComments] = useState({});
  const [keyword, setKeyword] = useState('');
  const [selectedItems, setSelectedItems] = useState([]);
  const [columns, setColumns] = useState([
    {
      key: 'customer_display',
      label:'Patient',
      show: true
    },
    {
      key: 'resource_display',
      label: 'Doctor',
      show: true
    },
    {
      key: 'source',
      label: 'Source',
      show: true
    },
    {
      key: 'type',
      label: 'Type',
      show: true
    },
    {
      key: 'transportation',
      label: 'Transportation',
      show: true
    },
    {
      key: 'symptom',
      label: 'Symptom Or Special Need',
      show: true
    },
    {
      key: 'np',
      label: 'NP',
      show: true
    },
    {
      key: 'upload',
      label: 'Upload By',
      show: true
    },
    {
      key: 'status',
      label: 'Status',
      show: true
    },
    {
      key: 'create_date',
      label: 'Create Date',
      show: 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`);
    }
    CustomerService.getAllCustomers().then((data) => {
      setCustomers(data.data);
    })
    ResourceService.getAll().then(data => {
      setResources(data.data);
    }) 
  }, []);

  useEffect(() => {
    if (customers?.length > 0 && resources?.length>0) {
      EventRequestsService.getAllEventRequests().then((data) => {
				setEventRequests(data.data);
			})
    }
  }, [resources, customers]);

  useEffect(() => {
    const newEventRequests = [...eventRequests];
    const sortedEventRequests = sorting.key === '' ? newEventRequests : newEventRequests.sort((a, b) => {
      return a[sorting.key].localeCompare(b[sorting.key]);
    });
    setEventRequests(
      sorting.order === 'asc' ? sortedEventRequests : sortedEventRequests.reverse()
    )
  }, [sorting]);

  const filterRequestsFun = (item, statusParam, keywordParam) => {
    
      return  (item?.customer_display?.toLowerCase()?.includes(keywordParam?.toLowerCase()) || item?.source?.toLowerCase()?.includes(keywordParam?.toLowerCase()) ||
               item?.resource_display?.toLowerCase()?.includes(keywordParam?.toLowerCase())) && item?.status === statusParam
  
  }
 
  const redirectToAdmin = () => {
    navigate(`/medical`)
  }


  const goToCreateNew = () => {
    navigate(`/medical/event-request`)
  }

  const toggleSelectedAllItems = () => {
    if (selectedItems.length !== eventRequests?.filter((item) => filterRequestsFun(item, showDone ? 'done': 'active', keyword))?.length || selectedItems.length === 0) {
      const newSelectedItems = [...eventRequests?.filter((item) => filterRequestsFun(item, showDone ? 'done': 'active', keyword))].map((customer) => customer.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 showDoneItems = (value) => {
		setShowDone(value === 'completedRequests');
		// Recover all filters
		setKeyword('');
		setSorting({key: '', order: ''});
		setSelectedItems([]);
	}

  const checkSelectAll = () => {
    return selectedItems.length === eventRequests?.filter((item) => filterRequestsFun(item, showDone ? 'done': 'active', keyword))?.length && selectedItems.length > 0;
  }

	const deleteItem = (id) => {
		EventRequestsService.updateEventRequest(id, {status: 'inactive'}).then(() => {
			EventRequestsService.getAllEventRequests().then((data) => {
				setEventRequests(data.data);
			})
		})
	}

	const confirmEventRequest = (eventRequest) => {
		EventRequestsService.updateEventRequest(eventRequest.id, {status: 'done', edit_history:[{ employee: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name, date: new Date() }]}).then(() => {
			EventRequestsService.getAllEventRequests().then((data) => {
				setEventRequests(data.data);
			})
		})
	}

	const createNewEvent = (eventRequest) => {
		const customer = customers.find(c => c.id === eventRequest?.customer_id);
		const resource = resources.find(r => r.id === eventRequest?.resource);
		const newEventData = {
      customer: eventRequest?.customer_id,
      resource: eventRequest?.resource,
      client_name: customer?.name,
      client_pharmacy: customer?.pharmacy,
      client_pcp: customer?.care_provider,
      client_birth_date: customer?.birth_date,
      client_seating: customer?.seating,
      resource_type: resource?.type,
      resource_name: resource?.name,
      resource_phone: resource?.phone,
      resource_contact: resource?.contact,
      resource_address: resource?.address,
      resource_city: resource?.city,
      resource_state: resource?.state,
      // legacy fields end
      // We still wanna keep the legacy fields below
      notes: eventRequest?.symptom,
      other: eventRequest?.symptom,
      disability: customer?.disability? 'yes' : 'no',
      trans_method: eventRequest?.transportation,
      new_patient: eventRequest?.np?.toLowerCase()
    }
    
    const newEvent = {
      data: newEventData,
      notes: eventRequest?.symptom,
      start_time: new Date(),
      type: 'medical',
      source_type: resource?.type,
      source_uuid: resource?.id,
      source_name: resource?.name,
      target_type: customer?.type,
      target_uuid: customer?.id,
      target_name: customer?.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() }]
    }

    console.log('new Event', newEvent);
		navigate(`/medical/events/create-from-request?event=${encodeURIComponent(JSON.stringify(newEvent))}`)
	}

  const setCommentsValue = (e) => {
    const { name, value } = e.target;
    setComments({ ...comments, [name]: value });
  }

  const saveComments = (id) => {
    const currentComment = comments[id];
    if (currentComment) {
      const existingComments = eventRequests?.find((request) => request.id === id)?.notes || [];
      const newComments = [...existingComments, {
        content: currentComment,
        author: localStorage.getItem('user') && JSON.parse(localStorage.getItem('user'))?.name
      }];
      EventRequestsService.updateEventRequest(id, {
        notes: newComments
      }).then(() => {
        EventRequestsService.getAllEventRequests().then((data) => {
          setEventRequests(data.data);
          const textarea = document.getElementById(id);
          textarea.value = ''
        })
      });
    }
  }

  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 getStatusLabel = (status) => status === 'active' ? 'In Progress' : (status==='done' ? 'Done' : 'Deleted')
  
  const table = (statusParam, keywordParam) => <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>Completed By</th>
            <th>Comments</th>
            <th>Comment on the record</th>
            <th></th>
          </tr>
          
        </thead>
        <tbody>
          {
            eventRequests.filter((item) => filterRequestsFun(item, statusParam, keywordParam) )?.map((eventRequest, index) => <tr key={eventRequest?.id}>
              <td className="td-checkbox"><input type="checkbox" checked={selectedItems.includes(eventRequest?.id)} onClick={()=>toggleItem(eventRequest?.id)}/></td>
              <td className="td-index">{index + 1}</td>
              {columns.find(col => col.key === 'customer_display')?.show && <td>{eventRequest?.customer_display}</td>}
              {columns.find(col => col.key === 'resource_display')?.show && <td>{eventRequest?.resource_display}</td>}
              {columns.find(col => col.key === 'source')?.show && <td>{EventRequestsService.sourceList.find((item) => item?.value === eventRequest?.source)?.label || eventRequest?.source}</td>}
              {columns.find(col => col.key === 'type')?.show && <td>{eventRequest?.type}</td>}
              {columns.find(col => col.key === 'transportation')?.show && <td>{eventRequest?.transportation || '-'}</td>}
              {columns.find(col => col.key === 'symptom')?.show && <td>{eventRequest?.symptom}</td>}
              {columns.find(col => col.key === 'np')?.show && <td>{eventRequest?.np}</td>}
              {columns.find(col => col.key === 'upload')?.show && <td>{eventRequest?.upload}</td>}
              {columns.find(col => col.key === 'status')?.show && <td>{getStatusLabel(eventRequest?.status)}</td>}
              {columns.find(col => col.key === 'create_date')?.show && <td>{new Date(eventRequest?.create_date).toLocaleDateString()}</td>}
              <td>{ eventRequest.status === 'done' && eventRequest?.edit_history && eventRequest?.edit_history[eventRequest?.edit_history?.length - 1]?.employee || ''}</td>
              <td>{eventRequest?.notes?.map((note) => {
                return <p>{`${note?.author}: ${note?.content}`}</p>
              })}</td>
              <td align="center"><textarea id={eventRequest?.id} name={eventRequest?.id} onChange={setCommentsValue} className="comments-text"/> <button className="btn btn-primary btn-sm me-2 mt-2" onClick={() => saveComments(eventRequest?.id)}>Submit</button></td>
              <td className={eventRequest.status === 'active' ? 'table-button-container': ''}>
                {eventRequest.status !== 'done' && <button className="btn btn-primary btn-sm me-2" onClick={() => createNewEvent(eventRequest)}> New Appointment </button>}
                {eventRequest.status !== 'done' && <button className="btn btn-secondary btn-sm me-2" onClick={() => confirmEventRequest(eventRequest)}> Completed</button>}
                {/* <button className="btn btn-danger btn-sm" onClick={() => deleteItem(eventRequest?.id)}> Delete </button> */}
              </td>
            </tr>)
          }
        </tbody>
      </table>
    </div>
  </div>;


  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/medical/index">Medical</Breadcrumb.Item>
          <Breadcrumb.Item active>
            Appointment Requests Information
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
           <h4>
             All Medical Appointment Requests  
             {/* <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="activeRequests" id="requests-tab" onSelect={(k) => showDoneItems(k)}>
						<Tab eventKey="activeRequests" title="Active Requests">
							{table('active', keyword)}
						</Tab>
						<Tab eventKey="completedRequest" title="Completed Requests">
							{table('done', keyword)}
						</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>
						<ManageTable columns={columns} onColumnsChange={setColumns} />
						<button className="btn btn-primary me-2" onClick={() => goToCreateNew()}><Plus size={16}></Plus>Add New Appointment Request</button>
						<Export 
							columns={columns} 
							data={eventRequests.filter((item) => filterRequestsFun(item, showDone ? 'done': 'active', keyword))} 
							filename="event-requests" 
						/>
					</div>
				</div>
      </div>
    </>
  )
};

export default EventRequestList;