'use client';

import { useCallback, useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { addConsent, listConsents, revokeConsent } from '@/lib/services/patients';
import {
  CONSENT_TYPE_LABELS,
  ConsentType,
  PatientConsent,
} from '@/lib/types';
import { EmptyState, Loading, formatDateTime } from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

export default function ConsentsTab({
  patientId,
  canManage,
}: {
  patientId: number;
  canManage: boolean;
}) {
  const [items, setItems] = useState<PatientConsent[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

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

  async function handleCreate() {
    const typeOptions = (Object.keys(CONSENT_TYPE_LABELS) as ConsentType[])
      .map(
        (t) =>
          `<option value="${t}">${CONSENT_TYPE_LABELS[t]}</option>`,
      )
      .join('');

    const { value } = await Swal.fire({
      title: 'Registrar consentimento',
      html: `
        <div class="text-start">
          <label class="form-label">Tipo</label>
          <select id="sw-ctype" class="form-select mb-2">${typeOptions}</select>
          <label class="form-label">Versão do termo</label>
          <input id="sw-version" class="form-control mb-2" value="v1.0">
          <div class="form-check">
            <input id="sw-granted" type="checkbox" class="form-check-input" checked>
            <label class="form-check-label" for="sw-granted">Consentimento concedido</label>
          </div>
        </div>`,
      focusConfirm: false,
      showCancelButton: true,
      confirmButtonText: 'Registrar',
      cancelButtonText: 'Cancelar',
      preConfirm: () => {
        const type = (
          document.getElementById('sw-ctype') as HTMLSelectElement
        ).value as ConsentType;
        const version = (
          document.getElementById('sw-version') as HTMLInputElement
        ).value.trim();
        const granted = (
          document.getElementById('sw-granted') as HTMLInputElement
        ).checked;
        if (!version) {
          Swal.showValidationMessage('Informe a versão do termo');
          return false;
        }
        return { type, version, granted };
      },
    });

    if (!value) return;
    try {
      await addConsent(patientId, value);
      load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  async function handleRevoke(consent: PatientConsent) {
    const confirm = await Swal.fire({
      icon: 'warning',
      title: 'Revogar consentimento?',
      text: CONSENT_TYPE_LABELS[consent.type],
      showCancelButton: true,
      confirmButtonText: 'Revogar',
      cancelButtonText: 'Cancelar',
      confirmButtonColor: '#dc3545',
    });
    if (!confirm.isConfirmed) return;
    try {
      await revokeConsent(patientId, consent.id);
      load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  if (loading) return <Loading label="Carregando consentimentos…" />;
  if (error) return <div className="alert alert-danger">{error}</div>;

  return (
    <div className="card border-0 shadow-sm">
      <div className="card-header bg-white d-flex justify-content-between align-items-center">
        <span className="fw-semibold">
          <i className="bi bi-shield-check me-2 text-primary" />
          Consentimentos (LGPD)
        </span>
        {canManage && (
          <button className="btn btn-sm btn-primary" onClick={handleCreate}>
            <i className="bi bi-plus-lg me-1" />
            Registrar
          </button>
        )}
      </div>
      {items.length === 0 ? (
        <EmptyState
          icon="bi-shield-check"
          title="Nenhum consentimento registrado"
        />
      ) : (
        <div className="table-responsive">
          <table className="table align-middle mb-0">
            <thead className="table-light">
              <tr>
                <th>Tipo</th>
                <th>Versão</th>
                <th>Status</th>
                <th>Concedido em</th>
                <th>Revogado em</th>
                {canManage && <th className="text-end">Ações</th>}
              </tr>
            </thead>
            <tbody>
              {items.map((consent) => (
                <tr key={consent.id}>
                  <td className="fw-semibold">
                    {CONSENT_TYPE_LABELS[consent.type]}
                  </td>
                  <td>{consent.version}</td>
                  <td>
                    {consent.granted ? (
                      <span className="badge text-bg-success">Ativo</span>
                    ) : (
                      <span className="badge text-bg-secondary">Revogado</span>
                    )}
                  </td>
                  <td className="text-muted">
                    {formatDateTime(consent.grantedAt)}
                  </td>
                  <td className="text-muted">
                    {formatDateTime(consent.revokedAt)}
                  </td>
                  {canManage && (
                    <td className="text-end">
                      {consent.granted && (
                        <button
                          className="btn btn-sm btn-outline-danger"
                          onClick={() => handleRevoke(consent)}
                        >
                          Revogar
                        </button>
                      )}
                    </td>
                  )}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
