import { useEffect, useMemo, useState } from 'react'
import { PenSquare, RotateCcw } from 'lucide-react'
import { Button, Card, Loader } from '../../components/common'
import { endpoints, getErrorMessage } from '../../api/client'
import { t, tf } 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 ContentStepProps {
  config: GenerationConfig
  reporter: Reporter | null
  technicalSummary: string
  technicalAnswers: Record<string, unknown>[]
  savedPlan: SavedContentPlan | null
  forceEdit: boolean
  sessionId: string | null
  initialState: Record<string, unknown>
  onSessionChange: (sessionId: string) => void
  onStateChange: (state: Record<string, unknown>) => void
  onBack: () => void
  onReuseSavedPlan: () => void
  onEditSavedPlan: () => void
  onStartFresh: () => void
  onContinue: (state: Record<string, unknown>) => void
  onSkip: () => void
}

function planFieldValue(values: string[] | undefined): string {
  return values && values.length > 0 ? values.join(', ') : '—'
}

function planPreviewRows(plan: ContentPlan) {
  return [
    { label: t('Audience'), value: plan.audience.primary || '—' },
    { label: t('Goal'), value: plan.goal.primary || '—' },
    { label: t('Focus Areas'), value: planFieldValue(plan.focus_areas) },
    { label: t('Standards'), value: planFieldValue(plan.standards_to_reference) },
    { label: t('Must Include'), value: planFieldValue(plan.must_include) },
    { label: t('Avoid'), value: planFieldValue(plan.avoid) },
    { label: t('CTA'), value: plan.cta_style || plan.goal.cta || '—' },
  ]
}

function summarizeResearchScope(plan: ContentPlan): string {
  if (!plan.research_enabled) {
    return t('Disabled')
  }

  const parts = [
    plan.research_scope.directive,
    plan.research_scope.languages.length > 0 ? tf('Languages: %s', plan.research_scope.languages.join(', ')) : '',
    plan.research_scope.regions.length > 0 ? tf('Regions: %s', plan.research_scope.regions.join(', ')) : '',
    plan.research_scope.source_preferences.length > 0 ? tf('Sources: %s', plan.research_scope.source_preferences.join(', ')) : '',
    plan.research_scope.freshness ? tf('Freshness: %s', plan.research_scope.freshness) : '',
  ].filter(Boolean)

  return parts.length > 0 ? parts.join(' • ') : t('Enabled')
}

function getTopicTreePillars(plan: ContentPlan | null | undefined) {
  return plan?.topic_tree?.pillars ?? []
}

function countTopicTreeAngles(plan: ContentPlan): number {
  const pillars = getTopicTreePillars(plan)
  const articleCount = pillars.reduce((total, pillar) => (
    total + (pillar.clusters || []).reduce((clusterTotal, cluster) => clusterTotal + (cluster.articles || []).length, 0)
  ), 0)
  if (articleCount > 0) return articleCount
  const fromCounts = pillars.reduce((total, pillar) => (
    total + (pillar.article_count || (pillar.clusters || []).reduce((ct, c) => ct + (c.article_count || 0), 0))
  ), 0)
  if (fromCounts > 0) return fromCounts
  return plan.topic_tree?.total_articles || 0
}

