import { useEffect, useRef, useState } from 'react'
import { useParams, useSearchParams, useLocation, useBlocker, useNavigate } from 'react-router-dom'
import { Sparkles, Loader2, AlertTriangle } from 'lucide-react'
import { useFlowPilotSession } from '@/hooks/useFlowPilotSession'
import { FlowPilotIntake, FlowPilotSession, SessionBriefing } from '@/components/flowpilot'
import { aiSessionsApi } from '@/api'
import { toast } from '@/lib/toast'

export default function FlowPilotSessionPage() {
  const { sessionId } = useParams<{ sessionId?: string }>()
  const [searchParams, setSearchParams] = useSearchParams()
  const navigate = useNavigate()
  const location = useLocation()
  const prefill = (location.state as { prefill?: string } | null)?.prefill || ''
  const isPickup = searchParams.get('pickup') === 'true'
  const fp = useFlowPilotSession()
  const prefillHandledRef = useRef(false)

  // Block navigation when session is active
  const isActiveSession = fp.session?.status === 'active'
  const blocker = useBlocker(
    ({ currentLocation, nextLocation }) =>
      !!isActiveSession && currentLocation.pathname !== nextLocation.pathname
  )

  // Auto-submit when navigating from dashboard with prefilled problem
  useEffect(() => {
    if (prefill && !prefillHandledRef.current && !sessionId && !fp.session && !fp.isLoading) {
      prefillHandledRef.current = true
      fp.startSession({ intake_type: 'free_text', intake_content: { text: prefill } })
    }
  }, [prefill, sessionId, fp.session, fp.isLoading]) // eslint-disable-line react-hooks/exhaustive-deps
  const [pickingUp, setPickingUp] = useState(false)

  // Load existing session if ID in URL
  useEffect(() => {
    if (sessionId && !fp.session) {
      fp.loadSession(sessionId)
    }
  }, [sessionId]) // eslint-disable-line react-hooks/exhaustive-deps

  const handlePickupContinue = async () => {
    if (!sessionId) return
    setPickingUp(true)
    try {
      await aiSessionsApi.pickupSession(sessionId, { resume_mode: 'continue' })
      // Clear pickup param and reload the session as active
      setSearchParams({})
      await fp.loadSession(sessionId)
    } catch (e: unknown) {
      const message = e instanceof Error ? e.message : 'Failed to pick up session'
      toast.error(message)
    } finally {
      setPickingUp(false)
    }
  }

  const handlePickupFresh = async (context: string) => {
    if (!sessionId) return
    setPickingUp(true)
    try {
      await aiSessionsApi.pickupSession(sessionId, {
        resume_mode: 'fresh',
        additional_context: context,
      })
      setSearchParams({})
      await fp.loadSession(sessionId)
    } catch (e: unknown) {
      const message = e instanceof Error ? e.message : 'Failed to pick up session'
      toast.error(message)
    } finally {
      setPickingUp(false)
    }
  }

  // Error state
  if (fp.error && !fp.session) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <div className="glass-card-static p-6 text-center max-w-md">
          <p className="text-sm text-rose-400">{fp.error}</p>
          <button
            onClick={() => window.location.reload()}
            className="mt-3 text-xs text-muted-foreground hover:text-foreground transition-colors"
          >
            Try again
          </button>
        </div>
      </div>
    )
  }

  // Loading
  if (fp.isLoading && !fp.session) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <Loader2 size={24} className="animate-spin text-muted-foreground" />
      </div>
    )
  }

  // Intake screen (no session yet)
  if (!fp.session) {
    return (
      <div className="h-full p-6">
        <FlowPilotIntake onSubmit={fp.startSession} isLoading={fp.isLoading} defaultProblem={prefill} />
      </div>
    )
  }

  // Escalation pickup briefing
  if (isPickup && fp.session.status === 'requesting_escalation' && fp.session.escalation_reason) {
    // Build escalation package from session detail
    // The escalation_package is in the session but not directly on AISessionDetail —
    // we use what's available from the session fields
    const escalationPackage = {
      problem_summary: fp.session.problem_summary ?? undefined,
      escalation_reason: fp.session.escalation_reason ?? undefined,
      // Steps are available from the session detail
      steps_tried: fp.allSteps.map(step => ({
        step_type: step.step_type,
        description: (step.content as Record<string, string>)?.text || '',
      })),
    }

    return (
      <div className="flex h-full flex-col">
        {/* Header */}
        <div
          className="flex items-center gap-3 border-b px-5 py-3 shrink-0"
          style={{ borderColor: 'var(--glass-border)' }}
        >
          <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-amber-500/10">
            <Sparkles size={14} className="text-amber-400" />
          </span>
          <div className="flex-1 min-w-0">
            <h1 className="font-heading text-sm font-semibold text-foreground truncate">
              Escalation Pickup — {fp.session.problem_summary || 'FlowPilot Session'}
            </h1>
          </div>
          <span className="font-label rounded-md bg-amber-500/10 px-2 py-0.5 text-[0.625rem] uppercase tracking-wider text-amber-400 border border-amber-500/20">
            Awaiting pickup
          </span>
        </div>

        {/* Briefing */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="mx-auto max-w-2xl">
            <SessionBriefing
              escalationPackage={escalationPackage}
              onContinue={handlePickupContinue}
              onFresh={handlePickupFresh}
              isProcessing={pickingUp}
            />
          </div>
        </div>
      </div>
    )
  }

  // Active/completed session
  return (
    <div className="flex h-full flex-col">
      {/* Navigation guard modal */}
      {blocker.state === 'blocked' && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-xs">
          <div className="bg-card border border-border rounded-xl w-full max-w-md p-6 shadow-lg">
            <div className="flex items-center gap-3 mb-3">
              <span className="flex h-9 w-9 items-center justify-center rounded-lg bg-amber-500/10">
                <AlertTriangle size={18} className="text-amber-400" />
              </span>
              <h2 className="text-lg font-heading font-semibold text-foreground">Active Session</h2>
            </div>
            <p className="mb-4 text-sm text-muted-foreground">
              You have an active troubleshooting session. If you leave, your session will be paused and you can resume it later.
            </p>
            <div className="flex gap-2">
              <button
                onClick={() => blocker.reset()}
                className="flex-1 rounded-[10px] bg-gradient-to-r from-cyan-500 to-cyan-400 px-4 py-2.5 text-sm font-semibold text-[#101114] hover:opacity-90 active:scale-[0.97] transition-all"
              >
                Stay in Session
              </button>
              <button
                onClick={() => {
                  fp.pauseSession()
                  blocker.proceed()
                }}
                className="flex-1 rounded-[10px] bg-[rgba(255,255,255,0.04)] border border-[rgba(255,255,255,0.06)] px-4 py-2.5 text-sm font-medium text-foreground hover:border-[rgba(255,255,255,0.12)] transition-all"
              >
                Pause & Leave
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Header */}
      <div
        className="flex items-center gap-3 border-b px-5 py-3 shrink-0"
        style={{ borderColor: 'var(--glass-border)' }}
      >
        <span className="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10">
          <Sparkles size={14} className="text-primary" />
        </span>
        <div className="flex-1 min-w-0">
          <h1 className="font-heading text-sm font-semibold text-foreground truncate">
            {fp.session.problem_summary || 'FlowPilot Session'}
          </h1>
        </div>
        <span className="font-label rounded-md bg-card px-2 py-0.5 text-[0.625rem] uppercase tracking-wider text-muted-foreground border border-border">
          {fp.session.status}
        </span>
      </div>

      {/* Session content */}
      <div className="flex-1 min-h-0 flex flex-col">
        <FlowPilotSession
          session={fp.session}
          allSteps={fp.allSteps}
          currentStep={fp.currentStep}
          isProcessing={fp.isProcessing}
          canResolve={fp.canResolve}
          canEscalate={fp.canEscalate}
          documentation={fp.documentation}
          psaPushStatus={fp.psaPushStatus}
          psaPushError={fp.psaPushError}
          memberMappingWarning={fp.memberMappingWarning}
          onRespond={fp.respondToStep}
          onResolve={fp.resolveSession}
          onEscalate={fp.escalateSession}
          onPause={fp.pauseSession}
          onResume={fp.resumeOwnSession}
          onAbandon={async () => {
            await fp.abandonSession()
            navigate('/sessions')
          }}
          onRate={fp.rateSession}
          onReloadSession={() => fp.loadSession(fp.session!.id)}
        />
      </div>
    </div>
  )
}
