"use client";
import React, { useState } from 'react';
import ImageUploader from '@/components/ImageUploader';
import OptimizationSettings from '@/components/OptimizationSettings';
import ProcessingQueue from '@/components/ProcessingQueue';
import { OptimizationOptions, ProcessingJob } from '@/types/index';
import { processingApi } from '@/app/api/api';
import toast from 'react-hot-toast';

export default function OptimizePage() {
  const [files, setFiles] = useState<File[]>([]);
  const [options, setOptions] = useState<OptimizationOptions>({
    format: 'webp',
    quality: 80,
    namingTemplate: '{name}-optimized',
    seoKeywords: '',
    preserveMetadata: true,
  });
  const [jobs, setJobs] = useState<ProcessingJob[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [batchId, setBatchId] = useState<string | null>(null);

  const handleFilesSelected = (selectedFiles: File[]) => {
    setFiles(selectedFiles);
    // Reset jobs when new files are selected
    setJobs([]);
    setBatchId(null);
  };

  const handleStartProcessing = async () => {
    if (files.length === 0) {
      toast.error('Please select images to optimize');
      return;
    }

    setIsProcessing(true);
    
    try {
      // Create initial jobs with pending status
      const initialJobs: ProcessingJob[] = files.map((file, index) => ({
        id: `job-${Date.now()}-${index}`,
        fileName: file.name,
        status: 'pending',
        originalSize: file.size,
        optimizedSize: 0,
        progress: 0,
      }));

      setJobs(initialJobs);

      // Start batch processing
      const batchName = `Batch ${new Date().toLocaleString()}`;
      const response = await processingApi.startBatch(files, options, batchName);
      
      setBatchId(response.batchId);
      toast.success('Processing started!');

      // Poll for status updates
      pollBatchStatus(response.batchId);

    } catch (error: any) {
      console.error('Processing error:', error);
      const errorMessage = error.response?.data?.error || 'Processing failed';
      
      // Handle specific error types
      if (error.response?.status === 413) {
        if (errorMessage.includes('File too large')) {
          toast.error('One or more files exceed the 50MB limit. Please reduce file sizes and try again.');
        } else if (errorMessage.includes('Too many files')) {
          toast.error('Too many files selected. Maximum 100 files per batch.');
        } else {
          toast.error(errorMessage);
        }
      } else if (error.response?.status === 400 && errorMessage.includes('supported image format')) {
        toast.error('Some files are not supported image formats. Please upload JPG, PNG, GIF, SVG, HEIC, BMP, or TIFF files.');
      } else {
        toast.error(errorMessage);
      }
      
      setIsProcessing(false);
    }
  };

  const pollBatchStatus = async (batchId: string) => {
    try {
      const status = await processingApi.getBatchStatus(batchId);
      
      if (status.jobs) {
        // Update jobs with real data from backend
        const updatedJobs: ProcessingJob[] = status.jobs.map((job: any) => ({
          id: job.id,
          fileName: job.original_filename,
          status: job.status,
          originalSize: job.original_size,
          optimizedSize: job.output_size || 0,
          progress: job.progress,
          errorMessage: job.error_message
        }));
        
        setJobs(updatedJobs);
      }

      // Continue polling if still processing
      if (status.status === 'processing') {
        setTimeout(() => pollBatchStatus(batchId), 2000);
      } else {
        setIsProcessing(false);
        if (status.status === 'completed') {
          toast.success('All images processed successfully!');
        } else if (status.status === 'failed') {
          toast.error('Batch processing failed');
        }
      }
    } catch (error) {
      console.error('Status polling error:', error);
      setIsProcessing(false);
    }
  };

  const handleDownloadAll = async () => {
    if (!batchId) {
      toast.error('No batch available for download');
      return;
    }

    try {
      await processingApi.downloadBatch(batchId);
      toast.success('Download started!');
    } catch (error: any) {
      console.error('Download error:', error);
      toast.error(error.response?.data?.error || 'Download failed');
    }
  };

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">
          Optimize Your Images
        </h1>
        <p className="text-gray-600">
          Upload, configure, and optimize your images for maximum web performance.
        </p>
      </div>

      <div className="grid lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-8">
          <ImageUploader onFilesSelected={handleFilesSelected} />
          
          {files.length > 0 && (
            <OptimizationSettings 
              options={options}
              onOptionsChange={setOptions}
              onStartProcessing={handleStartProcessing}
              isProcessing={isProcessing}
              fileCount={files.length}
            />
          )}
        </div>

        <div className="lg:col-span-1">
          <ProcessingQueue 
            jobs={jobs} 
            onDownloadAll={handleDownloadAll}
            batchId={batchId}
          />
        </div>
      </div>
    </div>
  );
}

