/**
 * BoostMedia AI Content Generator Admin - Select Reporter Step
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useCallback, useEffect, useRef, useState } from 'react'
import { ChevronLeft, ChevronRight, Sparkles, Star } from 'lucide-react'
import { Badge, Button, Loader } from '../common'
import { ReporterBuilder } from '../reporters/ReporterBuilder'
import { endpoints } from '../../api/client'
import type { Reporter } from '../../types'
import type { GenerationConfig } from './SelectPostTypeStep'
import { t, isRtl } from '../../lib/i18n'

interface SelectReporterStepProps {
  config: GenerationConfig
  onUpdate: (config: GenerationConfig) => void
  onBack: () => void
  onNext: () => void
}

function formatReporterSummary(reporter: Reporter): string {
  return [reporter.writing_style, reporter.tone, reporter.depth_level].map((item) => t(item)).join(' / ')
}

export interface SelectReporterContentProps {
  config: GenerationConfig
  onUpdate: (config: GenerationConfig) => void
}

export function SelectReporterContent({
  config,
  onUpdate,
}: SelectReporterContentProps) {
  const [reporters, setReporters] = useState<Reporter[]>([])
  const [loading, setLoading] = useState(true)
  const [builderOpen, setBuilderOpen] = useState(false)
  const configRef = useRef(config)

  useEffect(() => {
    configRef.current = config
  }, [config])

  const loadReporters = useCallback(async () => {
    setLoading(true)
    try {
      const res = await endpoints.getReporters()
      const items = (res.data as Reporter[]) || []
      setReporters(items)

      if (!configRef.current.reporterId && items.length > 0) {
        const defaultReporter = items.find((item) => item.is_default) || items[0]
        onUpdate({
          ...configRef.current,
          reporterId: defaultReporter.id,
        })
      }
    } finally {
      setLoading(false)
    }
  }, [onUpdate])

  useEffect(() => {
    void loadReporters()
  }, [loadReporters])

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

  return (
    <div>
      <div className="mb-4 flex items-center justify-end">
        <Button size="sm" variant="secondary" onClick={() => setBuilderOpen(true)} icon={<Sparkles className="w-4 h-4" />}>
          {t('Create with AI')}
        </Button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {reporters.map((reporter) => (
          <button
            key={reporter.id}
            type="button"
            onClick={() => onUpdate({
              ...configRef.current,
              reporterId: reporter.id,
            })}
            className={`rounded-bc-md border-2 p-5 text-start transition-all ${
              config.reporterId === reporter.id
                ? 'border-bc-primary bg-bc-primary-light shadow-md'
                : 'border-bc-gray-200 bg-white hover:border-bc-gray-300'
            }`}
          >
            <div className="flex items-start justify-between gap-3">
              <div>
                <div className="flex items-center gap-2 flex-wrap">
                  <h3 className="text-lg font-semibold text-bc-gray-800">{reporter.name}</h3>
                  {reporter.is_default ? (
                    <Badge variant="primary" dot>{t('Default Reporter')}</Badge>
                  ) : null}
                </div>
                <p className="text-sm text-bc-gray-500 mt-1">{formatReporterSummary(reporter)}</p>
              </div>
              {config.reporterId === reporter.id ? (
                <Star className="w-5 h-5 text-bc-primary shrink-0" />
              ) : null}
            </div>

            <div className="flex flex-wrap gap-2 mt-3">
              {(reporter.specializations || []).slice(0, 4).map((item) => (
                <Badge key={item} variant="default">{item}</Badge>
              ))}
            </div>
          </button>
        ))}
      </div>

      <ReporterBuilder
        open={builderOpen}
        onClose={() => setBuilderOpen(false)}
        onSaved={(reporter) => {
          setBuilderOpen(false)
          void loadReporters()
          onUpdate({
            ...configRef.current,
            reporterId: reporter.id,
          })
        }}
        onUseManualDraft={() => {
          setBuilderOpen(false)
        }}
      />
    </div>
  )
}

export function SelectReporterStep({
  config,
  onUpdate,
  onBack,
  onNext,
}: SelectReporterStepProps) {
  return (
    <div className="max-w-4xl mx-auto">
      <div className="mb-8 flex flex-col gap-4 text-center sm:flex-row sm:items-start sm:justify-between sm:text-start">
        <div className="flex-1">
          <h2 className="text-2xl font-bold text-bc-gray-800 mb-2">
            {t('Select Reporter')}
          </h2>
          <p className="text-bc-gray-500">
            {t('Choose the reporter persona that should shape this generation')}
          </p>
        </div>
      </div>

      <SelectReporterContent config={config} onUpdate={onUpdate} />

      <div className="flex justify-between mt-8">
        <Button variant="ghost" onClick={onBack} icon={<ChevronRight className="w-5 h-5 ltr:rotate-180" />} iconPosition={isRtl() ? 'end' : 'start'}>
          {t('Back')}
        </Button>
        <Button
          onClick={onNext}
          disabled={!config.reporterId}
          size="lg"
          icon={<ChevronLeft className="w-5 h-5 ltr:rotate-180" />}
          iconPosition={isRtl() ? 'start' : 'end'}
        >
          {t('Next')}
        </Button>
      </div>
    </div>
  )
}
