import { useEffect, useMemo, useState } from 'react'
import { Card, Loader } from '../../components/common'
import { endpoints, getErrorMessage } from '../../api/client'
import { t } from '../../lib/i18n'
import type { ContentPlan, PostStructure, Reporter, SavedContentPlan } from '../../types'
import type { GenerationConfig } from '../../components/generator'
import { ConversationPhaseStep } from './ConversationPhaseStep'
import { createEmptyContentPlan } from './conversation-utils'

interface IntentStepProps {
  config: GenerationConfig
  reporter: Reporter | null
  savedPlan: SavedContentPlan | null
  sessionId: string | null
  initialState: Record<string, unknown>
  onSessionChange: (sessionId: string) => void
  onStateChange: (state: Record<string, unknown>) => void
  onContinue: (state: Record<string, unknown>) => void
  onBack: () => void
  onSkip: () => void
  submitting?: boolean
}

function intentFieldValue(value: unknown): string {
  if (!value) return '—'
  if (typeof value === 'string') return value || '—'
  if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '—'
  return '—'
}

export function IntentStep({
  config,
  reporter,
  savedPlan,
  sessionId,
  initialState,
  onSessionChange,
  onStateChange,
  onContinue,
  onBack,
  onSkip,
  submitting = false,
}: IntentStepProps) {
  const [structure, setStructure] = useState<PostStructure | null>(null)
  const [loading, setLoading] = useState(true)
  const [loadError, setLoadError] = useState<string | null>(null)

  useEffect(() => {
    let cancelled = false

    void (async () => {
      setLoading(true)
      setLoadError(null)
      try {
        const res = await endpoints.getStructure(config.postType)
        if (!cancelled) {
          setStructure(res.data as PostStructure)
        }
      } catch (error) {
        if (!cancelled) {
          setLoadError(getErrorMessage(error, t('Unknown error')))
        }
      } finally {
        if (!cancelled) {
          setLoading(false)
        }
      }
    })()

    return () => {
      cancelled = true
    }
  }, [config.postType])

  const context = useMemo(() => ({
    post_type: structure ? {
      slug: structure.post_type,
      label: structure.post_type_label,
      meta_fields: structure.meta_fields || [],
    } : null,
    topic: config.topic,
    count: config.count,
    length: config.length,
    generation_type: config.generationType,
    reporter,
    sprint_mode: true,
    article_count: config.count,
    saved_content_plan: savedPlan ? {
      summary: savedPlan.summary,
      content_plan: savedPlan.content_plan,
      still_valid: savedPlan.still_valid,
    } : null,
  }), [config.count, config.generationType, config.length, config.topic, reporter, savedPlan, structure])

  if (loading) {
    return (
      <div className="py-16 flex items-center justify-center">
        <Loader />
      </div>
    )
  }

  if (loadError) {
    return (
      <Card className="max-w-2xl mx-auto text-center py-12">
        <p className="text-bc-error mb-4">{t('Error loading content types')}</p>
        <p className="text-bc-gray-500 text-sm">{loadError}</p>
      </Card>
    )
  }

  return (
    <ConversationPhaseStep
      mode="generation_content"
      title={t('Intent Collection')}
      subtitle={t('Tell your reporter what you need — the research sprint will handle the rest')}
      assistantLabel={reporter?.name || undefined}
      sessionId={sessionId}
      initialStructuredState={initialState}
      context={context}
      autoStartMessage="[SYSTEM] Begin intent collection in RESEARCH-FIRST mode. Your job is to understand the user's INTENT, not to plan specific article topics or build a topic tree. Focus on understanding: 1) What the user's audience needs 2) What their goal is 3) What areas they want to focus on 4) Research preferences (scope, languages, freshness, source types). Use structured question_cards for questions with clear options. When you have a clear picture of all four areas, set ready: true. The research sprint will handle topic discovery and article formation."
      onSessionChange={onSessionChange}
      onStateChange={onStateChange}
      onBack={onBack}
      onContinue={onContinue}
      onSkip={onSkip}
      submitting={submitting}
      continueLabel={
        submitting
          ? t('Submitting research...')
          : config.generationType === 'repeating'
            ? t('Save plan and schedule')
            : t('Start research')
      }
      skipLabel={
        submitting
          ? t('Submitting research...')
          : config.generationType === 'repeating'
            ? t('Save plan and schedule')
            : t('Skip to research')
      }
      renderSidebar={({ draftState }) => {
        const plan = ((draftState.content_plan as ContentPlan | undefined) || createEmptyContentPlan())
        return (
          <div className="space-y-3 text-sm text-bc-gray-700">
            <div className="font-medium text-bc-gray-800">{t('Collected Intent')}</div>

            <div>
              <strong>{t('Audience')}:</strong> {intentFieldValue(plan.audience?.primary)}
            </div>

            <div>
              <strong>{t('Goal')}:</strong> {intentFieldValue(plan.goal?.primary)}
            </div>

            <div>
              <strong>{t('Focus Areas')}:</strong> {intentFieldValue(plan.focus_areas)}
            </div>

            <div>
              <strong>{t('Research Scope')}:</strong>{' '}
              {plan.research_scope?.directive || '—'}
            </div>

            {plan.must_include && plan.must_include.length > 0 && (
              <div>
                <strong>{t('Must Include')}:</strong> {plan.must_include.join(', ')}
              </div>
            )}

            {plan.avoid && plan.avoid.length > 0 && (
              <div>
                <strong>{t('Avoid')}:</strong> {plan.avoid.join(', ')}
              </div>
            )}

            <div>
              <strong>{t('Summary')}:</strong> {plan.summary || '—'}
            </div>
          </div>
        )
      }}
    />
  )
}
