import { useEffect, useState } from 'react'
import { createPortal } from 'react-dom'
import { Sparkles, X } from 'lucide-react'
import modalStyles from './CategoryModal.module.css'
import aiStyles from '../styles/ai.module.css'
import styles from './CategoryAiPromptModal.module.css'

export function buildTechnicalFormAiPrompt(categoryName: string) {
  return `Suggest technical data form fields for the "${categoryName}" product category.

For each field include:
- A short English label (e.g. "Screen Size", "Material", "Color")
- The input type: text, textarea, select, or multi_select
- Whether it is required
- For select / multi_select: the list of options

Focus on specs and attributes that shoppers typically compare when buying this type of product.`
}

interface TechnicalFormAiPromptModalProps {
  open: boolean
  categoryName: string
  onClose: () => void
  onRun: (prompt: string) => Promise<void>
  isRunning: boolean
}

const ANIMATION_MS = 220

export function TechnicalFormAiPromptModal({
  open,
  categoryName,
  onClose,
  onRun,
  isRunning,
}: TechnicalFormAiPromptModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [prompt, setPrompt] = useState(() => buildTechnicalFormAiPrompt(categoryName))
  const [error, setError] = useState('')

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setPrompt(buildTechnicalFormAiPrompt(categoryName))
      setError('')
    } else if (mounted) {
      setClosing(true)
      const timer = setTimeout(() => {
        setMounted(false)
        setClosing(false)
      }, ANIMATION_MS)
      return () => clearTimeout(timer)
    }
  }, [open, mounted, categoryName])

  useEffect(() => {
    if (!mounted || closing) return
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !isRunning) onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [mounted, closing, isRunning, onClose])

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    const trimmed = prompt.trim()
    if (trimmed.length < 10) {
      setError('Prompt must be at least 10 characters.')
      return
    }
    setError('')
    try {
      await onRun(trimmed)
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('Unable to generate technical form with AI.')
      }
    }
  }

  if (!mounted) return null

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={(e) => e.target === e.currentTarget && !isRunning && onClose()}
      role="presentation"
    >
      <div
        className={`${modalStyles.modal} ${styles.modal} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        role="dialog"
        aria-modal="true"
        aria-labelledby="tech-form-ai-prompt-title"
      >
        <div className={`${modalStyles.header} ${styles.header}`}>
          <div className={styles.headerBlock}>
            <h2 id="tech-form-ai-prompt-title" className={modalStyles.title}>
              Generate Technical Form with AI
            </h2>
            <p className={styles.subtitle}>
              Edit the prompt below, then run it to fill the form fields.
            </p>
          </div>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            disabled={isRunning}
            aria-label="Close"
          >
            <X size={20} />
          </button>
        </div>

        <form className={modalStyles.form} onSubmit={(e) => void handleSubmit(e)}>
          <div className={`${modalStyles.field} ${aiStyles.aiPromptField}`}>
            <label htmlFor="tech-form-ai-prompt">Prompt</label>
            <textarea
              id="tech-form-ai-prompt"
              className={aiStyles.aiPromptTextarea}
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              rows={8}
              disabled={isRunning}
              required
            />
          </div>

          {error && <p className={styles.error}>{error}</p>}

          <div className={modalStyles.actions}>
            <button
              type="button"
              className={modalStyles.cancelBtn}
              onClick={onClose}
              disabled={isRunning}
            >
              Cancel
            </button>
            <button
              type="submit"
              className={aiStyles.aiBtn}
              disabled={isRunning || prompt.trim().length < 10}
            >
              <Sparkles size={16} />
              {isRunning ? 'Generating…' : 'Run'}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
