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

import { useMemo } from 'react'
import { ChevronLeft, ChevronRight } from 'lucide-react'
import type { GenerationConfig } from './SelectPostTypeStep'
import { Button, Card, HelpTooltip } from '../common'
import { TagInput } from './TagInput'
import { t, isRtl } from '../../lib/i18n'

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

const countPresets = [10, 50, 100, 500, 1000]
const weekdayOptions = [
  { value: 0, label: t('Sun') },
  { value: 1, label: t('Mon') },
  { value: 2, label: t('Tue') },
  { value: 3, label: t('Wed') },
  { value: 4, label: t('Thu') },
  { value: 5, label: t('Fri') },
  { value: 6, label: t('Sat') },
]

function ToggleSwitch({
  checked,
  onChange,
}: {
  checked: boolean
  onChange: () => void
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={onChange}
      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 border-none focus:outline-none focus:ring-2 focus:ring-bc-primary focus:ring-offset-2 ${
        checked ? 'bg-bc-primary' : 'bg-bc-gray-300'
      }`}
    >
      <span
        className="absolute top-1 h-4 w-4 rounded-full bg-white shadow transition-all duration-200"
        style={{ insetInlineStart: checked ? '1.5rem' : '0.25rem' }}
      />
    </button>
  )
}

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

export function ConfigureContent({
  config,
  onUpdate,
}: ConfigureContentProps) {
  const selectedTermCount = config.term ? config.term.split(',').filter(Boolean).length : 0
  const hasMultipleCategories = selectedTermCount > 1

  const lengthOptions = useMemo(() => [
    { value: 'auto' as const, label: t('AI decides'), description: t('Based on samples') },
    { value: 'short' as const, label: t('Short'), description: t('~300 words') },
    { value: 'medium' as const, label: t('Medium'), description: t('~600 words') },
    { value: 'long' as const, label: t('Long'), description: t('~1000 words') },
  ], [])

  const repeatSummary = useMemo(() => {
    if (config.generationType !== 'repeating') {
      return ''
    }

    const unitLabel = config.repeatUnit === 'day'
      ? t(config.repeatEvery === 1 ? 'day' : 'days')
      : config.repeatUnit === 'month'
        ? t(config.repeatEvery === 1 ? 'month' : 'months')
        : t(config.repeatEvery === 1 ? 'week' : 'weeks')
    const weekdayLabel = config.repeatUnit === 'week' && config.repeatWeekdays.length > 0
      ? ` • ${config.repeatWeekdays.map((weekday) => weekdayOptions.find((option) => option.value === weekday)?.label || weekday).join(', ')}`
      : ''
    const budgetParts = [
      config.maxTotalRuns ? `${t('Up to')} ${config.maxTotalRuns} ${t(config.maxTotalRuns === 1 ? 'run' : 'runs')}` : '',
      config.maxTotalPosts ? `${t('Up to')} ${config.maxTotalPosts} ${t(config.maxTotalPosts === 1 ? 'post' : 'posts')}` : '',
      config.stopAfterMonths ? `${t('Stop after')} ${config.stopAfterMonths} ${t(config.stopAfterMonths === 1 ? 'month' : 'months')}` : '',
    ].filter(Boolean)

    return `${t('Every')} ${config.repeatEvery > 1 ? `${config.repeatEvery} ` : ''}${unitLabel}`.replace(/\s+/g, ' ').trim()
      + `${weekdayLabel} • ${String(config.repeatHour).padStart(2, '0')}:00`
      + (budgetParts.length > 0 ? ` • ${budgetParts.join(' • ')}` : '')
  }, [config.generationType, config.maxTotalPosts, config.maxTotalRuns, config.repeatEvery, config.repeatHour, config.repeatUnit, config.repeatWeekdays, config.stopAfterMonths])

  const updateNullablePositiveNumber = (
    key: 'stopAfterMonths' | 'maxTotalRuns' | 'maxTotalPosts',
    value: string,
  ) => {
    const normalized = value.trim()
    onUpdate({
      ...config,
      [key]: normalized === '' ? null : Math.max(1, parseInt(normalized, 10) || 1),
    })
  }

  return (
    <div>
      <div className="space-y-6">
        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2">
            {t('Plan name')}
          </label>
          <p className="text-sm text-bc-gray-500 mb-3">
            {t('Use a clear internal name so you can manage this plan later from the Content Plans dashboard.')}
          </p>
          <input
            type="text"
            value={config.planName}
            onChange={(e) => onUpdate({ ...config, planName: e.target.value })}
            placeholder={t('e.g.: Fire pumps monthly blog plan')}
            className="
              w-full p-3 rounded-bc
              border border-bc-gray-300
              bg-white text-bc-gray-800
              placeholder:text-bc-gray-400
              focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
              transition-all duration-200
            "
          />
        </Card>

        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2">
            {t('Plan execution')}
          </label>
          <p className="mb-3 text-sm text-bc-gray-500">
            {t('Choose whether this plan runs once or keeps running automatically, and set its publishing behavior in the same place.')}
          </p>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {[
              {
                value: 'one_time' as const,
                label: t('One-time plan'),
                description: t('Run this plan manually whenever you choose'),
              },
              {
                value: 'repeating' as const,
                label: t('Repeating plan'),
                description: t('Keep this plan active and let WordPress run it on a schedule'),
              },
            ].map((option) => (
              <button
                key={option.value}
                type="button"
                onClick={() => onUpdate({
                  ...config,
                  generationType: option.value,
                })}
                className={`
                  rounded-bc border-2 p-4 text-start transition-all duration-150 bc-focus-visible
                  ${config.generationType === option.value
                    ? 'border-bc-primary bg-bc-primary-light'
                    : 'border-bc-gray-200 bg-white hover:border-bc-gray-300'
                  }
                `}
              >
                <p className={`font-semibold ${config.generationType === option.value ? 'text-bc-primary' : 'text-bc-gray-700'}`}>
                  {option.label}
                </p>
                <p className="mt-1 text-sm text-bc-gray-500">{option.description}</p>
              </button>
            ))}
          </div>

          <div className="mt-4 rounded-bc border border-bc-gray-200 bg-bc-gray-50 p-4">
            {config.generationType === 'repeating' ? (
              <div className="space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-[minmax(0,140px)_minmax(0,1fr)_minmax(0,160px)] gap-4">
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Repeat every')}
                    </label>
                    <input
                      type="number"
                      min={1}
                      value={config.repeatEvery}
                      onChange={(e) => onUpdate({ ...config, repeatEvery: Math.max(1, parseInt(e.target.value, 10) || 1) })}
                      className="w-full rounded-bc border border-bc-gray-300 px-3 py-2"
                    />
                  </div>
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Time unit')}
                    </label>
                    <select
                      value={config.repeatUnit}
                      onChange={(e) => {
                        const nextUnit = e.target.value as GenerationConfig['repeatUnit']
                        onUpdate({
                          ...config,
                          repeatUnit: nextUnit,
                          repeatFrequency: nextUnit === 'month' ? 'monthly' : nextUnit === 'day' ? 'daily' : 'weekly',
                          repeatWeekdays: nextUnit === 'week' ? config.repeatWeekdays : [],
                        })
                      }}
                      className="w-full rounded-bc border border-bc-gray-300 px-3 py-2"
                    >
                      <option value="day">{t('Day')}</option>
                      <option value="week">{t('Week')}</option>
                      <option value="month">{t('Month')}</option>
                    </select>
                  </div>
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Run hour')}
                    </label>
                    <select
                      value={config.repeatHour}
                      onChange={(e) => onUpdate({ ...config, repeatHour: Number(e.target.value) })}
                      className="w-full rounded-bc border border-bc-gray-300 px-3 py-2"
                    >
                      {Array.from({ length: 24 }, (_, hour) => (
                        <option key={hour} value={hour}>
                          {String(hour).padStart(2, '0')}:00
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                {config.repeatUnit === 'week' ? (
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Run on weekday(s)')}
                    </label>
                    <div className="flex flex-wrap gap-2">
                      {weekdayOptions.map((weekday) => {
                        const selected = config.repeatWeekdays.includes(weekday.value)
                        return (
                          <button
                            key={weekday.value}
                            type="button"
                            onClick={() => onUpdate({
                              ...config,
                              repeatWeekdays: selected
                                ? config.repeatWeekdays.filter((value) => value !== weekday.value)
                                : [...config.repeatWeekdays, weekday.value].sort((a, b) => a - b),
                            })}
                            className={`rounded-full border px-3 py-1.5 text-sm transition-colors ${
                              selected
                                ? 'border-bc-primary bg-bc-primary-light text-bc-primary'
                                : 'border-bc-gray-200 bg-white text-bc-gray-600 hover:border-bc-gray-300'
                            }`}
                          >
                            {weekday.label}
                          </button>
                        )
                      })}
                    </div>
                    <p className="mt-2 text-xs text-bc-gray-500">
                      {t('Leave all weekdays unselected to run on the same weekday cadence as the plan start date.')}
                    </p>
                  </div>
                ) : null}

                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 rounded-bc border border-bc-gray-200 bg-white p-4">
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Stop after months')}
                    </label>
                    <input
                      type="number"
                      min={1}
                      value={config.stopAfterMonths ?? ''}
                      onChange={(e) => updateNullablePositiveNumber('stopAfterMonths', e.target.value)}
                      placeholder={t('Unlimited')}
                      className="w-full rounded-bc border border-bc-gray-300 px-3 py-2"
                    />
                  </div>
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Max total runs')}
                    </label>
                    <input
                      type="number"
                      min={1}
                      value={config.maxTotalRuns ?? ''}
                      onChange={(e) => updateNullablePositiveNumber('maxTotalRuns', e.target.value)}
                      placeholder={t('Unlimited')}
                      className="w-full rounded-bc border border-bc-gray-300 px-3 py-2"
                    />
                    {config.remainingRuns !== null ? (
                      <p className="mt-2 text-xs text-bc-gray-500">
                        {t('Remaining runs')}: {config.remainingRuns}
                      </p>
                    ) : null}
                  </div>
                  <div>
                    <label className="block font-semibold text-bc-gray-700 mb-2">
                      {t('Max total posts')}
                    </label>
                    <input
                      type="number"
                      min={1}
                      value={config.maxTotalPosts ?? ''}
                      onChange={(e) => updateNullablePositiveNumber('maxTotalPosts', e.target.value)}
                      placeholder={t('Unlimited')}
                      className="w-full rounded-bc border border-bc-gray-300 px-3 py-2"
                    />
                    {config.remainingPosts !== null ? (
                      <p className="mt-2 text-xs text-bc-gray-500">
                        {t('Remaining posts')}: {config.remainingPosts}
                      </p>
                    ) : null}
                  </div>
                </div>

                <div className="rounded-bc border border-dashed border-bc-primary/30 bg-bc-primary-light/40 px-4 py-3">
                  <div>
                    <div className="text-sm font-semibold text-bc-gray-800">{t('Schedule summary')}</div>
                    <p className="mt-1 text-sm text-bc-gray-600">
                      {repeatSummary}
                    </p>
                  </div>
                  <div className="mt-4 border-t border-bc-primary/15 pt-4">
                    <label className="flex items-start gap-3 cursor-pointer">
                      <ToggleSwitch
                        checked={config.isActive}
                        onChange={() => onUpdate({ ...config, isActive: !config.isActive })}
                      />
                      <div>
                        <span className="text-sm font-medium text-bc-gray-700">
                          {t('Plan active')}
                        </span>
                        <p className="text-xs text-bc-gray-500">
                          {t('Only active repeating plans will run automatically')}
                        </p>
                      </div>
                    </label>
                  </div>
                </div>
              </div>
            ) : (
              <div className="rounded-bc border border-dashed border-bc-gray-300 bg-white px-4 py-4 text-sm text-bc-gray-600">
                {t('Run this plan manually whenever you choose')}
              </div>
            )}
          </div>
        </Card>

        {/* Topic — textarea */}
        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2">
            {t('Topic / Instructions')} <span className="text-bc-accent">*</span>
          </label>
          <p className="text-sm text-bc-gray-500 mb-3">
            {t('Describe what the batch of posts should be about. Be as specific or general as you like — AI will understand.')}
          </p>
          <textarea
            value={config.topic}
            onChange={(e) => onUpdate({ ...config, topic: e.target.value })}
            placeholder={t('e.g.: Articles about different types of pumps with explanations of their capacity, uses, and maintenance tips')}
            rows={3}
            className="
              w-full p-3 rounded-bc
              border border-bc-gray-300
              bg-white text-bc-gray-800
              placeholder:text-bc-gray-400
              focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
              transition-all duration-200 resize-y
            "
          />
        </Card>

        {/* Keywords */}
        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2 flex items-center gap-1">
            {t('Keywords')}
            <HelpTooltip text={t('Keywords guide the AI to include specific topics and terms in the content. They improve relevance and SEO.')} />
          </label>
          <p className="text-sm text-bc-gray-500 mb-3">
            {t('Add keywords to be included in the content (press Enter to add)')}
          </p>
          <TagInput
            tags={config.keywords}
            onChange={(keywords) => onUpdate({ ...config, keywords })}
            placeholder={t('Add keyword...')}
          />
        </Card>

        {/* Count — presets + number input */}
        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2">
            {t('Number of posts')}
          </label>
          <p className="text-sm text-bc-gray-500 mb-3">
            {t('How many posts to create on this topic?')}
          </p>
          <div className="flex flex-wrap gap-2 mb-3">
            {countPresets.map((count) => (
              <button
                key={count}
                onClick={() => onUpdate({ ...config, count })}
                className={`
                  px-5 py-2.5 rounded-bc font-semibold text-sm
                  transition-all duration-150 bc-focus-visible
                  ${
                    config.count === count
                      ? 'bg-bc-primary text-white shadow-md'
                      : 'bg-bc-gray-100 text-bc-gray-700 hover:bg-bc-gray-200'
                  }
                `}
              >
                {count}
              </button>
            ))}
          </div>
          <input
            type="number"
            min={1}
            max={1000}
            value={config.count}
            onChange={(e) => onUpdate({ ...config, count: Math.min(1000, Math.max(1, parseInt(e.target.value) || 1)) })}
            className="w-32 px-3 py-2 border border-bc-gray-300 rounded-bc text-sm focus:border-bc-primary focus:ring-1 focus:ring-bc-primary outline-none transition-colors"
          />
          <p className="mt-2 text-xs text-bc-gray-500">
            {t('Each plan can generate up to 1,000 posts.')}
          </p>

          {/* Per-category toggle */}
          {hasMultipleCategories && (
            <div className="mt-4 p-3 bg-bc-gray-50 rounded-bc border border-bc-gray-200">
              <label className="flex items-center gap-3 cursor-pointer">
                <ToggleSwitch
                  checked={config.countPerCategory}
                  onChange={() => onUpdate({ ...config, countPerCategory: !config.countPerCategory })}
                />
                <div>
                  <span className="text-sm font-medium text-bc-gray-700">
                    {config.countPerCategory ? t('Per category') : t('Total')}
                  </span>
                  <p className="text-xs text-bc-gray-500">
                    {config.countPerCategory
                      ? t('Create this many posts for EACH selected category')
                      : t('Create this many posts total, distributed across selected categories')
                    }
                  </p>
                </div>
              </label>
            </div>
          )}
        </Card>

        {/* Publishing */}
        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2">
            {t('After creation')}
          </label>
          <p className="text-sm text-bc-gray-500 mb-3">
            {t('What should happen to posts after they are generated?')}
          </p>
          <div className="grid grid-cols-2 gap-3">
            {([
              { value: 'none' as const, label: t('Save as draft'), description: t('Save as draft for manual review') },
              { value: 'immediate' as const, label: t('Publish immediately'), description: t('Publish right after creation') },
              { value: 'daily' as const, label: t('Drip daily'), description: t('Publish one post each day') },
              { value: 'weekly' as const, label: t('Drip weekly'), description: t('Publish one post each week') },
            ] as const).map((option) => (
              <button
                key={option.value}
                type="button"
                onClick={() => onUpdate({ ...config, scheduling: option.value })}
                className={`
                  p-3 rounded-bc text-start
                  transition-all duration-150 bc-focus-visible
                  border-2
                  ${
                    config.scheduling === option.value
                      ? 'border-bc-primary bg-bc-primary-light'
                      : 'border-bc-gray-200 bg-white hover:border-bc-gray-300'
                  }
                `}
              >
                <p className={`font-semibold text-sm ${config.scheduling === option.value ? 'text-bc-primary' : 'text-bc-gray-700'}`}>
                  {option.label}
                </p>
                <p className="text-xs text-bc-gray-500 mt-1">{option.description}</p>
              </button>
            ))}
          </div>
        </Card>

        {/* Length */}
        <Card>
          <label className="block font-semibold text-bc-gray-700 mb-2 flex items-center gap-1">
            {t('Post length')}
            <HelpTooltip text={t('Short ≈ 300 words, Medium ≈ 600 words, Long ≈ 1000 words. "AI decides" lets the model choose based on sample posts.')} />
          </label>
          <div className="grid grid-cols-4 gap-3">
            {lengthOptions.map((option) => (
              <button
                key={option.value}
                onClick={() => onUpdate({ ...config, length: option.value })}
                className={`
                  p-4 rounded-bc text-center
                  transition-all duration-150 bc-focus-visible
                  border-2
                  ${
                    config.length === option.value
                      ? 'border-bc-primary bg-bc-primary-light'
                      : 'border-bc-gray-200 bg-white hover:border-bc-gray-300'
                  }
                `}
              >
                <p
                  className={`
                    font-semibold text-sm
                    ${config.length === option.value ? 'text-bc-primary' : 'text-bc-gray-700'}
                  `}
                >
                  {option.label}
                </p>
                <p className="text-xs text-bc-gray-500 mt-1">
                  {option.description}
                </p>
              </button>
            ))}
          </div>
        </Card>

      </div>
    </div>
  )
}

export function ConfigureStep({
  config,
  onUpdate,
  onBack,
  onNext,
}: ConfigureStepProps) {
  const isValid = config.topic.trim().length > 0

  return (
    <div className="max-w-2xl mx-auto">
      <div className="text-center mb-8">
        <h2 className="text-2xl font-bold text-bc-gray-800 mb-2">
          {t('Generation Settings')}
        </h2>
        <p className="text-bc-gray-500">
          {t('Set the details for the content to be created')}
        </p>
      </div>

      <ConfigureContent 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={!isValid}
          size="lg"
          icon={<ChevronLeft className="w-5 h-5 ltr:rotate-180" />}
          iconPosition={isRtl() ? 'start' : 'end'}
        >
          {t('Next step')}
        </Button>
      </div>
    </div>
  )
}
