import { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { PageMeta } from '@/components/common/PageMeta'
import { l1Api } from '@/api/l1'
import { L1WalkTreeVariant } from '@/components/l1/L1WalkTreeVariant'
import { L1WalkAdhocVariant } from '@/components/l1/L1WalkAdhocVariant'
import type { WalkSession } from '@/types/l1'

export default function L1WalkPage() {
  const { sessionId } = useParams<{ sessionId: string }>()
  const navigate = useNavigate()
  const [session, setSession] = useState<WalkSession | null>(null)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!sessionId) return
    l1Api.getSession(sessionId)
      .then(setSession)
      .catch((err) => {
        const msg = err?.response?.data?.detail || err?.message || 'Failed to load session'
        setError(typeof msg === 'string' ? msg : 'Failed to load session')
      })
  }, [sessionId])

  if (error) {
    return (
      <div className="overflow-y-auto h-full">
        <PageMeta title="L1 Walk" />
        <div className="max-w-4xl mx-auto px-6 pt-12 text-muted-foreground">
          {error}
        </div>
      </div>
    )
  }
  if (!session) {
    return (
      <div className="overflow-y-auto h-full">
        <PageMeta title="L1 Walk" />
        <div className="max-w-4xl mx-auto px-6 pt-12 text-muted-foreground">Loading…</div>
      </div>
    )
  }

  const handleDone = () => navigate('/l1')

  // Phase 1: adhoc variant handles session_kind='adhoc'. Tree variant handles flow/proposal.
  if (session.session_kind === 'adhoc') {
    return (
      <>
        <PageMeta title="L1 Walk" />
        <L1WalkAdhocVariant
          session={session}
          onSessionUpdate={setSession}
          onDone={handleDone}
        />
      </>
    )
  }

  return (
    <>
      <PageMeta title="L1 Walk" />
      <L1WalkTreeVariant
        session={session}
        onSessionUpdate={setSession}
        onDone={handleDone}
      />
    </>
  )
}
