import React, { useState, useEffect, useRef } from 'react';
import { Image, Download, Wand2, RefreshCw } from 'lucide-react';
import { thumbnailApi, jobsApi } from '../api/client';

const THUMBNAIL_STYLES = [
  { id: 'homeshopping', name: '홈쇼핑', desc: '강렬한 어필' },
  { id: 'viral', name: '바이럴', desc: '호기심 유발' },
  { id: 'informative', name: '정보성', desc: '명확한 전달' },
];

export default function ThumbnailGenerator({ jobId, onClose }) {
  const videoRef = useRef(null);
  const [duration, setDuration] = useState(0);
  const [currentTime, setCurrentTime] = useState(2.0);
  const [thumbnailStyle, setThumbnailStyle] = useState('homeshopping');
  const [thumbnailText, setThumbnailText] = useState('');
  const [fontSize, setFontSize] = useState(80);
  const [position, setPosition] = useState('center');
  const [isGenerating, setIsGenerating] = useState(false);
  const [isGeneratingText, setIsGeneratingText] = useState(false);
  const [generatedUrl, setGeneratedUrl] = useState(null);
  const [error, setError] = useState(null);

  // Load video metadata
  useEffect(() => {
    if (videoRef.current) {
      videoRef.current.addEventListener('loadedmetadata', () => {
        setDuration(videoRef.current.duration);
        // Start at 10% of video
        const startTime = videoRef.current.duration * 0.1;
        setCurrentTime(startTime);
        videoRef.current.currentTime = startTime;
      });
    }
  }, []);

  // Seek video when currentTime changes
  useEffect(() => {
    if (videoRef.current && videoRef.current.readyState >= 2) {
      videoRef.current.currentTime = currentTime;
    }
  }, [currentTime]);

  const handleSliderChange = (e) => {
    const time = parseFloat(e.target.value);
    setCurrentTime(time);
  };

  const handleGenerateText = async () => {
    setIsGeneratingText(true);
    setError(null);
    try {
      const res = await thumbnailApi.generateCatchphrase(jobId, thumbnailStyle);
      setThumbnailText(res.data.catchphrase || '');
    } catch (err) {
      setError(err.response?.data?.detail || '문구 생성 실패');
    } finally {
      setIsGeneratingText(false);
    }
  };

  const handleGenerate = async () => {
    setIsGenerating(true);
    setError(null);
    try {
      const res = await thumbnailApi.generate(jobId, {
        timestamp: currentTime,
        style: thumbnailStyle,
        customText: thumbnailText || null,
        fontSize: fontSize,
        position: position,
      });
      setGeneratedUrl(`${jobsApi.downloadThumbnail(jobId)}?t=${Date.now()}`);
      if (res.data.text && !thumbnailText) {
        setThumbnailText(res.data.text);
      }
    } catch (err) {
      setError(err.response?.data?.detail || '썸네일 생성 실패');
    } finally {
      setIsGenerating(false);
    }
  };

  const formatTime = (seconds) => {
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  // Calculate text position style
  const getTextPositionStyle = () => {
    const base = {
      position: 'absolute',
      left: '50%',
      transform: 'translateX(-50%)',
      textAlign: 'center',
      fontWeight: 'bold',
      color: 'white',
      textShadow: `
        -2px -2px 0 #000,
        2px -2px 0 #000,
        -2px 2px 0 #000,
        2px 2px 0 #000,
        -3px 0 0 #000,
        3px 0 0 #000,
        0 -3px 0 #000,
        0 3px 0 #000
      `,
      fontSize: `${fontSize * 0.5}px`, // Scale down for preview
      maxWidth: '90%',
      wordBreak: 'keep-all',
    };

    switch (position) {
      case 'top':
        return { ...base, top: '15%' };
      case 'bottom':
        return { ...base, bottom: '20%' };
      default: // center
        return { ...base, top: '50%', transform: 'translate(-50%, -50%)' };
    }
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between mb-2">
        <h3 className="font-semibold text-pink-400 flex items-center gap-2">
          <Image size={20} />
          썸네일 생성
        </h3>
        {onClose && (
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-white text-sm"
          >
            닫기
          </button>
        )}
      </div>

      {/* Video Preview with Text Overlay */}
      <div className="relative bg-black rounded-lg overflow-hidden">
        <video
          ref={videoRef}
          src={jobsApi.downloadOriginal(jobId)}
          className="w-full h-auto"
          muted
          playsInline
          preload="metadata"
        />
        {/* Text Overlay Preview */}
        {thumbnailText && (
          <div style={getTextPositionStyle()}>
            {thumbnailText}
          </div>
        )}
        {/* Time indicator */}
        <div className="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
          {formatTime(currentTime)}
        </div>
      </div>

      {/* Timeline Slider */}
      <div className="space-y-1">
        <label className="text-sm text-gray-400">프레임 선택</label>
        <input
          type="range"
          min={0}
          max={duration || 30}
          step={0.1}
          value={currentTime}
          onChange={handleSliderChange}
          className="w-full h-2 bg-gray-700 rounded-lg appearance-none cursor-pointer accent-pink-500"
        />
        <div className="flex justify-between text-xs text-gray-500">
          <span>0:00</span>
          <span className="text-pink-400 font-medium">{formatTime(currentTime)}</span>
          <span>{formatTime(duration)}</span>
        </div>
      </div>

      {/* Style Selection */}
      <div>
        <label className="block text-sm text-gray-400 mb-2">문구 스타일</label>
        <div className="grid grid-cols-3 gap-2">
          {THUMBNAIL_STYLES.map((style) => (
            <button
              key={style.id}
              onClick={() => setThumbnailStyle(style.id)}
              className={`p-2 rounded-lg border text-sm transition-colors ${
                thumbnailStyle === style.id
                  ? 'border-pink-500 bg-pink-500/10'
                  : 'border-gray-700 hover:border-gray-600'
              }`}
            >
              <div>{style.name}</div>
              <div className="text-xs text-gray-500">{style.desc}</div>
            </button>
          ))}
        </div>
      </div>

      {/* Text Input */}
      <div>
        <label className="block text-sm text-gray-400 mb-2">썸네일 문구</label>
        <div className="flex gap-2">
          <input
            type="text"
            value={thumbnailText}
            onChange={(e) => setThumbnailText(e.target.value)}
            placeholder="문구를 입력하거나 자동 생성..."
            maxLength={20}
            className="flex-1 p-2 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:border-pink-500"
          />
          <button
            onClick={handleGenerateText}
            disabled={isGeneratingText}
            className="px-3 py-2 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-500 hover:to-pink-500 rounded-lg transition-colors disabled:opacity-50"
            title="GPT로 문구 생성"
          >
            {isGeneratingText ? (
              <RefreshCw size={18} className="animate-spin" />
            ) : (
              <Wand2 size={18} />
            )}
          </button>
        </div>
        <div className="text-xs text-gray-500 mt-1">
          {thumbnailText.length}/20자 (최대 15자 권장)
        </div>
      </div>

      {/* Font Size & Position */}
      <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="block text-sm text-gray-400 mb-2">
            글자 크기: {fontSize}px
          </label>
          <input
            type="range"
            min="40"
            max="120"
            value={fontSize}
            onChange={(e) => setFontSize(parseInt(e.target.value))}
            className="w-full accent-pink-500"
          />
        </div>
        <div>
          <label className="block text-sm text-gray-400 mb-2">위치</label>
          <div className="flex gap-1">
            {['top', 'center', 'bottom'].map((pos) => (
              <button
                key={pos}
                onClick={() => setPosition(pos)}
                className={`flex-1 p-2 rounded border text-xs transition-colors ${
                  position === pos
                    ? 'border-pink-500 bg-pink-500/10'
                    : 'border-gray-700 hover:border-gray-600'
                }`}
              >
                {pos === 'top' ? '상단' : pos === 'center' ? '중앙' : '하단'}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Error Message */}
      {error && (
        <div className="p-2 bg-red-900/30 border border-red-800 rounded-lg text-red-400 text-sm">
          {error}
        </div>
      )}

      {/* Generate Button */}
      <button
        onClick={handleGenerate}
        disabled={isGenerating}
        className="w-full py-3 bg-gradient-to-r from-pink-600 to-purple-600 hover:from-pink-500 hover:to-purple-500 rounded-lg font-medium flex items-center justify-center gap-2 disabled:opacity-50 transition-all"
      >
        <Image size={18} className={isGenerating ? 'animate-pulse' : ''} />
        {isGenerating ? '생성 중...' : '썸네일 생성'}
      </button>

      {/* Generated Thumbnail Preview & Download */}
      {generatedUrl && (
        <div className="space-y-3 pt-4 border-t border-gray-700">
          <h4 className="text-sm text-gray-400">생성된 썸네일</h4>
          <div className="border border-gray-700 rounded-lg overflow-hidden">
            <img
              src={generatedUrl}
              alt="Generated Thumbnail"
              className="w-full h-auto"
            />
          </div>
          <a
            href={generatedUrl}
            download={`thumbnail_${jobId}.jpg`}
            className="w-full py-2 border border-pink-700/50 bg-pink-900/20 hover:bg-pink-900/30 rounded-lg transition-colors flex items-center justify-center gap-2 text-pink-300"
          >
            <Download size={18} />
            썸네일 다운로드
          </a>
        </div>
      )}
    </div>
  );
}
