import React, { useEffect, useState } from "react";
import { Avatar } from "../components/ui/Avatar";
// Funções utilitárias para formatação
function formatCPF(cpf?: string) {
  if (!cpf) return "Não informado";
  const v = cpf.replace(/\D/g, "").slice(0, 11);
  if (v.length !== 11) return cpf;
  return v.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, "$1.$2.$3-$4");
}

function formatPhone(phone?: string) {
  if (!phone) return "Não informado";
  let v = phone.replace(/\D/g, "");
  if (v.length < 10) return phone;
  v = v.slice(0, 13);
  v = "+55 " + v;
  v = v.replace(/(\+55 )(\d{2})(\d)/, "$1$2 $3");
  v = v.replace(/(\+55 \d{2} )(\d{5})(\d{1,4})/, "$1$2-$3");
  return v;
}

function formatEmail(email?: string) {
  if (!email) return "Não informado";
  return email.trim().toLowerCase();
}
import { Users, Mail, Phone } from "lucide-react";
import { patientService } from "../services/index";
import type { Patient } from "../services/patients/types";

type Paciente = Patient;

const ListaPacientes: React.FC = () => {
  const [pacientes, setPacientes] = useState<Paciente[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchPacientes = async () => {
      setLoading(true);
      setError(null);
      try {
        const items = await patientService.list();
        if (!items.length) {
          console.warn(
            '[ListaPacientes] Nenhum paciente retornado. Verifique se a tabela "patients" possui registros.'
          );
        }
        setPacientes(items as Paciente[]);
      } catch (e) {
        console.error("Erro ao listar pacientes", e);
        setError("Falha ao carregar pacientes");
        setPacientes([]);
      } finally {
        setLoading(false);
      }
    };
    fetchPacientes();
  }, []);

  return (
    <div className="min-h-screen bg-gray-50 p-4 sm:p-6 lg:p-8">
      <div className="max-w-7xl mx-auto space-y-4 sm:space-y-6">
        <h2 className="text-xl sm:text-2xl lg:text-3xl font-bold mb-3 sm:mb-4 flex items-center gap-2 sm:gap-3">
          <Users className="w-5 h-5 sm:w-6 sm:h-6 text-blue-600 flex-shrink-0" />{" "}
          Pacientes Cadastrados
        </h2>

        {loading && (
          <div className="text-sm sm:text-base text-gray-500 text-center py-8">
            Carregando pacientes...
          </div>
        )}

        {!loading && error && (
          <div className="text-sm sm:text-base text-red-600 bg-red-50 border border-red-200 p-3 sm:p-4 rounded-lg">
            {error}
          </div>
        )}

        {!loading && !error && pacientes.length === 0 && (
          <div className="text-sm sm:text-base text-gray-500 text-center py-8">
            Nenhum paciente cadastrado.
          </div>
        )}

        {!loading && !error && pacientes.length > 0 && (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-5 lg:gap-6">
            {pacientes.map((paciente, idx) => (
              <div
                key={paciente.id}
                className={`rounded-lg sm:rounded-xl p-4 sm:p-5 lg:p-6 flex flex-col gap-2 sm:gap-2.5 transition-all border border-gray-200 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/50 ${
                  idx % 2 === 0 ? "bg-white" : "bg-gray-50"
                }`}
                tabIndex={0}
              >
                <div className="flex items-center gap-2 sm:gap-3 mb-1 sm:mb-2">
                  <Avatar
                    src={
                      paciente.avatar_url ||
                      (paciente.user_id ? { id: paciente.user_id } : undefined)
                    }
                    name={paciente.full_name}
                    size="md"
                    color="blue"
                  />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5">
                      <Users className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600 flex-shrink-0" />
                      <span className="font-semibold text-sm sm:text-base lg:text-lg truncate">
                        {paciente.full_name}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="space-y-1.5 sm:space-y-2">
                  <div className="text-xs sm:text-sm text-gray-700">
                    <strong className="font-medium">CPF:</strong>{" "}
                    {formatCPF(paciente.cpf)}
                  </div>
                  <div className="flex items-start gap-2 text-xs sm:text-sm text-gray-700">
                    <Mail className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0 mt-0.5" />
                    <span className="break-all">
                      {formatEmail(paciente.email)}
                    </span>
                  </div>
                  <div className="flex items-center gap-2 text-xs sm:text-sm text-gray-700">
                    <Phone className="w-3.5 h-3.5 sm:w-4 sm:h-4 flex-shrink-0" />
                    <span className="break-words">
                      {formatPhone(paciente.phone_mobile)}
                    </span>
                  </div>
                  <div className="text-xs sm:text-sm text-gray-500 pt-1">
                    <strong className="font-medium">Nascimento:</strong>{" "}
                    {paciente.birth_date
                      ? new Date(paciente.birth_date).toLocaleDateString()
                      : "Não informado"}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default ListaPacientes;
