import React, { useEffect, useMemo, useRef, useState } from 'react'
import { getModelosSubtabKeyFromSlug, getModelosSubtabSlugFromKey } from '../deepLinks'
import PesquisaTab from './PesquisaTab'
import RepositorioTab from './RepositorioTab'
import VisaoGeralTab from './VisaoGeralTab'

const SUBTABS = [
  { key: 'Pesquisar Modelos', label: 'Pesquisar Modelos' },
  { key: 'Repositório de Modelos', label: 'Repositório de Modelos' },
  { key: 'Visão Geral', label: 'Visão Geral' },
]

export default function ModelosEstatisticosTab({
  sessionId,
  authUser,
  onUsarModeloEmAvaliacao,
  onEditarModeloEmElaboracao = null,
  onAbrirModeloNoRepositorio = null,
  routeRequest = null,
  onRouteChange = null,
  onModoImersivoChange = null,
}) {
  const [activeSubtab, setActiveSubtab] = useState('Pesquisar Modelos')
  const [pesquisaMapaScrollRequest, setPesquisaMapaScrollRequest] = useState(null)
  const [repositorioModeloAberto, setRepositorioModeloAberto] = useState(false)
  const handledRouteRequestRef = useRef('')

  useEffect(() => {
    const requestKey = String(routeRequest?.requestKey || '').trim()
    if (!requestKey) return
    if (handledRouteRequestRef.current === requestKey) return
    handledRouteRequestRef.current = requestKey

    const nextSubtab = getModelosSubtabKeyFromSlug(routeRequest?.subtab)
    setActiveSubtab(routeRequest?.modeloId ? 'Repositório de Modelos' : nextSubtab)

    if (routeRequest?.scrollToMapa) {
      setPesquisaMapaScrollRequest({ requestKey })
    }
  }, [routeRequest])

  const pesquisaRouteRequest = useMemo(() => {
    const requestKey = String(routeRequest?.requestKey || '').trim()
    if (!requestKey) return null
    if (String(routeRequest?.subtab || '').trim() !== 'pesquisa') return null
    return routeRequest
  }, [routeRequest])

  const repositorioOpenRequest = useMemo(() => {
    const requestKey = String(routeRequest?.requestKey || '').trim()
    const modeloId = String(routeRequest?.modeloId || '').trim()
    if (!requestKey || !modeloId) return null
    return {
      requestKey,
      modeloId,
      modelTab: routeRequest?.modelTab || 'mapa',
      nomeModelo: routeRequest?.nomeModelo || modeloId,
      modeloArquivo: routeRequest?.modeloArquivo || '',
      returnIntent: routeRequest?.returnIntent || null,
    }
  }, [routeRequest])

  useEffect(() => {
    if (typeof onModoImersivoChange !== 'function') return undefined
    onModoImersivoChange(repositorioModeloAberto)
    return () => onModoImersivoChange(false)
  }, [repositorioModeloAberto, onModoImersivoChange])

  return (
    <div className="tab-content">
      {!repositorioModeloAberto ? (
        <div className="inner-tabs" role="tablist" aria-label="Abas de modelos estatísticos">
          {SUBTABS.map((tab) => (
            <button
              key={tab.key}
              type="button"
              className={activeSubtab === tab.key ? 'inner-tab-pill active' : 'inner-tab-pill'}
              onClick={() => {
                setActiveSubtab(tab.key)
                if (typeof onRouteChange === 'function') {
                  onRouteChange({
                    tab: 'modelos',
                    subtab: getModelosSubtabSlugFromKey(tab.key),
                  })
                }
              }}
            >
              {tab.label}
            </button>
          ))}
        </div>
      ) : null}

      <div className="tab-pane" hidden={activeSubtab !== 'Pesquisar Modelos'}>
        <PesquisaTab
          sessionId={sessionId}
          onUsarModeloEmAvaliacao={onUsarModeloEmAvaliacao}
          onAbrirModeloNoRepositorio={onAbrirModeloNoRepositorio}
          routeRequest={pesquisaRouteRequest}
          scrollToMapaRequest={pesquisaMapaScrollRequest}
          onRouteChange={onRouteChange}
        />
      </div>

      <div className="tab-pane" hidden={activeSubtab !== 'Repositório de Modelos'}>
        <RepositorioTab
          authUser={authUser}
          sessionId={sessionId}
          openModeloRequest={repositorioOpenRequest}
          onUsarModeloEmAvaliacao={onUsarModeloEmAvaliacao}
          onEditarModeloEmElaboracao={onEditarModeloEmElaboracao}
          onRouteChange={onRouteChange}
          onModeloAbertoChange={setRepositorioModeloAberto}
        />
      </div>

      <div className="tab-pane" hidden={activeSubtab !== 'Visão Geral'}>
        <VisaoGeralTab />
      </div>
    </div>
  )
}
