'use client';

import { useEffect, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { purposeLabel } from '@/components/appointments/appointmentPurposeStyles';
import { APP_DATE, formatAppDate, formatAppTimeRange } from '@/lib/i18n/format';
import { getUserFacingError } from '@/components/shared/formatApiError';
import { TreatmentTypeBadge } from '@/components/ui/treatment/TreatmentTypeBadge';
import { patientsApi } from '@/lib/api/patients';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import type { PatientAppointmentHistoryItem } from '@/types/patient';
import type { TreatmentCatalogEntry } from '@/types/treatment-catalog';

interface PatientAppointmentHistoryProps {
  patientId: string;
}

function formatAppointmentDate(value: string, locale: string): string {
  return formatAppDate(value, locale, APP_DATE.withWeekday);
}

export function PatientAppointmentHistory({ patientId }: PatientAppointmentHistoryProps) {
  const locale = useLocale();
  const t = useTranslations('patients');
  const tErrors = useTranslations('errors');
  const [items, setItems] = useState<PatientAppointmentHistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);

  useEffect(() => {
    void treatmentCatalogApi
      .list('appointment')
      .then((response) => setTreatmentCatalog(response.data))
      .catch(() => {});
  }, []);

  useEffect(() => {
    let cancelled = false;

    void (async () => {
      setLoading(true);
      setError(null);
      try {
        const response = await patientsApi.listAppointments(patientId);
        if (!cancelled) {
          setItems(response.data);
        }
      } catch (err: unknown) {
        if (!cancelled) {
          setError(getUserFacingError(err, tErrors, t('appointmentHistoryError')));
          setItems([]);
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    })();

    return () => {
      cancelled = true;
    };
  }, [patientId, t, tErrors]);

  return (
    <div className="surface-card p-4 space-y-3">
      <div>
        <h3 className="text-base font-semibold text-text-primary">{t('appointmentHistoryTitle')}</h3>
        <p className="text-sm text-text-muted mt-1">{t('appointmentHistorySubtitle')}</p>
      </div>

      {loading ? (
        <p className="text-sm text-text-secondary">{t('appointmentHistoryLoading')}</p>
      ) : error ? (
        <p className="text-sm text-red-500">{error}</p>
      ) : items.length === 0 ? (
        <p className="text-sm text-text-secondary">{t('appointmentHistoryEmpty')}</p>
      ) : (
        <ul className="divide-y divide-border/60">
          {items.map((item) => (
            <li key={item.id} className="py-3 first:pt-0 last:pb-0">
              <div className="flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
                <div className="min-w-0">
                  <p className="text-sm font-medium text-text-primary">
                    {formatAppointmentDate(item.startAt, locale)}
                  </p>
                  <p className="text-sm text-text-secondary">
                    {formatAppTimeRange(item.startAt, item.endAt, locale)}
                  </p>
                </div>
                <div className="flex flex-col gap-1.5 sm:items-end">
                  {item.purpose ? (
                    <TreatmentTypeBadge
                      type={item.purpose}
                      label={purposeLabel(item.purpose, treatmentCatalog)}
                    />
                  ) : null}
                  <p className="text-sm text-text-muted">
                    {t('appointmentHistoryProvider', {
                      name: item.providerName || t('appointmentHistoryUnknownProvider'),
                    })}
                  </p>
                </div>
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
