
import React, { useRef, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { ImageItem, ImageUrlItem } from '../../types/api';
import { uploadImages } from '../../utils/api';

interface AssetManagementContentProps {
  onNext: (imageTaskId: string) => void;
  imageList: ImageItem[];
  onRemoveImage: (index: number) => void;
  onAddImages: (files: File[]) => void;
}

type VideoRatio = 'vertical' | 'horizontal';

const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
  onNext,
  imageList,
  onRemoveImage,
  onAddImages,
}) => {
  const { t } = useTranslation();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const imageListRef = useRef<HTMLDivElement>(null);
  const [isUploading, setIsUploading] = useState(false);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [videoRatio, setVideoRatio] = useState<VideoRatio>('vertical');

  // Load video ratio from localStorage on mount
  useEffect(() => {
    const savedRatio = localStorage.getItem('castad_video_ratio') as VideoRatio;
    if (savedRatio === 'vertical' || savedRatio === 'horizontal') {
      setVideoRatio(savedRatio);
    }
  }, []);

  // Save video ratio to localStorage when it changes
  const handleVideoRatioChange = (ratio: VideoRatio) => {
    setVideoRatio(ratio);
    localStorage.setItem('castad_video_ratio', ratio);
  };

  const getImageSrc = (item: ImageItem): string => {
    return item.type === 'url' ? item.url : item.preview;
  };

  const handleNextWithUpload = async () => {
    if (imageList.length === 0) return;

    setIsUploading(true);
    setUploadError(null);

    try {
      // URL 이미지와 파일 이미지 분리
      const urlImages: ImageUrlItem[] = imageList
        .filter((item: ImageItem): item is ImageItem & { type: 'url' } => item.type === 'url')
        .map((item) => ({ url: item.url }));

      const fileImages: File[] = imageList
        .filter((item: ImageItem): item is ImageItem & { type: 'file' } => item.type === 'file')
        .map((item) => item.file);

      // 이미지가 하나라도 있으면 업로드
      if (urlImages.length > 0 || fileImages.length > 0) {
        const response = await uploadImages(urlImages, fileImages);
        onNext(response.task_id);
      }
    } catch (error) {
      console.error('Image upload failed:', error);
      setUploadError(error instanceof Error ? error.message : t('assetManagement.uploadFailed'));
    } finally {
      setIsUploading(false);
    }
  };

  const handleImageListWheel = (e: React.WheelEvent) => {
    // 이 영역 안에서는 항상 스크롤 이벤트 전파 차단
    e.stopPropagation();
  };

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

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();

    const files = Array.from(e.dataTransfer.files).filter(file =>
      file.type.startsWith('image/')
    );

    if (files.length > 0) {
      onAddImages(files);
    }
  };

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

  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (files && files.length > 0) {
      onAddImages(Array.from(files));
      e.target.value = '';
    }
  };

  return (
    <main className="page-container">
      {/* Title */}
      <h1 className="asset-title">{t('assetManagement.title')}</h1>

      {/* Main Content Container */}
      <div className="asset-container">
        {/* Left Column - Selected Images */}
        <div className="asset-column asset-column-left">
          <h3 className="asset-section-title">{t('assetManagement.selectedImages')}</h3>
          <div
            ref={imageListRef}
            onWheel={handleImageListWheel}
            className="asset-image-list"
          >
            {imageList.length > 0 ? (
              <div className="asset-image-grid">
                {imageList.map((item, i) => (
                  <div key={i} className="asset-image-item">
                    <img
                      src={getImageSrc(item)}
                      alt={`${t('assetManagement.imageAlt')} ${i + 1}`}
                    />
                    {item.type === 'file' && (
                      <div className="asset-image-badge">{t('assetManagement.uploadBadge')}</div>
                    )}
                    <button
                      onClick={() => onRemoveImage(i)}
                      className="asset-image-remove"
                    >
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
                        <line x1="18" y1="6" x2="6" y2="18"/>
                        <line x1="6" y1="6" x2="18" y2="18"/>
                      </svg>
                    </button>
                  </div>
                ))}
              </div>
            ) : null}
          </div>
        </div>

        {/* Right Column - Upload and Video Ratio */}
        <div className="asset-column asset-column-right">
          {/* Image Upload Section */}
          <div className="asset-upload-section">
            <h3 className="asset-section-title">{t('assetManagement.imageUpload')}</h3>
            <div
              onClick={handleFileSelect}
              onDragOver={handleDragOver}
              onDrop={handleDrop}
              className="asset-upload-zone"
            >
              <p className="asset-upload-text">
                {t('assetManagement.dragAndDrop').split('\n').map((line, i) => (
                  <React.Fragment key={i}>{i > 0 && <br/>}{line}</React.Fragment>
                ))}
              </p>
            </div>
            <input
              ref={fileInputRef}
              type="file"
              accept="image/*"
              multiple
              onChange={handleFileChange}
              className="hidden"
            />
          </div>

          {/* Video Ratio Section */}
          <div className="asset-ratio-section">
            <h3 className="asset-section-title">{t('assetManagement.videoRatio')}</h3>
            <div className="asset-ratio-buttons">
              <button
                onClick={() => handleVideoRatioChange('vertical')}
                className={`asset-ratio-button ${videoRatio === 'vertical' ? 'active' : ''}`}
              >
                <div className="asset-ratio-icon asset-ratio-icon-vertical">
                  <div className="asset-ratio-box"></div>
                </div>
                <span>9:16</span>
              </button>
              <button
                onClick={() => handleVideoRatioChange('horizontal')}
                className={`asset-ratio-button ${videoRatio === 'horizontal' ? 'active' : ''}`}
              >
                <div className="asset-ratio-icon asset-ratio-icon-horizontal">
                  <div className="asset-ratio-box"></div>
                </div>
                <span>16:9</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Bottom Button */}
      <div className="asset-bottom">
        {uploadError && (
          <p className="text-red-500 text-sm mb-2">{uploadError}</p>
        )}
        <button
          onClick={handleNextWithUpload}
          disabled={imageList.length === 0 || isUploading}
          className="asset-next-button"
        >
          {isUploading ? t('assetManagement.uploading') : t('assetManagement.nextStep')}
        </button>
      </div>
    </main>
  );
};

export default AssetManagementContent;
