'use client';

import { useEffect, useState } from 'react';
import { useLocale, useTranslations } from 'next-intl';
import { ChevronRight } from 'lucide-react';
import { Link } from '@/i18n/navigation';
import { Card } from '@/components/ui/shared/Card';
import { formatAppTimeRange } from '@/lib/i18n/format';
import { purposeLabel } from '@/components/appointments/appointmentPurposeStyles';
import { treatmentAppointmentHref } from '@/components/shared/treatmentSelection';
import { treatmentTypeColor } from '@/components/shared/treatmentTypeDisplay';
import { canViewMyAppointmentsWeekChart } from '@/components/shared/permissions';
import { useAuth } from '@/lib/hooks/useAuth';
import { treatmentCatalogApi } from '@/lib/api/treatment-catalog';
import { ListRowSkeleton } from '@/components/ui/today/TodaySkeleton';
import type { TreatmentCatalogEntry } from '@/types/treatment-catalog';
import type { TodaySummaryActions } from '@/types/today';

interface TodayUpcomingAppointmentsProps {
  actions: TodaySummaryActions;
  loading?: boolean;
  isInitialLoad?: boolean;
}

export function TodayUpcomingAppointments({
  actions,
  loading = false,
  isInitialLoad = false,
}: TodayUpcomingAppointmentsProps) {
  const locale = useLocale();
  const t = useTranslations('today');
  const { currentOrganization } = useAuth();
  const [treatmentCatalog, setTreatmentCatalog] = useState<TreatmentCatalogEntry[]>([]);

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

  if (
    !currentOrganization ||
    currentOrganization.type !== 'CLINIC' ||
    !canViewMyAppointmentsWeekChart(currentOrganization)
  ) {
    return null;
  }

  const appointments = actions.upcomingAppointmentsToday ?? [];

  if (isInitialLoad) {
    return (
      <Card className="flex h-full min-h-0 flex-col p-3">
        <div className="mb-2 space-y-1.5">
          <div className="h-3.5 w-32 animate-pulse rounded bg-background-secondary/60" />
          <div className="h-3 w-44 animate-pulse rounded bg-background-secondary/60" />
        </div>
        <div className="space-y-2">
          {[0, 1].map((key) => (
            <ListRowSkeleton key={key} compact />
          ))}
        </div>
      </Card>
    );
  }

  return (
    <Card className="flex h-full min-h-0 flex-col p-3">
      <div className="mb-2 flex flex-col gap-1 sm:flex-row sm:items-start sm:justify-between">
        <div>
          <h2 className="text-sm font-semibold text-card-foreground">
            {t('upcomingAppointmentsTitle')}
          </h2>
          <p className="mt-0.5 text-[11px] text-text-muted">{t('upcomingAppointmentsSubtitle')}</p>
        </div>
        <Link
          href={treatmentAppointmentHref()}
          className="shrink-0 text-[11px] font-medium text-primary hover:underline underline-offset-2"
        >
          {t('viewAllAppointments')}
        </Link>
      </div>

      {appointments.length === 0 ? (
        <div className="flex min-h-[72px] items-center justify-center rounded-[var(--radius-md)] border border-dashed border-border/50 bg-background-secondary/20 px-3">
          <p className="text-xs text-text-muted text-center">{t('noUpcomingAppointments')}</p>
        </div>
      ) : (
        <div className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto">
          <ul className="divide-y divide-border/40">
            {appointments.map((appointment) => {
              const timeLabel = formatAppTimeRange(appointment.startAt, appointment.endAt, locale);
              const purposeIndex = treatmentCatalog.findIndex(
                (entry) => entry.code === appointment.purpose,
              );
              const purposeTextColor = treatmentTypeColor(
                appointment.purpose,
                purposeIndex < 0 ? 0 : purposeIndex,
              );
              const purposeDisplay = purposeLabel(appointment.purpose, treatmentCatalog);

              return (
                <li key={appointment.id}>
                  <Link
                    href={treatmentAppointmentHref(appointment.id)}
                    className="group -mx-1 flex items-center justify-between gap-2 rounded-[var(--radius-md)] px-1 py-2 transition-colors hover:bg-background-secondary/45"
                  >
                    <div className="min-w-0">
                      <p className="truncate text-xs font-medium text-text-primary">
                        {appointment.patientName}
                      </p>
                      <p className="mt-0.5 truncate text-[11px] text-text-muted">
                        {timeLabel}
                        {appointment.purpose ? (
                          <span style={{ color: purposeTextColor }}> · {purposeDisplay}</span>
                        ) : null}
                      </p>
                    </div>
                    <ChevronRight
                      className="h-3.5 w-3.5 shrink-0 text-text-muted opacity-0 transition-opacity group-hover:opacity-100"
                      aria-hidden
                    />
                  </Link>
                </li>
              );
            })}
          </ul>
        </div>
      )}
    </Card>
  );
}
