import type { Metadata } from 'next';
import Link from 'next/link';
import { cache } from 'react';
import { fetchPublic } from '@/lib/server-api';
import type { Dentist, Paginated } from '@/lib/types';

function photoUrlForDentist(dentist: Dentist): string | null {
  if (!dentist.photoUrl) return null;
  if (/^https?:\/\//i.test(dentist.photoUrl)) return dentist.photoUrl;
  const apiUrl =
    process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';
  return `${apiUrl}/dentists/${dentist.id}/photo`;
}

const loadDentists = cache(async (): Promise<Dentist[]> => {
  const { data } = await fetchPublic<Paginated<Dentist>>('/dentists?limit=100');
  return data?.data.filter((dentist) => dentist.isActive) ?? [];
});

export const metadata: Metadata = {
  title: 'Equipe',
  description: 'Conheça a equipe de dentistas da DentalFlow.',
};

function initials(name: string): string {
  return name
    .split(' ')
    .filter(Boolean)
    .slice(0, 2)
    .map((part) => part[0])
    .join('')
    .toUpperCase();
}

export default async function EquipePage() {
  const dentists = await loadDentists();

  return (
    <>
      <section className="df-hero text-center">
        <div className="container">
          <h1 className="display-5 fw-bold mb-3">Nossa equipe</h1>
          <p className="lead mb-0 mx-auto" style={{ maxWidth: 720 }}>
            Profissionais preparados para cuidar do seu sorriso com
            experiência e acolhimento.
          </p>
        </div>
      </section>

      <section className="container py-5">
        {dentists.length === 0 ? (
          <div className="text-center text-muted py-5">
            <i className="bi bi-people display-4 d-block mb-3" />
            <p className="mb-0">Nossa equipe estará disponível em breve.</p>
          </div>
        ) : (
          <div className="row g-4">
            {dentists.map((dentist) => (
              <div className="col-md-6 col-lg-4" key={dentist.id}>
                <div className="card h-100 border-0 shadow-sm df-card-hover">
                  {photoUrlForDentist(dentist) ? (
                    <div
                      className="card-img-top"
                      role="img"
                      aria-label={`Foto de ${dentist.fullName}`}
                      style={{
                        height: 220,
                        backgroundImage: `url(${JSON.stringify(photoUrlForDentist(dentist))})`,
                        backgroundPosition: 'center',
                        backgroundSize: 'cover',
                      }}
                    />
                  ) : (
                    <div
                      className="d-flex align-items-center justify-content-center bg-primary text-white display-4"
                      style={{ height: 220 }}
                      aria-hidden="true"
                    >
                      {initials(dentist.fullName)}
                    </div>
                  )}
                  <div className="card-body text-center p-4">
                    <h2 className="h5 card-title mb-2">{dentist.fullName}</h2>
                    {dentist.specialties.length > 0 && (
                      <p className="text-primary small fw-semibold mb-2">
                        {dentist.specialties.map((specialty) => specialty.name).join(' · ')}
                      </p>
                    )}
                    {dentist.bio && (
                      <p className="card-text text-muted small mb-0">
                        {dentist.bio}
                      </p>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </section>

      <section className="bg-light py-5">
        <div className="container text-center">
          <h2 className="fw-bold mb-3">Cuide do seu sorriso</h2>
          <p className="text-muted mb-4 mx-auto" style={{ maxWidth: 560 }}>
            Encontre o profissional ideal para o seu tratamento.
          </p>
          <Link href="/agendar" className="btn btn-primary btn-lg px-4">
            Agendar consulta
          </Link>
        </div>
      </section>
    </>
  );
}
