'use client';

import { useCallback, useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import Swal from 'sweetalert2';
import { RequireRole, useAuth } from '@/lib/auth-context';
import { getPatient, updatePatient } from '@/lib/services/patients';
import type { Gender, Patient } from '@/lib/types';
import PatientForm, {
  PatientFormValues,
} from '@/components/app/PatientForm';
import ContactsTab from '@/components/app/patient/ContactsTab';
import ConsentsTab from '@/components/app/patient/ConsentsTab';
import MedicalHistoryTab from '@/components/app/patient/MedicalHistoryTab';
import DocumentsTab from '@/components/app/patient/DocumentsTab';
import {
  BackLink,
  ErrorAlert,
  Loading,
  PageHeader,
  formatCpf,
} from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

type TabKey = 'dados' | 'contatos' | 'consentimentos' | 'historico' | 'documentos';

export default function PacienteDetailPage() {
  return (
    <RequireRole roles={['admin', 'receptionist', 'dentist']}>
      <PacienteDetail />
    </RequireRole>
  );
}

function PacienteDetail() {
  const params = useParams<{ id: string }>();
  const patientId = Number(params.id);
  const { user } = useAuth();

  const [patient, setPatient] = useState<Patient | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [submitting, setSubmitting] = useState(false);
  const [tab, setTab] = useState<TabKey>('dados');

  const canManage = user?.role !== undefined && user.role !== 'patient';
  const canEditHistory = user?.role === 'admin' || user?.role === 'dentist';

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      setPatient(await getPatient(patientId));
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [patientId]);

  useEffect(() => {
    if (!Number.isNaN(patientId)) load();
  }, [patientId, load]);

  async function handleSubmit(values: PatientFormValues) {
    setSubmitting(true);
    try {
      const updated = await updatePatient(patientId, {
        fullName: values.fullName,
        cpf: values.cpf || null,
        birthDate: values.birthDate || null,
        gender: (values.gender as Gender) || null,
        email: values.email || null,
        phone: values.phone || null,
        zipCode: values.zipCode || null,
        street: values.street || null,
        number: values.number || null,
        complement: values.complement || null,
        district: values.district || null,
        city: values.city || null,
        state: values.state || null,
        notes: values.notes || null,
        isActive: values.isActive,
      });
      setPatient(updated);
      Swal.fire({
        icon: 'success',
        title: 'Dados atualizados',
        timer: 1200,
        showConfirmButton: false,
      });
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    } finally {
      setSubmitting(false);
    }
  }

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

  const tabs: { key: TabKey; label: string; icon: string }[] = [
    { key: 'dados', label: 'Dados', icon: 'bi-person-vcard' },
    { key: 'contatos', label: 'Contatos', icon: 'bi-telephone' },
    { key: 'consentimentos', label: 'Consentimentos', icon: 'bi-shield-check' },
    { key: 'historico', label: 'Histórico clínico', icon: 'bi-clipboard2-pulse' },
    { key: 'documentos', label: 'Documentos', icon: 'bi-folder2-open' },
  ];

  return (
    <>
      <BackLink href="/painel/pacientes" label="Voltar para pacientes" />
      <PageHeader
        title={patient.fullName}
        subtitle={`CPF ${formatCpf(patient.cpf)} · ${
          patient.isActive ? 'Ativo' : 'Inativo'
        }`}
      />

      <ul className="nav nav-tabs mb-3" role="tablist">
        {tabs.map((item) => (
          <li className="nav-item" key={item.key} role="presentation">
            <button
              type="button"
              role="tab"
              aria-selected={tab === item.key}
              aria-label={item.label}
              className={`nav-link ${tab === item.key ? 'active' : ''}`}
              onClick={() => setTab(item.key)}
            >
              <i className={`bi ${item.icon} me-1`} aria-hidden="true" />
              <span className="d-none d-sm-inline">{item.label}</span>
            </button>
          </li>
        ))}
      </ul>

      {tab === 'dados' &&
        (canManage ? (
          <PatientForm
            initial={patient}
            submitting={submitting}
            onSubmit={handleSubmit}
          />
        ) : (
          <div className="alert alert-secondary">Somente leitura.</div>
        ))}

      {tab === 'contatos' && (
        <ContactsTab patientId={patientId} canManage={canManage} />
      )}

      {tab === 'consentimentos' && (
        <ConsentsTab patientId={patientId} canManage={canManage} />
      )}

      {tab === 'historico' && (
        <MedicalHistoryTab patientId={patientId} canEdit={canEditHistory} />
      )}

      {tab === 'documentos' && (
        <DocumentsTab patientId={patientId} canManage={canManage} />
      )}
    </>
  );
}
