"use client";

import React, { useState, useEffect } from "react";
import {
  PhotoIcon,
  ClockIcon,
  CheckCircleIcon,
  XCircleIcon,
  SparklesIcon,
} from "@heroicons/react/24/outline";

// 처리 작업 상태
interface ProcessingJob {
  id: string;
  uploadId: string;
  status: "pending" | "processing" | "completed" | "failed";
  progress: number;
  error?: string;
  createdAt: string;
  startedAt?: string;
  completedAt?: string;
  result?: {
    original: {
      width: number;
      height: number;
      format: string;
      size: number;
    };
    processed: Array<{
      size: string;
      format: string;
      width: number;
      height: number;
      fileSize: number;
      url: string;
    }>;
    webp?: Array<{
      size: string;
      width: number;
      height: number;
      fileSize: number;
      url: string;
    }>;
  };
}

interface ImageProcessorProps {
  uploadId: string;
  onProcessingComplete?: (result: ProcessingJob["result"]) => void;
  className?: string;
}

export function ImageProcessor({
  uploadId,
  onProcessingComplete,
  className = "",
}: ImageProcessorProps) {
  const [job, setJob] = useState<ProcessingJob | null>(null);
  const [error, setError] = useState<string>("");

  // 처리 상태 폴링
  useEffect(() => {
    if (!uploadId) return;

    const checkStatus = async () => {
      try {
        const response = await fetch(`/api/media/process?uploadId=${uploadId}`);
        const data = await response.json();

        if (data.success && data.job) {
          setJob(data.job);

          // 처리 완료 시 콜백 호출
          if (
            data.job.status === "completed" &&
            data.job.result &&
            onProcessingComplete
          ) {
            onProcessingComplete(data.job.result);
          }
        } else if (!response.ok) {
          setError(data.error || "Failed to get processing status");
        }
      } catch (err) {
        setError("Failed to check processing status");
        console.error("Processing status check failed:", err);
      }
    };

    // 초기 확인
    checkStatus();

    // 처리 중인 경우 주기적으로 확인
    const interval = setInterval(() => {
      if (job?.status === "processing" || job?.status === "pending") {
        checkStatus();
      }
    }, 2000);

    return () => clearInterval(interval);
  }, [uploadId, job?.status, onProcessingComplete]);

  const getStatusIcon = (status: ProcessingJob["status"]) => {
    switch (status) {
      case "pending":
        return <ClockIcon className="h-5 w-5 text-yellow-500" />;
      case "processing":
        return <SparklesIcon className="h-5 w-5 text-blue-500 animate-spin" />;
      case "completed":
        return <CheckCircleIcon className="h-5 w-5 text-green-500" />;
      case "failed":
        return <XCircleIcon className="h-5 w-5 text-red-500" />;
      default:
        return <PhotoIcon className="h-5 w-5 text-gray-400" />;
    }
  };

  const getStatusText = (status: ProcessingJob["status"]) => {
    switch (status) {
      case "pending":
        return "대기 중...";
      case "processing":
        return "처리 중...";
      case "completed":
        return "처리 완료";
      case "failed":
        return "처리 실패";
      default:
        return "알 수 없음";
    }
  };

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return "0 B";
    const k = 1024;
    const sizes = ["B", "KB", "MB", "GB"];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
  };

  const calculateSavings = (original: number, processed: number): number => {
    return Math.round(((original - processed) / original) * 100);
  };

  if (error) {
    return (
      <div
        className={`bg-red-50 border border-red-200 rounded-lg p-4 ${className}`}
      >
        <div className="flex items-center">
          <XCircleIcon className="h-5 w-5 text-red-500 mr-2" />
          <span className="text-sm text-red-700">{error}</span>
        </div>
      </div>
    );
  }

  if (!job) {
    return (
      <div
        className={`bg-gray-50 border border-gray-200 rounded-lg p-4 ${className}`}
      >
        <div className="flex items-center">
          <ClockIcon className="h-5 w-5 text-gray-400 mr-2" />
          <span className="text-sm text-gray-600">처리 상태 확인 중...</span>
        </div>
      </div>
    );
  }

  return (
    <div
      className={`bg-white border border-gray-200 rounded-lg p-4 ${className}`}
    >
      {/* 상태 헤더 */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center">
          {getStatusIcon(job.status)}
          <span className="ml-2 text-sm font-medium text-gray-900">
            {getStatusText(job.status)}
          </span>
        </div>
        <span className="text-xs text-gray-500">{job.progress}%</span>
      </div>

      {/* 진행률 바 */}
      {(job.status === "processing" || job.status === "pending") && (
        <div className="mb-4">
          <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: `${job.progress}%` }}
            />
          </div>
        </div>
      )}

      {/* 에러 메시지 */}
      {job.status === "failed" && job.error && (
        <div className="mb-4 p-3 bg-red-50 border border-red-200 rounded-md">
          <p className="text-sm text-red-700">{job.error}</p>
        </div>
      )}

      {/* 처리 결과 */}
      {job.status === "completed" && job.result && (
        <div className="space-y-4">
          {/* 원본 정보 */}
          <div className="bg-gray-50 rounded-lg p-3">
            <h4 className="text-sm font-medium text-gray-900 mb-2">
              원본 이미지
            </h4>
            <div className="grid grid-cols-2 gap-4 text-xs text-gray-600">
              <div>
                크기: {job.result.original.width} × {job.result.original.height}
                px
              </div>
              <div>포맷: {job.result.original.format.toUpperCase()}</div>
              <div>파일 크기: {formatFileSize(job.result.original.size)}</div>
            </div>
          </div>

          {/* 처리된 이미지들 */}
          <div>
            <h4 className="text-sm font-medium text-gray-900 mb-2">
              최적화된 이미지
            </h4>
            <div className="space-y-2">
              {job.result.processed.map((processed, index) => (
                <div
                  key={index}
                  className="flex items-center justify-between p-2 bg-green-50 rounded-md"
                >
                  <div className="flex-1">
                    <div className="text-xs font-medium text-gray-900">
                      {processed.size} ({processed.width} × {processed.height}
                      px)
                    </div>
                    <div className="text-xs text-gray-600">
                      {formatFileSize(processed.fileSize)} •{" "}
                      {processed.format.toUpperCase()}
                    </div>
                  </div>
                  <div className="text-xs text-green-600 font-medium">
                    -
                    {calculateSavings(
                      job.result!.original.size,
                      processed.fileSize
                    )}
                    %
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* WebP 이미지들 */}
          {job.result.webp && job.result.webp.length > 0 && (
            <div>
              <h4 className="text-sm font-medium text-gray-900 mb-2">
                WebP 이미지
              </h4>
              <div className="space-y-2">
                {job.result.webp.map((webp, index) => (
                  <div
                    key={index}
                    className="flex items-center justify-between p-2 bg-blue-50 rounded-md"
                  >
                    <div className="flex-1">
                      <div className="text-xs font-medium text-gray-900">
                        {webp.size} ({webp.width} × {webp.height}px)
                      </div>
                      <div className="text-xs text-gray-600">
                        {formatFileSize(webp.fileSize)} • WebP
                      </div>
                    </div>
                    <div className="text-xs text-blue-600 font-medium">
                      추가 최적화
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* 처리 시간 */}
          {job.startedAt && job.completedAt && (
            <div className="text-xs text-gray-500 pt-2 border-t border-gray-200">
              처리 시간:{" "}
              {Math.round(
                (new Date(job.completedAt).getTime() -
                  new Date(job.startedAt).getTime()) /
                  1000
              )}
              초
            </div>
          )}
        </div>
      )}
    </div>
  );
}
