import React, {useState, useEffect} from "react";
import { PencilSquare } from "react-bootstrap-icons";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import { AuthService, CustomerService, EventsService, ResourceService } from "../../services";
import { Breadcrumb, Tabs, Tab } from "react-bootstrap";

const ViewEvent = () => {
  const navigate = useNavigate();
  const urlParams = useParams();
  const [searchParams] = useSearchParams();
  const [activeTab, setActiveTab] = useState(searchParams.get('tab') || 'eventInfo');
  const [currentEvent, setCurrentEvent] =  useState(undefined);
  const [resources, setResources] = useState([]);
  const [customers, setCustomers] = useState([]);
  const params = new URLSearchParams(window.location.search);
  
  const redirectToCalendar = () => {
    navigate(`/medical/events/calendar`);
  }

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

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

  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.getAllActiveCustomers()]).then(([resourcesData, customersData]) => {
      setResources(resourcesData.data);
      setCustomers(customersData.data);
      if (!currentEvent) {
        EventsService.getEvent(urlParams.id).then(eventData => {
          setCurrentEvent(eventData.data);
        })
      }
    })
  }, []);

  const getResourceName = () => {
    if (currentEvent?.data?.resource) {
      return resources.find(r => r.id === currentEvent?.data?.resource)?.name || currentEvent?.data?.resource_name;
    }
    return currentEvent?.data?.resource_name || '';
  };

  const getCustomerName = () => {
    if (currentEvent?.data?.customer) {
      return customers.find(c => c.id === currentEvent?.data?.customer)?.name || currentEvent?.data?.client_name;
    }
    return currentEvent?.data?.client_name || '';
  };

  const formatDateTime = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
  };

  return (
    <>
      <div className="list row mb-4">
        <Breadcrumb>
          <Breadcrumb.Item href="/medical/index">Medical</Breadcrumb.Item>
          <Breadcrumb.Item href="/medical/events/list">
            Medical Events
          </Breadcrumb.Item>
          <Breadcrumb.Item active>
            View Event Details
          </Breadcrumb.Item>
        </Breadcrumb>
        <div className="col-md-12 text-primary">
          <h4>View Medical Event Details <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-view-tab">
            <Tab eventKey="eventInfo" title="Event Information">
              <h6 className="text-primary">Appointment Details</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Provider</div>
                  <div className="field-value">{getResourceName()}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Customer</div>
                  <div className="field-value">{getCustomerName()}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Label</div>
                  <div className="field-value">
                    {currentEvent?.color && (
                      <span style={{ 
                        display: 'inline-block', 
                        width: '16px', 
                        height: '16px', 
                        borderRadius: '4px', 
                        backgroundColor: currentEvent?.color,
                        marginRight: '8px',
                        verticalAlign: 'middle'
                      }}></span>
                    )}
                    {currentEvent?.color || ''}
                  </div>
                </div>
              </div>
              
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Appointment Time</div>
                  <div className="field-value">{formatDateTime(currentEvent?.start_time)}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">End Time</div>
                  <div className="field-value">{formatDateTime(currentEvent?.stop_time)}</div>
                </div>
              </div>

              <h6 className="text-primary">Patient Information</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">New Patient</div>
                  <div className="field-value">{currentEvent?.data?.new_patient || 'No'}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Confirmed</div>
                  <div className="field-value">{currentEvent?.confirmed ? 'Yes' : 'No'}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Fasting Required</div>
                  <div className="field-value">{currentEvent?.data?.fasting || 'No'}</div>
                </div>
              </div>

              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Language Support</div>
                  <div className="field-value">{currentEvent?.data?.interpreter || ''}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Eyes-on Required</div>
                  <div className="field-value">{currentEvent?.data?.disability || 'No'}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">ID Needed</div>
                  <div className="field-value">{currentEvent?.data?.need_id || 'No'}</div>
                </div>
              </div>

              <h6 className="text-primary">Medical Requirements</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Doctor Order</div>
                  <div className="field-value">{currentEvent?.data?.doc_order || ''}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Need Medication List</div>
                  <div className="field-value">{currentEvent?.data?.need_med_list || 'No'}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Disability Support</div>
                  <div className="field-value">{currentEvent?.data?.disability_support || ''}</div>
                </div>
              </div>

              <h6 className="text-primary">Transportation & Notes</h6>
              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Transportation Support</div>
                  <div className="field-value">{currentEvent?.data?.trans_method || ''}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Reason</div>
                  <div className="field-value">{currentEvent?.data?.reason || ''}</div>
                </div>
              </div>

              <div className="app-main-content-fields-section">
                <div className="field-body">
                  <div className="field-label">Notes</div>
                  <div className="field-value">{currentEvent?.data?.notes || ''}</div>
                </div>
                <div className="field-body">
                  <div className="field-label">Other Requirements</div>
                  <div className="field-value">{currentEvent?.data?.other || ''}</div>
                </div>
              </div>
            </Tab>
          </Tabs>
          <div className="list-func-panel">
            <button className="btn btn-primary" onClick={() => goToEdit(currentEvent?.id)}>
              <PencilSquare className="me-2" size={16}></PencilSquare>Edit
            </button>
          </div>
        </div>
      </div>
    </>
  );
};

export default ViewEvent;
