import React, { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { filterByServiceType } from '../utils';
import { useAppointmentList } from '../../hooks/useAppointmentList';
import AppointmentsTable from '../common-components/appointments-table.component';
import { useSelectedDateContext } from '../../hooks/selected-date-context';

interface AppointmentsListProps {
  appointmentServiceTypes?: Array<string>;
  date: string;
  excludeCancelledAppointments?: boolean;
  status?: string;
  title: string;
}

const statusToAppointmentState: Record<string, string> = {
  expected: 'WAITING',
  checkedIn: 'ATTENDED',
  completed: 'COMPLETED',
  missed: 'EXPIRED',
  cancelled: 'CANCELLED',
  scheduled: 'SCHEDULED',
};

const statusToAppointmentStateId: Record<string, string> = {
  expected: '4',
  checkedIn: '2',
  completed: '3',
  missed: '5',
  cancelled: '6',
  scheduled: '1',
};

const AppointmentsList: React.FC<AppointmentsListProps> = ({
  appointmentServiceTypes = [],
  date,
  excludeCancelledAppointments = false,
  status,
  title,
}) => {
  const { t } = useTranslation();
  const { selectedDate } = useSelectedDateContext();

  const appointmentState = useMemo(() => {
    if (!status) {
      return 'WAITING';
    }

    const normalizedStatus = status.toLowerCase().trim();
    const mappedState = statusToAppointmentState[normalizedStatus];

    if (!mappedState) {
      return 'WAITING';
    }

    return mappedState;
  }, [status]);

  // Use the date parameter if provided, otherwise fall back to selectedDate from context
  const targetDate = date || selectedDate;
  const { appointmentList, isLoading, error, mutate } = useAppointmentList(appointmentState, targetDate);

  const appointmentsFilteredByServiceType = useMemo(() => {
    let filteredAppointments = appointmentList;

    if (appointmentServiceTypes.length > 0) {
      filteredAppointments = filterByServiceType(appointmentList, appointmentServiceTypes);
    }

    if (excludeCancelledAppointments) {
      filteredAppointments = filteredAppointments.filter(
        (appointment) => appointment.appointmentState?.description !== 'CANCELLED',
      );
    }

    return filteredAppointments.map((appointment) => ({
      id: appointment.uuid || appointment.appointmentId?.toString() || Math.random().toString(),
      ...appointment,
    }));
  }, [appointmentList, appointmentServiceTypes, excludeCancelledAppointments]);

  return (
    <AppointmentsTable
      appointments={appointmentsFilteredByServiceType}
      hasActiveFilters={appointmentServiceTypes.length > 0}
      isLoading={isLoading}
      tableHeading={title}
    />
  );
};

export default AppointmentsList;
