import { useEffect, useMemo, useState } from 'react'

import { FeatureBadge, FeatureCallout } from '../components/FeatureState.jsx'
import { featurePanelClass } from '../components/featureStateStyles.js'
import { availabilityRepository } from '../repositories/availabilityRepository.js'
import { professionalRepository } from '../repositories/professionalRepository.js'

const cardClass = 'rounded-2xl border border-[#404040] bg-[#262626] shadow-sm'
const weekdays = [
  { label: 'Seg', value: 1 },
  { label: 'Ter', value: 2 },
  { label: 'Qua', value: 3 },
  { label: 'Qui', value: 4 },
  { label: 'Sex', value: 5 },
]

export function TeamPage({ navigate }) {
  const [professionals, setProfessionals] = useState([])
  const [availability, setAvailability] = useState([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')

  useEffect(() => {
    let active = true

    async function loadTeam() {
      try {
        setError('')
        const [professionalsData, availabilityData] = await Promise.all([
          professionalRepository.getAll(),
          availabilityRepository.getAll({ active: true }),
        ])

        if (!active) return

        setProfessionals(professionalsData)
        setAvailability(availabilityData)
      } catch (loadError) {
        if (!active) return
        setError(loadError.message || 'Erro ao carregar profissionais e disponibilidade.')
      } finally {
        if (active) setLoading(false)
      }
    }

    loadTeam()

    return () => {
      active = false
    }
  }, [])

  const availabilityByDoctor = useMemo(() => groupAvailabilityByDoctor(availability), [availability])

  return (
    <div className="mx-auto max-w-7xl space-y-6">
      {error ? (
        <FeatureCallout
          description={error}
          status="wip"
          title="Não foi possível carregar disponibilidade"
        />
      ) : null}

      <header className="flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-[#f5f5f5]">Profissionais</h1>
          <p className="mt-1 text-sm text-[#b8b8b8]">Equipe, agenda e cobertura operacional da clínica.</p>
        </div>
        <button
          className="h-10 rounded-sm bg-[#3b82f6] px-4 text-sm font-semibold text-white transition hover:bg-[#2563eb]"
          onClick={() => navigate('/agenda')}
          type="button"
        >
          Ver disponibilidade
        </button>
      </header>

      {loading ? (
        <p className="py-10 text-center text-sm text-[#a3a3a3]">Carregando profissionais...</p>
      ) : null}

      <section className="grid gap-4 md:grid-cols-2 xl:grid-cols-4" aria-label="Equipe medica">
        {professionals.map((professional) => (
          <article className={`${cardClass} ${featurePanelClass('live')} p-5`} key={professional.id}>
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="grid size-11 place-items-center rounded-full border border-[#3b82f6]/30 bg-[#3b82f6]/10 text-sm font-bold text-[#3b82f6]">
                  {initials(professional.name)}
                </div>
                <h2 className="mt-4 text-lg font-bold text-[#f5f5f5]">{professional.name}</h2>
                <p className="mt-1 text-sm text-[#a3a3a3]">{professional.role}</p>
              </div>
              <StatusPill status={professional.status} />
            </div>

            <dl className="mt-5 grid gap-3 text-sm">
              <Info label="Agenda" value={professional.schedule} />
              <Info label="Proximo horario" value={professional.nextSlot} />
              <Info label="Pacientes ativos" value={professional.patients} />
            </dl>
          </article>
        ))}
      </section>

      <section className={`${cardClass} ${featurePanelClass('live')} p-5`}>
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <div className="flex flex-wrap items-center gap-2">
              <h2 className="text-xl font-bold text-[#f5f5f5]">Mapa de cobertura</h2>
              <FeatureBadge status="live" />
            </div>
            <p className="mt-1 text-sm text-[#a3a3a3]">
              Disponibilidades ativas cadastradas em /rest/v1/doctor_availability.
            </p>
          </div>
          <button
            className="h-10 rounded-sm border border-[#404040] bg-[#303030] px-4 text-sm font-semibold text-[#e5e5e5] transition hover:border-[#3b82f6]"
            onClick={() => navigate('/configuracoes')}
            type="button"
          >
            Configurar regras
          </button>
        </div>

        <div className="mt-5 overflow-x-auto rounded-sm border border-[#404040]">
          <div className="grid min-w-[720px] grid-cols-[1.2fr_repeat(5,1fr)] bg-[#171717] text-xs font-bold uppercase tracking-[0.16em] text-[#a3a3a3]">
            {['Profissional', ...weekdays.map((weekday) => weekday.label)].map((label) => (
              <div className="border-b border-[#404040] px-4 py-3" key={label}>
                {label}
              </div>
            ))}
          </div>
          {professionals.map((professional) => (
            <div className="grid min-w-[720px] grid-cols-[1.2fr_repeat(5,1fr)] text-sm" key={professional.id}>
              <div className="border-b border-[#404040] px-4 py-3 font-semibold text-[#f5f5f5]">{professional.name}</div>
              {weekdays.map((weekday) => (
                <div className="border-b border-[#404040] px-4 py-3 text-[#b8b8b8]" key={`${professional.id}-${weekday.value}`}>
                  {formatCoverage(availabilityByDoctor.get(String(professional.id))?.[weekday.value])}
                </div>
              ))}
            </div>
          ))}
        </div>
      </section>
    </div>
  )
}

function Info({ label, value }) {
  return (
    <div>
      <dt className="text-xs font-semibold text-[#737373]">{label}</dt>
      <dd className="mt-1 text-[#e5e5e5]">{value}</dd>
    </div>
  )
}

function StatusPill({ status }) {
  const className =
    status === 'Disponivel'
      ? 'bg-emerald-500/20 text-emerald-400'
      : status === 'Em atendimento'
        ? 'bg-amber-500/20 text-amber-400'
        : 'bg-blue-500/20 text-blue-400'

  return <span className={`rounded px-2 py-1 text-[10px] font-bold ${className}`}>{status}</span>
}

function initials(name) {
  return String(name || '')
    .replace(/^(Dr\.|Dra\.|Nutri\.|Enf\.)\s+/i, '')
    .split(' ')
    .slice(0, 2)
    .map((part) => part[0])
    .join('')
    .toUpperCase()
}

function groupAvailabilityByDoctor(items) {
  const grouped = new Map()

  for (const item of items) {
    const doctorId = String(item.doctorId)
    const current = grouped.get(doctorId) || {}
    current[item.weekday] = [...(current[item.weekday] || []), item]
    grouped.set(doctorId, current)
  }

  return grouped
}

function formatCoverage(items = []) {
  const activeItems = items.filter((item) => item.active !== false)
  if (!activeItems.length) return 'Sem regra'

  return activeItems
    .map((item) => `${formatTime(item.startTime)}-${formatTime(item.endTime)}`)
    .join(', ')
}

function formatTime(value) {
  return String(value || '').slice(0, 5)
}
