'use client';

import Link from 'next/link';
import { useCallback, useEffect, useState } from 'react';
import Swal from 'sweetalert2';
import { RequireRole, useAuth } from '@/lib/auth-context';
import { listPatients, removePatient } from '@/lib/services/patients';
import type { Patient } from '@/lib/types';
import {
  EmptyState,
  ErrorAlert,
  Loading,
  PageHeader,
  Pagination,
  formatCpf,
} from '@/components/app/ui';
import { extractApiError } from '@/lib/api-client';

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

const PAGE_SIZE = 10;

function PatientsView() {
  const { user } = useAuth();
  const isAdmin = user?.role === 'admin';

  const [items, setItems] = useState<Patient[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);
  const [search, setSearch] = useState('');
  const [term, setTerm] = useState('');
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await listPatients({
        page,
        limit: PAGE_SIZE,
        search: term || undefined,
      });
      setItems(result.data);
      setTotal(result.total);
      setTotalPages(Math.max(result.totalPages, 1));
    } catch (err) {
      setError(extractApiError(err));
    } finally {
      setLoading(false);
    }
  }, [page, term]);

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

  function handleSearch(e: React.FormEvent) {
    e.preventDefault();
    setPage(1);
    setTerm(search.trim());
  }

  async function handleRemove(patient: Patient) {
    const confirm = await Swal.fire({
      icon: 'warning',
      title: 'Remover paciente?',
      text: patient.fullName,
      showCancelButton: true,
      confirmButtonText: 'Remover',
      cancelButtonText: 'Cancelar',
      confirmButtonColor: '#dc3545',
    });
    if (!confirm.isConfirmed) return;

    try {
      await removePatient(patient.id);
      await Swal.fire({
        icon: 'success',
        title: 'Paciente removido',
        timer: 1100,
        showConfirmButton: false,
      });
      load();
    } catch (err) {
      Swal.fire({ icon: 'error', title: 'Erro', text: extractApiError(err) });
    }
  }

  return (
    <>
      <PageHeader
        title="Pacientes"
        subtitle="Cadastro e histórico de pacientes"
        action={
          <Link href="/painel/pacientes/novo" className="btn btn-primary">
            <i className="bi bi-person-plus me-1" />
            Novo paciente
          </Link>
        }
      />

      <form className="row g-2 mb-3" onSubmit={handleSearch}>
        <div className="col-12 col-md-5">
          <div className="input-group">
            <span className="input-group-text">
              <i className="bi bi-search" />
            </span>
            <input
              className="form-control"
              placeholder="Buscar por nome, CPF, e-mail ou telefone"
              value={search}
              onChange={(e) => setSearch(e.target.value)}
              aria-label="Buscar paciente"
            />
          </div>
        </div>
        <div className="col-auto">
          <button className="btn btn-outline-primary" type="submit">
            Buscar
          </button>
        </div>
      </form>

      {error && <ErrorAlert message={error} onRetry={load} />}

      {loading ? (
        <Loading />
      ) : items.length === 0 ? (
        <EmptyState
          icon="bi-people"
          title="Nenhum paciente encontrado"
          description={
            term
              ? 'Ajuste a busca e tente novamente.'
              : 'Cadastre o primeiro paciente.'
          }
          action={
            !term && (
              <Link href="/painel/pacientes/novo" className="btn btn-primary">
                Novo paciente
              </Link>
            )
          }
        />
      ) : (
        <div className="card border-0 shadow-sm">
          <div className="table-responsive">
            <table className="table table-hover align-middle mb-0">
              <thead className="table-light">
                <tr>
                  <th>Nome</th>
                  <th>CPF</th>
                  <th>Contato</th>
                  <th>Status</th>
                  <th className="text-end">Ações</th>
                </tr>
              </thead>
              <tbody>
                {items.map((patient) => (
                  <tr key={patient.id}>
                    <td className="fw-semibold">{patient.fullName}</td>
                    <td>{formatCpf(patient.cpf)}</td>
                    <td className="text-muted">
                      {patient.email || patient.phone || '—'}
                    </td>
                    <td>
                      {patient.isActive ? (
                        <span className="badge text-bg-success">Ativo</span>
                      ) : (
                        <span className="badge text-bg-secondary">Inativo</span>
                      )}
                    </td>
                    <td className="text-end table-nowrap">
                      <Link
                        href={`/painel/pacientes/${patient.id}`}
                        className="btn btn-sm btn-outline-primary"
                      >
                        Abrir
                      </Link>
                      {isAdmin && (
                        <button
                          className="btn btn-sm btn-outline-danger ms-1"
                          onClick={() => handleRemove(patient)}
                          aria-label={`Remover ${patient.fullName}`}
                        >
                          <i className="bi bi-trash" />
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          <div className="card-body pt-0">
            <Pagination
              page={page}
              totalPages={totalPages}
              total={total}
              onChange={setPage}
            />
          </div>
        </div>
      )}
    </>
  );
}
