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

export const DEFAULT_CATEGORY_AI_PROMPT = `Create a practical product category tree for my store.

Include English names, Farsi names in Persian script, and short English descriptions.
Use 3-5 main categories with relevant subcategories where it helps shoppers browse.`

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

const ANIMATION_MS = 220

export function CategoryAiPromptModal({
  open,
  onClose,
  onRun,
  isRunning,
}: CategoryAiPromptModalProps) {
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [prompt, setPrompt] = useState(DEFAULT_CATEGORY_AI_PROMPT)
  const [error, setError] = useState('')

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

  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 ApiError) {
        setError(err.message)
      } else if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('Unable to generate categories 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="category-ai-prompt-title"
      >
        <div className={`${modalStyles.header} ${styles.header}`}>
          <div className={styles.headerBlock}>
            <h2 id="category-ai-prompt-title" className={modalStyles.title}>
              Fill Categories with AI
            </h2>
            <p className={styles.subtitle}>
              Edit the prompt below, then run it to generate and save a category tree.
            </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="category-ai-prompt">Prompt</label>
            <textarea
              id="category-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}
            >
              {isRunning ? (
                <>
                  <Sparkles size={16} />
                  Running...
                </>
              ) : (
                <>
                  <Sparkles size={16} />
                  Run
                </>
              )}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
