import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import { useTranslation } from 'react-i18next';
import { useParams } from 'react-router-dom';
import { omrsDateFormat } from './constants';
import { SelectedDateContextProvider } from './hooks/selected-date-context';
import AppointmentTabs from './appointments/appointment-tabs.component';
import AppointmentsHeader from './header/appointments-header.component';
import AppointmentMetrics from './metrics/appointments-metrics.component';

const Appointments: React.FC = () => {
  const { t } = useTranslation();
  const params = useParams();

  const [appointmentServiceTypes, setAppointmentServiceTypes] = useState<Array<string>>([]);

  // Initialize with URL date parameter if available, otherwise use today
  const [selectedDate, setSelectedDate] = useState(() => {
    const initialDate = params.date
      ? dayjs(params.date).startOf('day').format(omrsDateFormat)
      : dayjs().startOf('day').format(omrsDateFormat);

    return initialDate;
  });

  useEffect(() => {
    if (params.date) {
      const formattedDate = dayjs(params.date).startOf('day').format(omrsDateFormat);
      setSelectedDate(formattedDate);
    }
  }, [params.date, selectedDate]);

  useEffect(() => {
    if (params.serviceType) {
      setAppointmentServiceTypes([params.serviceType]);
    }
  }, [params.serviceType]);

  return (
    <SelectedDateContextProvider value={{ selectedDate, setSelectedDate }}>
      <AppointmentsHeader
        appointmentServiceTypes={appointmentServiceTypes}
        onChange={setAppointmentServiceTypes}
        title={t('appointments', 'Appointments')}
      />
      <AppointmentMetrics appointmentServiceTypes={appointmentServiceTypes} />
      <AppointmentTabs appointmentServiceTypes={appointmentServiceTypes} />
    </SelectedDateContextProvider>
  );
};

export default Appointments;
