'use client';

import { useEffect, useState } from 'react';
import { ShieldCheck, AlertCircle, FileText } from 'lucide-react';
import { EmptyState, Skeleton } from '@sehat/ui';
import { api, ApiClientError } from '@/lib/api-client';
import type { Appointment, PatientEmrRecord } from '@/lib/api-types';
import { computeAgeYears } from '@/lib/date-utils';
import { PatientSummaryCard } from './patient-summary-card';
import { AllergyStrip } from './allergy-strip';
import { MedicationsStrip } from './medications-strip';
import { EmrHighlights } from './emr-highlights';

interface EmrPaneProps {
  appointment: Appointment;
  /** Surfaced upwards so the prescription writer can prime its context. */
  onRecordLoaded?: (record: PatientEmrRecord) => void;
  /** Surfaces age/gender to the sticky header (kept above this pane). */
  onIdentityResolved?: (identity: {
    name: string | null;
    age: string | null;
    gender: string | null;
  }) => void;
}

/**
 * Owns the EMR fetch + render for the left pane. Splits skeleton / empty /
 * error states out of the main page so the layout stays readable.
 */
export function EmrPane({
  appointment,
  onRecordLoaded,
  onIdentityResolved,
}: EmrPaneProps) {
  const [record, setRecord] = useState<PatientEmrRecord | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [errorCode, setErrorCode] = useState<number | null>(null);

  useEffect(() => {
    let cancelled = false;
    void (async () => {
      try {
        const r = await api.getPatientEmr(appointment.patientId, appointment.id);
        if (cancelled) return;
        setRecord(r);
        onRecordLoaded?.(r);
        if (r.demographics) {
          const age = computeAgeYears(r.demographics.dateOfBirth);
          onIdentityResolved?.({
            name: `${r.demographics.firstName} ${r.demographics.lastName}`.trim(),
            age: age != null ? `${age} yr` : null,
            gender: r.demographics.gender || null,
          });
        }
      } catch (e) {
        if (cancelled) return;
        if (e instanceof ApiClientError) {
          setError(e.message);
          setErrorCode(e.statusCode);
        } else {
          setError('Failed to load EMR');
        }
      }
    })();
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [appointment.patientId, appointment.id]);

  if (error) {
    if (errorCode === 404) {
      return (
        <EmptyState
          icon={<FileText className="h-6 w-6" />}
          title="EMR not yet completed"
          description="This patient has not built their medical record. Encourage them to finish onboarding before the consult."
          action={
            <a
              href={`mailto:?subject=Please%20complete%20your%20EMR`}
              className="inline-flex items-center gap-1.5 rounded-md bg-brand-500 px-3 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-brand-600"
            >
              Request EMR completion
            </a>
          }
        />
      );
    }
    return (
      <div className="flex items-start gap-2 rounded-md border border-danger-500/30 bg-danger-500/5 p-3 text-sm text-danger-500">
        <AlertCircle className="mt-0.5 h-4 w-4 flex-shrink-0" />
        <span>{error}</span>
      </div>
    );
  }

  if (!record) {
    return (
      <div className="space-y-3">
        <Skeleton className="h-28 w-full rounded-lg" />
        <Skeleton className="h-16 w-full rounded-md" />
        <Skeleton className="h-12 w-full rounded-md" />
        <Skeleton className="h-40 w-full rounded-lg" />
      </div>
    );
  }

  return (
    <div className="space-y-3">
      <PatientSummaryCard
        record={record}
        fallbackName={appointment.patientName}
        symptoms={appointment.symptoms}
      />
      <AllergyStrip allergies={record.allergies} />
      <MedicationsStrip medications={record.medications} />
      <EmrHighlights record={record} />
      <p className="flex items-center gap-1 text-[10px] text-ink-3">
        <ShieldCheck className="h-3 w-3" />
        EMR access is audit-logged against appointment{' '}
        <span className="font-mono">{appointment.id.slice(0, 8)}</span>.
      </p>
    </div>
  );
}
