import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { X } from 'lucide-react'
import { ImageCropper } from './ImageCropper'
import { useT } from '../i18n/useT'
import modalStyles from './CategoryModal.module.css'
import styles from './AddWebsiteSliderSlideModal.module.css'

export interface WebsiteSliderSlideFormData {
  image: string | null
  title: string
  linkUrl: string
}

interface AddWebsiteSliderSlideModalProps {
  open: boolean
  onClose: () => void
  onSubmit: (data: WebsiteSliderSlideFormData) => void
  isSubmitting?: boolean
}

const ANIMATION_MS = 220

export function AddWebsiteSliderSlideModal({
  open,
  onClose,
  onSubmit,
  isSubmitting = false,
}: AddWebsiteSliderSlideModalProps) {
  const t = useT()
  const formRef = useRef<HTMLFormElement>(null)
  const [mounted, setMounted] = useState(open)
  const [closing, setClosing] = useState(false)
  const [image, setImage] = useState<string | null>(null)
  const [title, setTitle] = useState('')
  const [linkUrl, setLinkUrl] = useState('')

  useEffect(() => {
    if (open) {
      setMounted(true)
      setClosing(false)
      setImage(null)
      setTitle('')
      setLinkUrl('')
    } 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') onClose()
    }
    document.addEventListener('keydown', onKey)
    return () => document.removeEventListener('keydown', onKey)
  }, [mounted, closing, onClose])

  if (!mounted) return null

  function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    if (!image) return
    onSubmit({
      image,
      title: title.trim(),
      linkUrl: linkUrl.trim(),
    })
  }

  return createPortal(
    <div
      className={`${modalStyles.overlay} ${closing ? modalStyles.overlayOut : modalStyles.overlayIn}`}
      onClick={(e) => e.target === e.currentTarget && onClose()}
      role="presentation"
    >
      <div
        className={`${modalStyles.modal} ${styles.modalWide} ${closing ? modalStyles.modalOut : modalStyles.modalIn}`}
        role="dialog"
        aria-modal="true"
        aria-labelledby="add-slide-title"
      >
        <div className={modalStyles.header}>
          <h3 id="add-slide-title" className={modalStyles.title}>
            {t('website.sliders.modal.title')}
          </h3>
          <button
            type="button"
            className={modalStyles.closeBtn}
            onClick={onClose}
            aria-label={t('common.close')}
          >
            <X size={20} />
          </button>
        </div>

        <form ref={formRef} className={modalStyles.form} onSubmit={handleSubmit}>
          <div className={modalStyles.field}>
            <label>{t('website.sliders.modal.image')}</label>
            <ImageCropper
              value={image}
              onChange={setImage}
              aspect={9 / 4}
              uploadLabel={t('website.sliders.modal.upload')}
              hint={t('website.sliders.modal.hint')}
              changeLabel={t('website.sliders.modal.changeImage')}
            />
          </div>

          <div className={modalStyles.field}>
            <label htmlFor="slide-title">{t('website.sliders.modal.titleOptional')}</label>
            <input
              id="slide-title"
              type="text"
              placeholder={t('website.sliders.modal.titlePlaceholder')}
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={modalStyles.field}>
            <label htmlFor="slide-link">{t('website.sliders.modal.linkOptional')}</label>
            <input
              id="slide-link"
              type="url"
              dir="ltr"
              placeholder="https://example.com/promo"
              value={linkUrl}
              onChange={(e) => setLinkUrl(e.target.value)}
              disabled={isSubmitting}
            />
          </div>

          <div className={modalStyles.actions}>
            <button
              type="button"
              className={modalStyles.cancelBtn}
              onClick={onClose}
              disabled={isSubmitting}
            >
              {t('products.form.cancel')}
            </button>
            <button
              type="submit"
              className={modalStyles.submitBtn}
              disabled={isSubmitting || !image}
            >
              {isSubmitting ? t('website.adding') : t('website.sliders.modal.addSlide')}
            </button>
          </div>
        </form>
      </div>
    </div>
  ,
  document.body,
  )
}
