/**
 * BoostMedia AI Content Generator Admin - Settings Step (merged: post type + reporter + configure)
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useEffect, useState } from 'react'
import { Check, ChevronDown, ChevronLeft, ChevronRight } from 'lucide-react'
import { Button } from '../common'
import { SelectPostTypeContent } from './SelectPostTypeStep'
import { SelectReporterContent } from './SelectReporterStep'
import { ConfigureContent } from './ConfigureStep'
import type { GenerationConfig } from './SelectPostTypeStep'
import { t, isRtl } from '../../lib/i18n'

type SectionId = 'post-type' | 'reporter' | 'configure'

interface SettingsStepProps {
  config: GenerationConfig
  onUpdate: (config: GenerationConfig) => void
  onComplete: () => void
}

function AccordionSection({
  title,
  isOpen,
  isComplete,
  disabled,
  onToggle,
  children,
}: {
  title: string
  isOpen: boolean
  isComplete: boolean
  disabled?: boolean
  onToggle: () => void
  children: React.ReactNode
}) {
  return (
    <div
      className={`rounded-bc-md border transition-colors ${
        isOpen ? 'border-bc-primary/30 bg-white shadow-sm' : 'border-bc-gray-200 bg-bc-gray-50'
      } ${disabled ? 'opacity-50 pointer-events-none' : ''}`}
    >
      <button
        type="button"
        onClick={onToggle}
        disabled={disabled}
        className="flex w-full items-center justify-between gap-3 px-5 py-4 text-start"
      >
        <div className="flex items-center gap-3">
          <div
            className={`flex h-7 w-7 shrink-0 items-center justify-center rounded-full text-xs font-bold transition-colors ${
              isComplete
                ? 'bg-bc-success text-white'
                : isOpen
                  ? 'bg-bc-primary text-white'
                  : 'bg-bc-gray-200 text-bc-gray-500'
            }`}
          >
            {isComplete ? <Check className="h-4 w-4" /> : null}
          </div>
          <span className={`text-base font-semibold ${isOpen ? 'text-bc-gray-800' : 'text-bc-gray-600'}`}>
            {title}
          </span>
        </div>
        <ChevronDown
          className={`h-5 w-5 text-bc-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`}
        />
      </button>

      {isOpen && (
        <div className="border-t border-bc-gray-200 px-5 py-5">
          {children}
        </div>
      )}
    </div>
  )
}

function ConfirmContinueButton({ onClick }: { onClick: () => void }) {
  const ArrowIcon = isRtl() ? ChevronLeft : ChevronRight
  return (
    <button
      type="button"
      onClick={onClick}
      className="mt-4 inline-flex items-center gap-1.5 text-sm font-medium text-bc-teal hover:underline bg-transparent border-none cursor-pointer px-0"
    >
      {t('Confirm and continue')}
      <ArrowIcon className="w-4 h-4" />
    </button>
  )
}

export function SettingsStep({ config, onUpdate, onComplete }: SettingsStepProps) {
  const [openSection, setOpenSection] = useState<SectionId | null>(
    config.postType ? (config.reporterId ? 'configure' : 'reporter') : 'post-type'
  )
  const [confirmedPostType, setConfirmedPostType] = useState(Boolean(config.postType))
  const [confirmedReporter, setConfirmedReporter] = useState(Boolean(config.reporterId))

  useEffect(() => {
    if (config.postType) setConfirmedPostType(true)
  }, [config.postType])

  useEffect(() => {
    if (config.reporterId) setConfirmedReporter(true)
  }, [config.reporterId])

  const isPostTypeSelected = Boolean(config.postType)
  const isReporterSelected = Boolean(config.reporterId)
  const isConfigComplete = Boolean(config.topic && config.count)

  const isPostTypeComplete = isPostTypeSelected && confirmedPostType
  const isReporterComplete = isReporterSelected && confirmedReporter
  const allComplete = isPostTypeComplete && isReporterComplete && isConfigComplete

  const handleToggle = (section: SectionId) => {
    setOpenSection(prev => prev === section ? null : section)
  }

  const handleConfirmPostType = () => {
    setConfirmedPostType(true)
    setOpenSection('reporter')
  }

  const handleConfirmReporter = () => {
    setConfirmedReporter(true)
    setOpenSection('configure')
  }

  return (
    <div className="max-w-3xl mx-auto space-y-3">
      <AccordionSection
        title={t('Post Type & Category')}
        isOpen={openSection === 'post-type'}
        isComplete={isPostTypeComplete}
        onToggle={() => handleToggle('post-type')}
      >
        <SelectPostTypeContent config={config} onUpdate={(next) => {
          if (next.postType !== config.postType) {
            setConfirmedPostType(false)
          }
          onUpdate(next)
        }} />
        {isPostTypeSelected && !confirmedPostType && (
          <ConfirmContinueButton onClick={handleConfirmPostType} />
        )}
      </AccordionSection>

      <AccordionSection
        title={t('Reporter')}
        isOpen={openSection === 'reporter'}
        isComplete={isReporterComplete}
        disabled={!isPostTypeComplete}
        onToggle={() => handleToggle('reporter')}
      >
        <SelectReporterContent config={config} onUpdate={(next) => {
          if (next.reporterId !== config.reporterId) {
            setConfirmedReporter(false)
          }
          onUpdate(next)
        }} />
        {isReporterSelected && !confirmedReporter && (
          <ConfirmContinueButton onClick={handleConfirmReporter} />
        )}
      </AccordionSection>

      <AccordionSection
        title={t('Plan Configuration')}
        isOpen={openSection === 'configure'}
        isComplete={isConfigComplete}
        disabled={!isReporterComplete}
        onToggle={() => handleToggle('configure')}
      >
        <ConfigureContent config={config} onUpdate={onUpdate} />
      </AccordionSection>

      <div className="flex justify-end pt-4">
        <Button
          onClick={onComplete}
          disabled={!allComplete}
          size="lg"
          icon={<ChevronLeft className="w-5 h-5 ltr:rotate-180" />}
          iconPosition={isRtl() ? 'start' : 'end'}
        >
          {t('Continue to Technical Questions')}
        </Button>
      </div>
    </div>
  )
}
