'use client'

import type {
  BrandVoiceBannedTerm,
  BrandVoiceChannelRule,
  BrandVoiceStructuredProfile,
  BrandVoiceWorkedExample,
} from '@actuate-media/cms-core/brand-voice'
import {
  MAX_BANNED_TERMS,
  MAX_PREFERRED_TERMS,
  MAX_WORKED_EXAMPLES,
} from '@actuate-media/cms-core/brand-voice'
import { Plus, Trash2 } from 'lucide-react'
import { useId } from 'react'

const INPUT_CLASS =
  'w-full rounded-md border border-border bg-input-background px-3 py-2 text-base text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-60'
const LABEL_CLASS = 'mb-1 block text-sm font-medium text-foreground'

export function BrandVoiceRulesSections({
  structured,
  disabled,
  onChange,
}: {
  structured: BrandVoiceStructuredProfile
  disabled: boolean
  onChange: (next: BrandVoiceStructuredProfile) => void
}) {
  const preferredId = useId()
  const patternId = useId()

  function update(patch: Partial<BrandVoiceStructuredProfile>) {
    onChange({ ...structured, ...patch })
  }

  function updateBanned(index: number, patch: Partial<BrandVoiceBannedTerm>) {
    const bannedTerms = structured.bannedTerms.map((row, i) =>
      i === index ? { ...row, ...patch } : row,
    )
    update({ bannedTerms })
  }

  function updateChannel(index: number, patch: Partial<BrandVoiceChannelRule>) {
    const channels = structured.channels.map((row, i) => (i === index ? { ...row, ...patch } : row))
    update({ channels })
  }

  function updateExample(index: number, patch: Partial<BrandVoiceWorkedExample>) {
    const workedExamples = structured.workedExamples.map((row, i) =>
      i === index ? { ...row, ...patch } : row,
    )
    update({ workedExamples })
  }

  return (
    <div className="space-y-6">
      <section className="space-y-3">
        <div>
          <h4 className="text-foreground text-base font-medium">Vocabulary rules</h4>
          <p className="text-muted-foreground mt-1 text-sm">
            Banned terms produce deterministic alignment errors. Preferred terms are scored as
            bonuses.
          </p>
        </div>

        <div className="space-y-2">
          <p className="text-foreground text-sm font-medium">Banned terms</p>
          {structured.bannedTerms.length === 0 && (
            <p className="text-muted-foreground text-sm">No banned terms yet.</p>
          )}
          {structured.bannedTerms.map((row, index) => (
            <div key={`banned-${index}`} className="grid gap-2 md:grid-cols-[1fr_1fr_auto]">
              <input
                type="text"
                value={row.term}
                disabled={disabled}
                placeholder="e.g. cheap"
                aria-label={`Banned term ${index + 1}`}
                onChange={(e) => updateBanned(index, { term: e.target.value })}
                className={INPUT_CLASS}
              />
              <input
                type="text"
                value={row.useInstead}
                disabled={disabled}
                placeholder="Use instead (optional)"
                aria-label={`Replacement for banned term ${index + 1}`}
                onChange={(e) => updateBanned(index, { useInstead: e.target.value })}
                className={INPUT_CLASS}
              />
              <button
                type="button"
                disabled={disabled}
                aria-label={`Remove banned term ${index + 1}`}
                onClick={() =>
                  update({ bannedTerms: structured.bannedTerms.filter((_, i) => i !== index) })
                }
                className="border-border text-muted-foreground hover:bg-accent inline-flex items-center justify-center rounded-md border px-3 py-2 transition-colors disabled:opacity-50"
              >
                <Trash2 size={16} aria-hidden="true" />
              </button>
            </div>
          ))}
          <button
            type="button"
            disabled={disabled || structured.bannedTerms.length >= MAX_BANNED_TERMS}
            onClick={() =>
              update({ bannedTerms: [...structured.bannedTerms, { term: '', useInstead: '' }] })
            }
            className="border-border text-foreground hover:bg-accent inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:opacity-50"
          >
            <Plus size={14} aria-hidden="true" />
            Add banned term
          </button>
        </div>

        <div>
          <label htmlFor={preferredId} className={LABEL_CLASS}>
            Preferred terms
          </label>
          <input
            id={preferredId}
            type="text"
            disabled={disabled}
            placeholder="Comma-separated, e.g. ecommerce, sign up"
            value={structured.preferredTerms.join(', ')}
            onChange={(e) =>
              update({
                preferredTerms: e.target.value
                  .split(',')
                  .map((t) => t.trim())
                  .filter(Boolean)
                  .slice(0, MAX_PREFERRED_TERMS),
              })
            }
            className={INPUT_CLASS}
          />
        </div>

        <div>
          <label htmlFor={patternId} className={LABEL_CLASS}>
            Avoid patterns
          </label>
          <textarea
            id={patternId}
            disabled={disabled}
            placeholder={
              'One per line, e.g.\nhype stacking (multiple superlatives in one sentence)'
            }
            value={structured.avoidPatterns.join('\n')}
            onChange={(e) =>
              update({
                avoidPatterns: e.target.value
                  .split('\n')
                  .map((line) => line.trim())
                  .filter(Boolean),
              })
            }
            className={`${INPUT_CLASS} min-h-[88px] resize-y`}
          />
        </div>
      </section>

      <section className="space-y-3">
        <div>
          <h4 className="text-foreground text-base font-medium">Channel overrides</h4>
          <p className="text-muted-foreground mt-1 text-sm">
            Length limits and notes used when scoring copy for a specific channel.
          </p>
        </div>
        <div className="space-y-3">
          {structured.channels.map((channel, index) => (
            <div key={channel.id} className="border-border rounded-md border p-4">
              <p className="text-foreground mb-3 text-sm font-medium">{channel.label}</p>
              <div className="grid gap-3 md:grid-cols-3">
                {channel.id === 'google_ads' ? (
                  <>
                    <div>
                      <label className={LABEL_CLASS}>Max headline chars</label>
                      <input
                        type="number"
                        min={1}
                        disabled={disabled}
                        value={channel.maxHeadlineChars ?? ''}
                        onChange={(e) =>
                          updateChannel(index, {
                            maxHeadlineChars: e.target.value ? Number(e.target.value) : undefined,
                          })
                        }
                        className={INPUT_CLASS}
                      />
                    </div>
                    <div>
                      <label className={LABEL_CLASS}>Max description chars</label>
                      <input
                        type="number"
                        min={1}
                        disabled={disabled}
                        value={channel.maxDescriptionChars ?? ''}
                        onChange={(e) =>
                          updateChannel(index, {
                            maxDescriptionChars: e.target.value
                              ? Number(e.target.value)
                              : undefined,
                          })
                        }
                        className={INPUT_CLASS}
                      />
                    </div>
                  </>
                ) : (
                  <div>
                    <label className={LABEL_CLASS}>Max characters</label>
                    <input
                      type="number"
                      min={1}
                      disabled={disabled}
                      value={channel.maxChars ?? ''}
                      onChange={(e) =>
                        updateChannel(index, {
                          maxChars: e.target.value ? Number(e.target.value) : undefined,
                        })
                      }
                      className={INPUT_CLASS}
                    />
                  </div>
                )}
                <div className={channel.id === 'google_ads' ? 'md:col-span-1' : 'md:col-span-2'}>
                  <label className={LABEL_CLASS}>Note</label>
                  <input
                    type="text"
                    disabled={disabled}
                    value={channel.note ?? ''}
                    onChange={(e) => updateChannel(index, { note: e.target.value })}
                    className={INPUT_CLASS}
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
      </section>

      <section className="space-y-3">
        <div>
          <h4 className="text-foreground text-base font-medium">Worked examples</h4>
          <p className="text-muted-foreground mt-1 text-sm">
            Off-brand vs on-brand pairs anchor scoring feedback and the sample copy field.
          </p>
        </div>
        {structured.workedExamples.length === 0 && (
          <p className="text-muted-foreground text-sm">No worked examples yet.</p>
        )}
        {structured.workedExamples.map((example, index) => (
          <div key={`example-${index}`} className="border-border space-y-2 rounded-md border p-4">
            <div className="flex items-center justify-between gap-3">
              <p className="text-foreground text-sm font-medium">Example {index + 1}</p>
              <button
                type="button"
                disabled={disabled}
                aria-label={`Remove worked example ${index + 1}`}
                onClick={() =>
                  update({
                    workedExamples: structured.workedExamples.filter((_, i) => i !== index),
                  })
                }
                className="border-border text-muted-foreground hover:bg-accent inline-flex items-center justify-center rounded-md border px-2 py-1 transition-colors disabled:opacity-50"
              >
                <Trash2 size={14} aria-hidden="true" />
              </button>
            </div>
            <input
              type="text"
              disabled={disabled}
              placeholder="Off-brand copy"
              aria-label={`Off-brand example ${index + 1}`}
              value={example.offBrand}
              onChange={(e) => updateExample(index, { offBrand: e.target.value })}
              className={INPUT_CLASS}
            />
            <input
              type="text"
              disabled={disabled}
              placeholder="On-brand rewrite"
              aria-label={`On-brand example ${index + 1}`}
              value={example.onBrand}
              onChange={(e) => updateExample(index, { onBrand: e.target.value })}
              className={INPUT_CLASS}
            />
            <input
              type="text"
              disabled={disabled}
              placeholder="Why this is better"
              aria-label={`Why example ${index + 1} is on-brand`}
              value={example.why}
              onChange={(e) => updateExample(index, { why: e.target.value })}
              className={INPUT_CLASS}
            />
          </div>
        ))}
        <button
          type="button"
          disabled={disabled || structured.workedExamples.length >= MAX_WORKED_EXAMPLES}
          onClick={() =>
            update({
              workedExamples: [
                ...structured.workedExamples,
                { offBrand: '', onBrand: '', why: '' },
              ],
            })
          }
          className="border-border text-foreground hover:bg-accent inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-sm transition-colors disabled:opacity-50"
        >
          <Plus size={14} aria-hidden="true" />
          Add worked example
        </button>
      </section>
    </div>
  )
}
