"use client";

import React, { useState, useEffect } from "react";
import {
  PlayIcon,
  PauseIcon,
  StopIcon,
  ChartBarIcon,
  PhotoIcon,
} from "@heroicons/react/24/outline";

// 배치 처리 설정
interface BatchProcessingOptions {
  sizes: string[];
  formats: string[];
  quality: number;
  progressive: boolean;
  stripMetadata: boolean;
  enableWebp: boolean;
  enableAvif: boolean;
}

// 배치 작업 항목
interface BatchJobItem {
  uploadId: string;
  fileName: string;
  status: "pending" | "processing" | "completed" | "failed";
  progress: number;
  error?: string;
  startedAt?: Date;
  completedAt?: Date;
}

// 배치 작업 통계
interface BatchStats {
  total: number;
  pending: number;
  processing: number;
  completed: number;
  failed: number;
  totalSizeReduction: number;
  averageProcessingTime: number;
}

interface BatchImageProcessorProps {
  uploadIds: string[];
  onBatchComplete?: (stats: BatchStats) => void;
  className?: string;
}

export function BatchImageProcessor({
  uploadIds,
  onBatchComplete,
  className = "",
}: BatchImageProcessorProps) {
  const [jobs, setJobs] = useState<BatchJobItem[]>([]);
  const [isRunning, setIsRunning] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [stats, setStats] = useState<BatchStats>({
    total: 0,
    pending: 0,
    processing: 0,
    completed: 0,
    failed: 0,
    totalSizeReduction: 0,
    averageProcessingTime: 0,
  });

  const [options, setOptions] = useState<BatchProcessingOptions>({
    sizes: ["thumbnail", "small", "medium", "large"],
    formats: ["jpeg", "webp"],
    quality: 80,
    progressive: true,
    stripMetadata: true,
    enableWebp: true,
    enableAvif: false,
  });

  // 초기 작업 목록 설정
  useEffect(() => {
    const initialJobs = uploadIds.map((uploadId) => ({
      uploadId,
      fileName: `File ${uploadId.substring(0, 8)}...`,
      status: "pending" as const,
      progress: 0,
    }));

    setJobs(initialJobs);
    updateStats(initialJobs);
  }, [uploadIds]);

  // 통계 업데이트
  const updateStats = (currentJobs: BatchJobItem[]) => {
    const newStats: BatchStats = {
      total: currentJobs.length,
      pending: currentJobs.filter((j) => j.status === "pending").length,
      processing: currentJobs.filter((j) => j.status === "processing").length,
      completed: currentJobs.filter((j) => j.status === "completed").length,
      failed: currentJobs.filter((j) => j.status === "failed").length,
      totalSizeReduction: 0, // TODO: 실제 계산
      averageProcessingTime: 0, // TODO: 실제 계산
    };

    setStats(newStats);

    // 모든 작업 완료 시 콜백 호출
    if (
      newStats.completed + newStats.failed === newStats.total &&
      newStats.total > 0
    ) {
      onBatchComplete?.(newStats);
    }
  };

  // 배치 처리 시작
  const startBatch = async () => {
    setIsRunning(true);
    setIsPaused(false);

    for (let i = 0; i < jobs.length; i++) {
      if (isPaused) break;

      const job = jobs[i];
      if (job.status !== "pending") continue;

      // 작업 상태를 processing으로 변경
      setJobs((prevJobs) => {
        const updatedJobs = [...prevJobs];
        updatedJobs[i] = {
          ...job,
          status: "processing",
          startedAt: new Date(),
        };
        updateStats(updatedJobs);
        return updatedJobs;
      });

      try {
        // 이미지 처리 요청
        const response = await fetch("/api/media/process", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            uploadId: job.uploadId,
            inputPath: `/uploads/${job.uploadId}`, // 임시 경로
            fileName: job.fileName,
            options,
          }),
        });

        if (response.ok) {
          // 처리 완료 상태로 변경
          setJobs((prevJobs) => {
            const updatedJobs = [...prevJobs];
            updatedJobs[i] = {
              ...updatedJobs[i],
              status: "completed",
              progress: 100,
              completedAt: new Date(),
            };
            updateStats(updatedJobs);
            return updatedJobs;
          });
        } else {
          throw new Error("Processing failed");
        }
      } catch (error) {
        // 실패 상태로 변경
        setJobs((prevJobs) => {
          const updatedJobs = [...prevJobs];
          updatedJobs[i] = {
            ...updatedJobs[i],
            status: "failed",
            error: error instanceof Error ? error.message : "Unknown error",
            completedAt: new Date(),
          };
          updateStats(updatedJobs);
          return updatedJobs;
        });
      }

      // 다음 작업 전 잠시 대기
      await new Promise((resolve) => setTimeout(resolve, 500));
    }

    setIsRunning(false);
  };

  // 배치 처리 일시정지
  const pauseBatch = () => {
    setIsPaused(true);
    setIsRunning(false);
  };

  // 배치 처리 중지
  const stopBatch = () => {
    setIsRunning(false);
    setIsPaused(false);

    // 모든 pending 작업을 중지
    setJobs((prevJobs) => {
      const updatedJobs = prevJobs.map((job) =>
        job.status === "pending"
          ? { ...job, status: "failed" as const, error: "Cancelled" }
          : job
      );
      updateStats(updatedJobs);
      return updatedJobs;
    });
  };

  // 작업 재시도
  const retryFailedJobs = () => {
    setJobs((prevJobs) => {
      const updatedJobs = prevJobs.map((job) =>
        job.status === "failed"
          ? { ...job, status: "pending" as const, error: undefined }
          : job
      );
      updateStats(updatedJobs);
      return updatedJobs;
    });
  };

  return (
    <div className={`bg-white border border-gray-200 rounded-lg ${className}`}>
      {/* 헤더 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <PhotoIcon className="h-6 w-6 text-gray-400 mr-2" />
            <h3 className="text-lg font-medium text-gray-900">
              배치 이미지 처리
            </h3>
          </div>
          <div className="flex items-center space-x-2">
            {!isRunning && !isPaused && (
              <button
                onClick={startBatch}
                disabled={stats.pending === 0}
                className="flex items-center px-3 py-1.5 bg-blue-600 text-white text-sm rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <PlayIcon className="h-4 w-4 mr-1" />
                시작
              </button>
            )}
            {isRunning && (
              <button
                onClick={pauseBatch}
                className="flex items-center px-3 py-1.5 bg-yellow-600 text-white text-sm rounded-md hover:bg-yellow-700"
              >
                <PauseIcon className="h-4 w-4 mr-1" />
                일시정지
              </button>
            )}
            {(isRunning || isPaused) && (
              <button
                onClick={stopBatch}
                className="flex items-center px-3 py-1.5 bg-red-600 text-white text-sm rounded-md hover:bg-red-700"
              >
                <StopIcon className="h-4 w-4 mr-1" />
                중지
              </button>
            )}
            {stats.failed > 0 && !isRunning && (
              <button
                onClick={retryFailedJobs}
                className="flex items-center px-3 py-1.5 bg-green-600 text-white text-sm rounded-md hover:bg-green-700"
              >
                재시도
              </button>
            )}
          </div>
        </div>
      </div>

      {/* 통계 */}
      <div className="p-4 border-b border-gray-200">
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          <div className="text-center">
            <div className="text-2xl font-bold text-gray-900">
              {stats.total}
            </div>
            <div className="text-sm text-gray-500">전체</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-yellow-600">
              {stats.pending}
            </div>
            <div className="text-sm text-gray-500">대기</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-blue-600">
              {stats.processing}
            </div>
            <div className="text-sm text-gray-500">처리 중</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-green-600">
              {stats.completed}
            </div>
            <div className="text-sm text-gray-500">완료</div>
          </div>
          <div className="text-center">
            <div className="text-2xl font-bold text-red-600">
              {stats.failed}
            </div>
            <div className="text-sm text-gray-500">실패</div>
          </div>
        </div>
      </div>

      {/* 진행률 */}
      <div className="p-4 border-b border-gray-200">
        <div className="flex items-center justify-between mb-2">
          <span className="text-sm font-medium text-gray-700">전체 진행률</span>
          <span className="text-sm text-gray-500">
            {Math.round(
              ((stats.completed + stats.failed) / stats.total) * 100
            ) || 0}
            %
          </span>
        </div>
        <div className="w-full bg-gray-200 rounded-full h-2">
          <div
            className="bg-blue-500 h-2 rounded-full transition-all duration-500"
            style={{
              width: `${
                ((stats.completed + stats.failed) / stats.total) * 100 || 0
              }%`,
            }}
          />
        </div>
      </div>

      {/* 작업 목록 */}
      <div className="p-4">
        <div className="space-y-2 max-h-64 overflow-y-auto">
          {jobs.map((job, _index) => (
            <div
              key={job.uploadId}
              className="flex items-center justify-between p-2 bg-gray-50 rounded-md"
            >
              <div className="flex-1">
                <div className="text-sm font-medium text-gray-900">
                  {job.fileName}
                </div>
                <div className="text-xs text-gray-500">{job.uploadId}</div>
              </div>
              <div className="flex items-center space-x-2">
                <div
                  className={`px-2 py-1 text-xs rounded-full ${
                    job.status === "pending"
                      ? "bg-yellow-100 text-yellow-800"
                      : job.status === "processing"
                      ? "bg-blue-100 text-blue-800"
                      : job.status === "completed"
                      ? "bg-green-100 text-green-800"
                      : "bg-red-100 text-red-800"
                  }`}
                >
                  {job.status === "pending"
                    ? "대기"
                    : job.status === "processing"
                    ? "처리 중"
                    : job.status === "completed"
                    ? "완료"
                    : "실패"}
                </div>
                {job.status === "processing" && (
                  <div className="text-xs text-gray-500">{job.progress}%</div>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 처리 옵션 */}
      <div className="p-4 border-t border-gray-200 bg-gray-50">
        <details className="group">
          <summary className="flex items-center justify-between cursor-pointer">
            <span className="text-sm font-medium text-gray-700">처리 옵션</span>
            <ChartBarIcon className="h-4 w-4 text-gray-400 group-open:transform group-open:rotate-180 transition-transform" />
          </summary>
          <div className="mt-3 space-y-3">
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                이미지 크기
              </label>
              <div className="flex flex-wrap gap-2">
                {["thumbnail", "small", "medium", "large"].map((size) => (
                  <label key={size} className="flex items-center">
                    <input
                      type="checkbox"
                      checked={options.sizes.includes(size)}
                      onChange={(e) => {
                        if (e.target.checked) {
                          setOptions((prev) => ({
                            ...prev,
                            sizes: [...prev.sizes, size],
                          }));
                        } else {
                          setOptions((prev) => ({
                            ...prev,
                            sizes: prev.sizes.filter((s) => s !== size),
                          }));
                        }
                      }}
                      className="mr-1 h-3 w-3"
                    />
                    <span className="text-xs text-gray-600">{size}</span>
                  </label>
                ))}
              </div>
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-700 mb-1">
                품질: {options.quality}%
              </label>
              <input
                type="range"
                min="1"
                max="100"
                value={options.quality}
                onChange={(e) =>
                  setOptions((prev) => ({
                    ...prev,
                    quality: parseInt(e.target.value),
                  }))
                }
                className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
              />
            </div>
            <div className="flex items-center space-x-4">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={options.enableWebp}
                  onChange={(e) =>
                    setOptions((prev) => ({
                      ...prev,
                      enableWebp: e.target.checked,
                    }))
                  }
                  className="mr-1 h-3 w-3"
                />
                <span className="text-xs text-gray-600">WebP 생성</span>
              </label>
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={options.stripMetadata}
                  onChange={(e) =>
                    setOptions((prev) => ({
                      ...prev,
                      stripMetadata: e.target.checked,
                    }))
                  }
                  className="mr-1 h-3 w-3"
                />
                <span className="text-xs text-gray-600">메타데이터 제거</span>
              </label>
            </div>
          </div>
        </details>
      </div>
    </div>
  );
}
