import React, { useEffect, useState } from "react";
import { Avatar } from "../components/ui/Avatar";
import { Stethoscope, Mail, Phone, AlertTriangle } from "lucide-react";
import { doctorService } from "../services";

interface MedicoDetalhado {
  id: string;
  user_id?: string | null;
  nome: string;
  especialidade: string;
  crm: string;
  email: string;
  telefone?: string;
}

const ListaMedicos: React.FC = () => {
  const [medicos, setMedicos] = useState<MedicoDetalhado[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    async function load() {
      setLoading(true);
      setError(null);
      try {
        const list = await doctorService.list({ active: true });
        if (!list.length) {
          console.warn(
            '[ListaMedicos] Nenhum médico retornado. Verifique se a tabela "doctors" possui registros e se as variáveis VITE_SUPABASE_URL / VITE_SUPABASE_ANON_KEY apontam para produção.'
          );
        }
        if (!cancelled) {
          // Mapear para o formato esperado pelo componente
          const medicosFormatados = list.map((doctor) => {
            // Log para debug
            console.log("[ListaMedicos] Médico:", {
              id: doctor.id,
              name: doctor.full_name,
              user_id: doctor.user_id,
              has_user_id: !!doctor.user_id,
            });

            return {
              id: doctor.id,
              user_id: doctor.user_id,
              nome: doctor.full_name,
              especialidade: doctor.specialty || "Não informado",
              crm: doctor.crm,
              email: doctor.email,
              telefone: doctor.phone_mobile || "",
            };
          });
          setMedicos(medicosFormatados);
        }
      } catch (e) {
        console.error("Erro inesperado ao listar médicos", e);
        if (!cancelled) {
          setError("Erro inesperado ao listar médicos");
          setMedicos([]);
        }
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, []);

  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">
        {/* Cabeçalho Responsivo */}
        <div className="flex items-center gap-2 sm:gap-3">
          <Stethoscope className="w-5 h-5 sm:w-6 sm:h-6 text-indigo-600 flex-shrink-0" />
          <h2 className="text-xl sm:text-2xl lg:text-3xl font-bold text-gray-900">
            Médicos Cadastrados
          </h2>
        </div>

        {/* Estados de Loading/Error */}
        {loading && (
          <div className="text-sm sm:text-base text-gray-500 text-center py-8">
            Carregando médicos...
          </div>
        )}

        {!loading && error && (
          <div className="flex items-start sm:items-center gap-2 text-red-700 bg-red-50 border border-red-200 p-3 sm:p-4 rounded-lg text-sm sm:text-base">
            <AlertTriangle className="w-5 h-5 flex-shrink-0 mt-0.5 sm:mt-0" />
            <span>{error}</span>
          </div>
        )}

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

        {/* Grid de Médicos - Responsivo */}
        {!loading && !error && medicos.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">
            {medicos.map((medico) => (
              <article
                key={medico.id}
                className="bg-white rounded-lg sm:rounded-xl shadow-sm hover:shadow-md border border-gray-200 p-4 sm:p-5 lg:p-6 flex flex-col gap-2.5 sm:gap-3 transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500"
                tabIndex={0}
              >
                {/* Header do Card */}
                <header className="flex items-center gap-2 sm:gap-3">
                  <Avatar
                    src={medico.user_id ? { id: medico.user_id } : undefined}
                    name={medico.nome}
                    size="md"
                    color="green"
                  />
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-1.5 mb-1">
                      <Stethoscope className="w-4 h-4 text-indigo-600 flex-shrink-0" />
                      <h3 className="font-semibold text-sm sm:text-base lg:text-lg text-gray-900 truncate">
                        {medico.nome}
                      </h3>
                    </div>
                  </div>
                </header>

                {/* Informações do Médico */}
                <div className="space-y-1.5 sm:space-y-2">
                  <div className="text-xs sm:text-sm text-gray-700">
                    <strong className="font-medium">Especialidade:</strong>{" "}
                    <span className="break-words">{medico.especialidade}</span>
                  </div>
                  <div className="text-xs sm:text-sm text-gray-700">
                    <strong className="font-medium">CRM:</strong> {medico.crm}
                  </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">{medico.email}</span>
                  </div>
                  {medico.telefone && (
                    <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>{medico.telefone}</span>
                    </div>
                  )}
                </div>
              </article>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default ListaMedicos;