export function ContentStep({
  config,
  reporter,
  technicalSummary,
  technicalAnswers,
  savedPlan,
  forceEdit,
  sessionId,
  initialState,
  onSessionChange,
  onStateChange,
  onBack,
  onReuseSavedPlan,
  onEditSavedPlan,
  onStartFresh,
  onContinue,
  onSkip,
}: ContentStepProps) {
  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(() => {
    return {
      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,
      technical_summary: technicalSummary,
      technical_answers: technicalAnswers,
      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, technicalAnswers, technicalSummary])

  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>
    )
  }

  if (savedPlan?.still_valid && !forceEdit && !sessionId) {
    return (
      <Card className="max-w-3xl mx-auto">
        <h2 className="text-2xl font-bold text-bc-gray-800 mb-2">{t('Content Planning')}</h2>
        <p className="text-bc-gray-500 mb-6">{t('Content Plan')}</p>
        <div className="space-y-3 rounded-bc border border-bc-gray-200 bg-bc-gray-50 px-4 py-4 text-sm text-bc-gray-700">
          {planPreviewRows(savedPlan.content_plan || createEmptyContentPlan()).map((row) => (
            <div key={row.label}>
              <strong>{row.label}:</strong> {row.value}
            </div>
          ))}
          <div><strong>{t('Research')}:</strong> {summarizeResearchScope(savedPlan.content_plan || createEmptyContentPlan())}</div>
          <div>
            <strong>{t('Topic Tree')}:</strong>{' '}
            {countTopicTreeAngles(savedPlan.content_plan || createEmptyContentPlan()) > 0
              ? tf('%d angles across %d pillars', countTopicTreeAngles(savedPlan.content_plan || createEmptyContentPlan()), savedPlan.content_plan?.topic_tree?.pillars?.length || 0)
              : t('Not planned yet')}
          </div>
          <div><strong>{t('Summary')}:</strong> {savedPlan.summary || '—'}</div>
        </div>
        <div className="mt-6 flex flex-wrap justify-between gap-3">
          <div className="flex gap-2">
            <Button variant="ghost" onClick={onBack}>
              {t('Back')}
            </Button>
            <Button variant="ghost" onClick={onEditSavedPlan} icon={<PenSquare className="w-4 h-4" />}>
              {t('Edit content plan')}
            </Button>
            <Button variant="ghost" onClick={onStartFresh} icon={<RotateCcw className="w-4 h-4" />}>
              {t('Start fresh')}
            </Button>
          </div>
          <div className="flex gap-2">
            <Button variant="secondary" onClick={onSkip}>
              {t('Skip and generate')}
            </Button>
            <Button onClick={onReuseSavedPlan}>
              {t('Reuse')}
            </Button>
          </div>
        </div>
      </Card>
    )
  }

  return (
    <ConversationPhaseStep
      mode="generation_content"
      title={t('Content Planning')}
      subtitle={t('Refine the article direction with your reporter persona')}
      assistantLabel={reporter?.name || undefined}
      sessionId={sessionId}
      initialStructuredState={initialState}
      context={context}
      autoStartMessage="[SYSTEM] Begin content planning. Use the full reporter persona to shape your questions and suggestions. The reporter's style determines how the content will be written; help the user refine the content direction within that voice. Use the topic, generation settings, and technical context to ask the most useful editorial questions and build the content plan. For your first reply, use structured question_cards for any question that has clear radio or checkbox options, especially research scope, source preferences, target audience, focus areas, CTA style, and outline preferences. Include suggested_index or suggested_indices and always set has_other=true."
      onSessionChange={onSessionChange}
      onStateChange={onStateChange}
      onBack={onBack}
      onContinue={onContinue}
      onSkip={onSkip}
      continueLabel={t('Generate')}
      skipLabel={t('Skip and generate')}
      renderSidebar={({ draftState }) => {
        const plan = ((draftState.content_plan as ContentPlan | undefined) || createEmptyContentPlan())
        const topicTreePillars = getTopicTreePillars(plan)
        return (
          <div className="space-y-3 text-sm text-bc-gray-700">
            <div className="font-medium text-bc-gray-800">{t('Content Plan')}</div>
            {planPreviewRows(plan).map((row) => (
              <div key={row.label}>
                <strong>{row.label}:</strong> {row.value}
              </div>
            ))}
            <div>
              <strong>{t('Summary')}:</strong> {plan.summary || '—'}
            </div>
            <div>
              <strong>{t('Research')}:</strong> {summarizeResearchScope(plan)}
            </div>
            <div>
              <strong>{t('Topic Tree')}:</strong>{' '}
              {countTopicTreeAngles(plan) > 0
                ? tf('%d angles across %d pillars', countTopicTreeAngles(plan), topicTreePillars.length)
                : t('Not planned yet')}
            </div>
            {topicTreePillars.length > 0 ? (
              <div className="space-y-2 rounded-bc border border-bc-gray-200 bg-bc-gray-50 p-3">
                {topicTreePillars.map((pillar) => (
                  <div key={pillar.id}>
                    <div className="font-medium text-bc-gray-800">{pillar.title || (pillar as any).name || (pillar as any).topic || t('Untitled pillar')}</div>
                    {(pillar.clusters || []).map((cluster) => (
                      <div key={cluster.id} className="mt-1 ms-3">
                        <div className="text-xs font-medium text-bc-gray-600">{cluster.title || (cluster as any).name || (cluster as any).topic || t('Untitled cluster')}</div>
                        <div className="mt-1 flex flex-wrap gap-1">
                          {(cluster.articles || []).map((article) => (
                            <span
                              key={article.id}
                              className="rounded-full bg-white px-2 py-1 text-xs text-bc-gray-700 border border-bc-gray-200"
                            >
                              {article.angle}
                            </span>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                ))}
              </div>
            ) : null}
          </div>
        )
      }}
    />
  )
}
