import { useCallback, useEffect, useState } from 'react'
import Cropper, { type Area } from 'react-easy-crop'
import { Button } from '@shared/ui'
import { getCroppedImg } from './getCroppedImg'
import styles from './AvatarCropModal.module.css'

interface Props {
  imageSrc: string
  isSaving?: boolean
  onCancel: () => void
  onConfirm: (blob: Blob) => void | Promise<void>
}

export function AvatarCropModal({ imageSrc, isSaving, onCancel, onConfirm }: Props) {
  const [crop, setCrop] = useState({ x: 0, y: 0 })
  const [zoom, setZoom] = useState(1)
  const [pixels, setPixels] = useState<Area | null>(null)
  const [error, setError] = useState<string | null>(null)

  const handleComplete = useCallback((_: Area, areaPixels: Area) => {
    setPixels(areaPixels)
  }, [])

  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !isSaving) onCancel()
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [onCancel, isSaving])

  const handleConfirm = async () => {
    if (!pixels) return
    setError(null)
    try {
      const blob = await getCroppedImg(imageSrc, pixels)
      await onConfirm(blob)
    } catch {
      setError('Не удалось обрезать изображение')
    }
  }

  return (
    <div className={styles.backdrop} onClick={isSaving ? undefined : onCancel}>
      <div className={styles.card} onClick={(e) => e.stopPropagation()}>
        <h3 className={styles.title}>Выберите область аватара</h3>

        <div className={styles.cropArea}>
          <Cropper
            image={imageSrc}
            crop={crop}
            zoom={zoom}
            aspect={1}
            cropShape="round"
            showGrid={false}
            onCropChange={setCrop}
            onZoomChange={setZoom}
            onCropComplete={handleComplete}
          />
        </div>

        <div className={styles.controls}>
          <label htmlFor="avatar-zoom">Масштаб</label>
          <input
            id="avatar-zoom"
            className={styles.zoom}
            type="range"
            min={1}
            max={3}
            step={0.01}
            value={zoom}
            onChange={(e) => setZoom(Number(e.target.value))}
          />
        </div>

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

        <div className={styles.actions}>
          <Button variant="ghost" onClick={onCancel} disabled={isSaving}>
            Отмена
          </Button>
          <Button variant="primary" onClick={handleConfirm} disabled={isSaving || !pixels}>
            {isSaving ? 'Загрузка...' : 'Сохранить'}
          </Button>
        </div>
      </div>
    </div>
  )
}
