import Link from 'next/link'
import { notFound } from 'next/navigation'
import { serverGet } from '@/lib/api'
import { ldJson } from '@/lib/format'
import { BookConsultation } from '@/components/BookConsultation'

const SITE = process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'

interface Provider {
  id: number; type?: string; display_name: string; specialty?: string | null; gender?: string | null
  experience_years?: number | null; bio?: string | null; qualifications?: string[] | null
  conditions_treated?: string[] | null; services_offered?: string[] | null; languages?: string[] | null
  photo?: string | null; consult_fee?: number | string | null; online_fee?: number | string | null
  offers_online?: boolean; is_verified?: boolean; registration_number?: string | null
}

async function getProvider(id: string): Promise<Provider | null> {
  try { const r = await serverGet<{ data: Provider } | Provider>(`/providers/${id}`, 300); return (r as { data?: Provider }).data ?? (r as Provider) } catch { return null }
}

export async function generateMetadata({ params }: { params: { id: string } }) {
  const p = await getProvider(params.id)
  if (!p) return { title: 'Provider' }
  const role = p.specialty || p.type || 'Health professional'
  const desc = (p.bio?.slice(0, 155)) || `Book a consultation with ${p.display_name}${p.specialty ? `, ${p.specialty}` : ''} on Fitorza — online or in person.`
  return {
    title: `${p.display_name}${p.specialty ? ` — ${p.specialty}` : ''}`,
    description: desc,
    alternates: { canonical: `/providers/${params.id}` },
    openGraph: {
      title: `${p.display_name} · ${role}`,
      description: desc,
      type: 'profile',
      url: `/providers/${params.id}`,
      images: p.photo ? [{ url: p.photo }] : undefined,
    },
  }
}

export default async function ProviderDetail({ params }: { params: { id: string } }) {
  const p = await getProvider(params.id)
  if (!p) notFound()

  const isMedical = (p.type ?? '').toLowerCase().includes('doctor') || (p.type ?? '').toLowerCase().includes('dietitian') || !!p.registration_number
  const providerLd = {
    '@context': 'https://schema.org',
    '@type': isMedical ? 'Physician' : 'Person',
    name: p.display_name,
    url: `${SITE}/providers/${p.id}`,
    image: p.photo || undefined,
    medicalSpecialty: p.specialty || undefined,
    description: p.bio || undefined,
    knowsLanguage: p.languages?.length ? p.languages : undefined,
    jobTitle: p.specialty || p.type || undefined,
  }

  return (
    <div className="container-x py-6">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: ldJson(providerLd) }} />
      <nav className="mb-4 text-xs text-muted"><Link href="/providers">Doctors</Link> / <span className="text-ink">{p.display_name}</span></nav>
      <div className="grid gap-6 md:grid-cols-[1fr_320px]">
        <div>
          <div className="flex gap-4">
            <div className="flex h-24 w-24 shrink-0 items-center justify-center overflow-hidden rounded-full bg-soft">
              {p.photo ? /* eslint-disable-next-line @next/next/no-img-element */ <img src={p.photo} alt={p.display_name} className="h-full w-full object-cover" /> : <span className="text-2xl font-bold text-hair">Dr</span>}
            </div>
            <div>
              <h1 className="h-section flex items-center gap-2">{p.display_name}{p.is_verified && <span className="tag tag-otc">Verified</span>}</h1>
              <div className="text-sm text-muted">{p.specialty || p.type}{p.experience_years ? ` · ${p.experience_years} yrs` : ''}</div>
              {p.registration_number && <div className="text-[12px] text-muted">Reg #: {p.registration_number}</div>}
            </div>
          </div>
          {p.bio && <p className="mt-5 text-sm leading-relaxed text-muted">{p.bio}</p>}
          {!!p.qualifications?.length && <div className="mt-5"><h2 className="mb-2 font-bold">Qualifications</h2><ul className="list-inside list-disc text-sm text-muted">{p.qualifications.map((q) => <li key={q}>{q}</li>)}</ul></div>}
          {!!p.conditions_treated?.length && <div className="mt-5"><h2 className="mb-2 font-bold">Conditions treated</h2><div className="flex flex-wrap gap-2">{p.conditions_treated.map((c) => <span key={c} className="tag bg-soft text-muted">{c}</span>)}</div></div>}
          {!!p.services_offered?.length && <div className="mt-5"><h2 className="mb-2 font-bold">Services</h2><div className="flex flex-wrap gap-2">{p.services_offered.map((s) => <span key={s} className="tag bg-soft text-muted">{s}</span>)}</div></div>}
        </div>
        <BookConsultation
          providerId={p.id}
          consultFee={p.consult_fee}
          onlineFee={p.online_fee}
          offersOnline={p.offers_online}
        />
      </div>
    </div>
  )
}
