'use client';

import { useCallback, useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { RequireRole } from '@/lib/auth-context';
import {
  ATTACHMENT_KIND_LABELS,
  Exam,
  EXAM_STATUS_BADGES,
  EXAM_STATUS_LABELS,
  examAttachmentPath,
  listMyExams,
} from '@/lib/services/exams';
import { openProtectedFile } from '@/lib/download';
import { EmptyState, ErrorAlert, Loading, PageHeader, formatDateTime } from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

export default function PortalExamesPage() {
  return (
    <RequireRole roles={['patient']}>
      <MyExams />
    </RequireRole>
  );
}

function MyExams() {
  const [exams, setExams] = useState<Exam[] | null>(null);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setError(null);
    try {
      setExams(await listMyExams());
    } catch (err) {
      setError(extractApiError(err));
    }
  }, []);

  useEffect(() => {
    load();
  }, [load]);

  async function openFile(examId: number, attachmentId: number) {
    try {
      await openProtectedFile(examAttachmentPath(examId, attachmentId));
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  if (error) return <ErrorAlert message={error} onRetry={load} />;
  if (!exams) return <Loading />;

  return (
    <>
      <PageHeader title="Meus exames" subtitle="Pedidos, marcações e resultados liberados pelo dentista" />
      {exams.length === 0 ? (
        <EmptyState icon="bi-file-earmark-medical" title="Nenhum exame" />
      ) : (
        <div className="d-flex flex-column gap-3">
          {exams.map((exam) => (
            <div className="card border-0 shadow-sm" key={exam.id}>
              <div className="card-body">
                <div className="d-flex flex-wrap justify-content-between gap-2 mb-2">
                  <h2 className="h6 fw-bold mb-0">{exam.name}</h2>
                  <span className={`badge ${EXAM_STATUS_BADGES[exam.status]}`}>
                    {EXAM_STATUS_LABELS[exam.status]}
                  </span>
                </div>
                <p className="small text-muted mb-2">
                  Pedido por {exam.requestedByDentist?.fullName} em {formatDateTime(exam.createdAt)}
                </p>
                {exam.instructions && <p className="small mb-2">{exam.instructions}</p>}
                {exam.scheduledAt && (
                  <p className="small mb-2">
                    <i className="bi bi-calendar-event me-1" aria-hidden="true" />
                    Marcado para {formatDateTime(exam.scheduledAt)}
                    {exam.location && ` — ${exam.location}`}
                  </p>
                )}
                {exam.status === 'completed' && exam.resultSummary && (
                  <div className="border rounded p-3 bg-light mb-2">
                    <div className="small text-muted mb-1">Laudo</div>
                    <div style={{ whiteSpace: 'pre-wrap' }}>{exam.resultSummary}</div>
                  </div>
                )}
                {exam.attachments.length > 0 && (
                  <div className="d-flex flex-wrap gap-2">
                    {exam.attachments.map((a) => (
                      <button
                        key={a.id}
                        className="btn btn-sm btn-outline-primary"
                        onClick={() => openFile(exam.id, a.id)}
                      >
                        <i className="bi bi-file-earmark-arrow-down me-1" aria-hidden="true" />
                        {ATTACHMENT_KIND_LABELS[a.kind]}: {a.originalName}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </>
  );
}
