"use client";

import {
  Clock,
  CheckCircle,
  XCircle,
  Loader,
  Download,
  FileImage,
  TrendingDown,
} from "lucide-react";
import { ProcessingJob } from "../types";

interface ProcessingQueueProps {
  jobs: ProcessingJob[];
  onDownloadAll?: () => void;
  batchId?: string | null;
}

export default function ProcessingQueue({
  jobs,
  onDownloadAll,
  batchId,
}: ProcessingQueueProps) {
  const getStatusIcon = (status: string) => {
    switch (status) {
      case "pending":
        return <Clock className="w-5 h-5 text-yellow-500" />;
      case "processing":
        return <Loader className="w-5 h-5 text-blue-500 animate-spin" />;
      case "completed":
        return <CheckCircle className="w-5 h-5 text-green-500" />;
      case "failed":
        return <XCircle className="w-5 h-5 text-red-500" />;
      default:
        return <Clock className="w-5 h-5 text-gray-400" />;
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case "pending":
        return "bg-yellow-100 text-yellow-800";
      case "processing":
        return "bg-blue-100 text-blue-800";
      case "completed":
        return "bg-green-100 text-green-800";
      case "failed":
        return "bg-red-100 text-red-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

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

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

  const completedJobs = jobs.filter(
    (job) => job.status === "completed" && job.optimizedSize > 0
  );
  const totalOriginalSize = completedJobs.reduce(
    (sum, job) => sum + job.originalSize,
    0
  );
  const totalOptimizedSize = completedJobs.reduce(
    (sum, job) => sum + job.optimizedSize,
    0
  );
  const totalSavings =
    totalOriginalSize > 0
      ? calculateSavings(totalOriginalSize, totalOptimizedSize)
      : 0;
  const totalSavedBytes = totalOriginalSize - totalOptimizedSize;

  const allCompleted =
    jobs.length > 0 && jobs.every((job) => job.status === "completed");
  const hasCompletedJobs = completedJobs.length > 0;

  if (jobs.length === 0) {
    return (
      <div className="bg-white rounded-2xl shadow-lg p-8">
        <h3 className="text-xl font-bold text-gray-900 mb-4">Processing Queue</h3>
        <div className="text-center py-12">
          <FileImage className="w-16 h-16 text-gray-300 mx-auto mb-4" />
          <p className="text-gray-500">No images in queue</p>
          <p className="text-sm text-gray-400 mt-2">
            Upload images to start processing
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-white rounded-2xl shadow-lg p-8">
      <div className="flex items-center justify-between mb-6">
        <h3 className="text-xl font-bold text-gray-900">Processing Queue</h3>
        <span className="text-sm text-gray-500">{jobs.length} files</span>
      </div>

      {/* Stats Summary */}
      {hasCompletedJobs && (
        <div className="bg-gradient-to-r from-green-50 to-blue-50 rounded-lg p-4 mb-6">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <p className="text-sm text-gray-600">Total Savings</p>
              <p className="text-2xl font-bold text-green-600">{totalSavings}%</p>
            </div>
            <div className="text-right">
              <p className="text-sm text-gray-600">Size Reduction</p>
              <p className="text-lg font-semibold text-gray-900">
                {formatFileSize(totalSavedBytes)}
              </p>
            </div>
            <div className="col-span-2 pt-2 border-t border-gray-200">
              <div className="flex justify-between text-sm text-gray-600">
                <span>Original: {formatFileSize(totalOriginalSize)}</span>
                <span>Optimized: {formatFileSize(totalOptimizedSize)}</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Jobs */}
      <div className="space-y-3 max-h-96 overflow-y-auto">
        {jobs.map((job) => (
          <div key={job.id} className="border border-gray-200 rounded-lg p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center space-x-3">
                {getStatusIcon(job.status)}
                <div className="min-w-0 flex-1">
                  <p
                    className="text-sm font-medium text-gray-900 truncate"
                    title={job.fileName}
                  >
                    {job.fileName}
                  </p>
                  <p className="text-xs text-gray-500">
                    {formatFileSize(job.originalSize)}
                    {job.optimizedSize > 0 && (
                      <span className="text-green-600 ml-2">
                        → {formatFileSize(job.optimizedSize)}
                      </span>
                    )}
                  </p>
                </div>
              </div>
              <span
                className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(
                  job.status
                )}`}
              >
                {job.status.charAt(0).toUpperCase() + job.status.slice(1)}
              </span>
            </div>

            {job.status === "processing" && (
              <div className="mb-3">
                <div className="flex justify-between text-xs text-gray-600 mb-1">
                  <span>Processing...</span>
                  <span>{job.progress}%</span>
                </div>
                <div className="w-full bg-gray-200 rounded-full h-2">
                  <div
                    className="bg-gradient-to-r from-blue-500 to-purple-600 h-2 rounded-full transition-all duration-300"
                    style={{ width: `${job.progress}%` }}
                  />
                </div>
              </div>
            )}

            {job.status === "completed" && job.optimizedSize > 0 && (
              <div className="flex items-center justify-between text-xs text-gray-600">
                <span className="flex items-center">
                  <TrendingDown className="w-3 h-3 mr-1 text-green-500" />
                  {calculateSavings(job.originalSize, job.optimizedSize)}% smaller
                </span>
              </div>
            )}

            {job.status === "failed" && job.errorMessage && (
              <p className="text-xs text-red-600 mt-2">
                Error: {job.errorMessage}
              </p>
            )}
          </div>
        ))}
      </div>

      {allCompleted && hasCompletedJobs && batchId && (
        <div className="mt-6 pt-6 border-t border-gray-200">
          <button
            onClick={onDownloadAll}
            className="w-full flex items-center justify-center space-x-2 px-6 py-3 bg-gradient-to-r from-green-500 to-blue-600 text-white font-semibold rounded-lg hover:from-green-600 hover:to-blue-700 transition-all transform hover:scale-105"
          >
            <Download className="w-5 h-5" />
            <span>Download All ({completedJobs.length} files)</span>
          </button>
        </div>
      )}
    </div>
  );
}
