import React, { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './UploadPhotoBlock.module.css';

interface UploadPhotoBlockProps {
  onPhotoSelect?: (file: File) => void;
  previewUrl?: string;
}

const UploadPhotoBlock: React.FC<UploadPhotoBlockProps> = ({ onPhotoSelect, previewUrl }) => {
  const navigate = useNavigate();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [isDragging, setIsDragging] = useState(false);

  const handleFileSelect = (file: File) => {
    if (file && file.type.startsWith('image/')) {
      // Очищаем предыдущие данные изображения при загрузке нового
      localStorage.removeItem('stickerPreviewUrl');
      localStorage.removeItem('stickerImageData');
      
      onPhotoSelect?.(file);
      navigate('/crop-photo', { state: { file } });
    }
  };

  const handleClick = () => {
    fileInputRef.current?.click();
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    
    const file = e.dataTransfer.files[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = () => {
    setIsDragging(false);
  };

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      handleFileSelect(file);
    }
  };

  return (
    <div className={styles.container}>
      <div
        className={`${styles.uploadArea} ${isDragging ? styles.dragging : ''} ${previewUrl ? styles.hasPreview : ''}`}
        onClick={handleClick}
        onDrop={handleDrop}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
      >
        {previewUrl ? (
          <div className={styles.preview}>
            <img src={previewUrl} alt="Preview" className={styles.previewImage} />
            <div className={styles.changeOverlay}>
              <span className={styles.changeText}>Изменить фото</span>
            </div>
          </div>
        ) : (
          <>
            <div className={styles.icon}>📷</div>
            <div className={styles.text}>
              <span className={styles.title}>Загрузите фото</span>
              <span className={styles.subtitle}>Перетащите или нажмите для выбора</span>
            </div>
          </>
        )}
      </div>
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        onChange={handleFileChange}
        className={styles.fileInput}
      />
    </div>
  );
};

export default UploadPhotoBlock;
