'use client';

import * as React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Slider } from '@/components/ui/slider';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { FileUpload } from './FileUpload';
import { ConversionPreview } from './ConversionPreview';
import { toast } from 'sonner';
import {
  getFormatByExtension,
  getFormatByMimeType,
  getCompatibleFormats,
} from '@/lib/media/utils/formatMappings';
import { convertWithFFmpeg } from '@/lib/media/converters/ffmpegService';
import { convertWithImageMagick } from '@/lib/media/converters/imagemagickService';
import { addToHistory } from '@/lib/media/storage/history';
import { downloadBlobsAsZip, generateOutputFilename } from '@/lib/media/utils/fileUtils';
import type { ConversionJob, ConversionFormat, ConversionOptions } from '@/types/media';

export function FileConverter() {
  const [selectedFiles, setSelectedFiles] = React.useState<File[]>([]);
  const [inputFormat, setInputFormat] = React.useState<ConversionFormat | undefined>();
  const [outputFormat, setOutputFormat] = React.useState<ConversionFormat | undefined>();
  const [compatibleFormats, setCompatibleFormats] = React.useState<ConversionFormat[]>([]);
  const [conversionJobs, setConversionJobs] = React.useState<ConversionJob[]>([]);
  const [conversionOptions, setConversionOptions] = React.useState<ConversionOptions>({});

  const fileInputRef = React.useRef<HTMLInputElement>(null);

  // Detect input format when files are selected
  React.useEffect(() => {
    if (selectedFiles.length === 0) {
      setInputFormat(undefined);
      setOutputFormat(undefined);
      setCompatibleFormats([]);
      setConversionJobs([]);
      return;
    }

    // Use first file to detect format (assume all files same format for batch)
    const firstFile = selectedFiles[0];

    // Try to detect format from extension
    const ext = firstFile.name.split('.').pop()?.toLowerCase();
    let format = ext ? getFormatByExtension(ext) : undefined;

    // Fallback to MIME type
    if (!format) {
      format = getFormatByMimeType(firstFile.type);
    }

    if (format) {
      setInputFormat(format);
      const compatible = getCompatibleFormats(format);
      setCompatibleFormats(compatible);

      // Auto-select first compatible format
      if (compatible.length > 0 && !outputFormat) {
        setOutputFormat(compatible[0]);
      }

      toast.success(`Detected format: ${format.name} (${selectedFiles.length} file${selectedFiles.length > 1 ? 's' : ''})`);
    } else {
      toast.error('Could not detect file format');
      setInputFormat(undefined);
      setCompatibleFormats([]);
    }
  }, [selectedFiles]);

  const handleConvert = async () => {
    if (selectedFiles.length === 0 || !inputFormat || !outputFormat) {
      toast.error('Please select files and output format');
      return;
    }

    // Create conversion jobs for all files
    const jobs: ConversionJob[] = selectedFiles.map((file) => ({
      id: Math.random().toString(36).substring(7),
      inputFile: file,
      inputFormat,
      outputFormat,
      options: conversionOptions,
      status: 'pending',
      progress: 0,
      startTime: Date.now(),
    }));

    setConversionJobs(jobs);

    // Track success/failure counts
    let successCount = 0;
    let failureCount = 0;

    // Convert files sequentially
    for (let i = 0; i < jobs.length; i++) {
      const job = jobs[i];

      try {
        // Update job to loading
        setConversionJobs((prev) =>
          prev.map((j, idx) => idx === i ? { ...j, status: 'loading' as const } : j)
        );

        // Update job to processing
        setConversionJobs((prev) =>
          prev.map((j, idx) => idx === i ? { ...j, status: 'processing' as const, progress: 10 } : j)
        );

        // Call appropriate converter
        let result;

        if (!outputFormat) throw new Error('Output format not selected');

        switch (outputFormat.converter) {
          case 'ffmpeg':
            result = await convertWithFFmpeg(job.inputFile, outputFormat.extension, conversionOptions, (progress) => {
              setConversionJobs((prev) =>
                prev.map((j, idx) => idx === i ? { ...j, progress } : j)
              );
            });
            break;

          case 'imagemagick':
            result = await convertWithImageMagick(
              job.inputFile,
              outputFormat.extension,
              conversionOptions,
              (progress) => {
                setConversionJobs((prev) =>
                  prev.map((j, idx) => idx === i ? { ...j, progress } : j)
                );
              }
            );
            break;

          default:
            throw new Error(`Unknown converter: ${outputFormat.converter}`);
        }

        // Update job with result
        if (result.success && result.blob) {
          successCount++;

          setConversionJobs((prev) =>
            prev.map((j, idx) => idx === i ? {
              ...j,
              status: 'completed' as const,
              progress: 100,
              result: result.blob,
              endTime: Date.now(),
            } : j)
          );

          // Add to history
          addToHistory({
            inputFileName: job.inputFile.name,
            inputFormat: inputFormat.name,
            outputFormat: outputFormat.name,
            outputFileName: `output.${outputFormat.extension}`,
            fileSize: result.blob.size,
            result: result.blob,
          });
        } else {
          failureCount++;

          setConversionJobs((prev) =>
            prev.map((j, idx) => idx === i ? {
              ...j,
              status: 'error' as const,
              error: result.error || 'Unknown error',
              endTime: Date.now(),
            } : j)
          );
        }
      } catch (error) {
        failureCount++;
        const errorMessage = error instanceof Error ? error.message : 'Unknown error';

        setConversionJobs((prev) =>
          prev.map((j, idx) => idx === i ? {
            ...j,
            status: 'error' as const,
            error: errorMessage,
            endTime: Date.now(),
          } : j)
        );
      }
    }

    // Show completion message
    if (successCount === jobs.length) {
      toast.success(`All ${jobs.length} files converted successfully!`);
    } else if (successCount > 0) {
      toast.info(`${successCount}/${jobs.length} files converted successfully`);
    } else {
      toast.error('All conversions failed');
    }
  };

  const handleReset = () => {
    setSelectedFiles([]);
    setInputFormat(undefined);
    setOutputFormat(undefined);
    setCompatibleFormats([]);
    setConversionJobs([]);
    setConversionOptions({});
  };

  const handleFileSelect = (files: File[]) => {
    setSelectedFiles((prev) => [...prev, ...files]);
  };

  const handleFileRemove = (index: number) => {
    setSelectedFiles((prev) => prev.filter((_, i) => i !== index));
  };

  const handleDownloadAll = async () => {
    if (!outputFormat) return;

    const completedJobs = conversionJobs.filter(job => job.status === 'completed' && job.result);

    if (completedJobs.length === 0) {
      toast.error('No files to download');
      return;
    }

    if (completedJobs.length === 1) {
      // Just download the single file
      const job = completedJobs[0];
      const filename = generateOutputFilename(job.inputFile.name, outputFormat.extension);
      const url = URL.createObjectURL(job.result!);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      return;
    }

    // Download multiple files as ZIP
    const files = completedJobs.map(job => ({
      blob: job.result!,
      filename: generateOutputFilename(job.inputFile.name, outputFormat.extension),
    }));

    await downloadBlobsAsZip(files, `converted-files.zip`);
    toast.success(`Downloaded ${files.length} files as ZIP`);
  };

  const handleRetry = async (jobId: string) => {
    const jobIndex = conversionJobs.findIndex(j => j.id === jobId);
    if (jobIndex === -1 || !outputFormat) return;

    const job = conversionJobs[jobIndex];

    try {
      // Reset job to loading
      setConversionJobs((prev) =>
        prev.map((j, idx) => idx === jobIndex ? {
          ...j,
          status: 'loading' as const,
          progress: 0,
          error: undefined,
          startTime: Date.now(),
        } : j)
      );

      // Update to processing
      setConversionJobs((prev) =>
        prev.map((j, idx) => idx === jobIndex ? { ...j, status: 'processing' as const, progress: 10 } : j)
      );

      // Call appropriate converter
      let result;

      switch (outputFormat.converter) {
        case 'ffmpeg':
          result = await convertWithFFmpeg(job.inputFile, outputFormat.extension, conversionOptions, (progress) => {
            setConversionJobs((prev) =>
              prev.map((j, idx) => idx === jobIndex ? { ...j, progress } : j)
            );
          });
          break;

        case 'imagemagick':
          result = await convertWithImageMagick(
            job.inputFile,
            outputFormat.extension,
            conversionOptions,
            (progress) => {
              setConversionJobs((prev) =>
                prev.map((j, idx) => idx === jobIndex ? { ...j, progress } : j)
              );
            }
          );
          break;

        default:
          throw new Error(`Unknown converter: ${outputFormat.converter}`);
      }

      // Update job with result
      if (result.success && result.blob) {
        setConversionJobs((prev) =>
          prev.map((j, idx) => idx === jobIndex ? {
            ...j,
            status: 'completed' as const,
            progress: 100,
            result: result.blob,
            endTime: Date.now(),
          } : j)
        );

        toast.success('Conversion completed successfully!');

        // Add to history
        addToHistory({
          inputFileName: job.inputFile.name,
          inputFormat: job.inputFormat.name,
          outputFormat: outputFormat.name,
          outputFileName: `output.${outputFormat.extension}`,
          fileSize: result.blob.size,
          result: result.blob,
        });
      } else {
        setConversionJobs((prev) =>
          prev.map((j, idx) => idx === jobIndex ? {
            ...j,
            status: 'error' as const,
            error: result.error || 'Unknown error',
            endTime: Date.now(),
          } : j)
        );

        toast.error(result.error || 'Retry failed');
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : 'Unknown error';

      setConversionJobs((prev) =>
        prev.map((j, idx) => idx === jobIndex ? {
          ...j,
          status: 'error' as const,
          error: errorMessage,
          endTime: Date.now(),
        } : j)
      );

      toast.error(`Retry failed: ${errorMessage}`);
    }
  };

  const isConverting = conversionJobs.some(job => job.status === 'loading' || job.status === 'processing');
  const isConvertDisabled = selectedFiles.length === 0 || !outputFormat || isConverting;
  const completedCount = conversionJobs.filter(job => job.status === 'completed').length;

  return (
    <div className="grid grid-cols-1 lg:grid-cols-2 gap-6 w-full">
      {/* Left Column: Upload and Conversion Options */}
      <div className="space-y-6">
        {/* Upload Card */}
        <Card>
          <CardContent>
            <FileUpload
              onFileSelect={handleFileSelect}
              onFileRemove={handleFileRemove}
              selectedFiles={selectedFiles}
              disabled={isConverting}
              inputRef={fileInputRef}
              inputFormat={inputFormat}
            />
          </CardContent>
        </Card>

        {/* Conversion Options Card */}
        {inputFormat && compatibleFormats.length > 0 && (
          <Card>
            <CardHeader>
              <CardTitle>Options</CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Output Format Select */}
              <div className="space-y-1.5">
                <Label className="text-xs">Output Format</Label>
                <Select
                  value={outputFormat?.id || ''}
                  onValueChange={(formatId) => {
                    const format = compatibleFormats.find(f => f.id === formatId);
                    if (format) setOutputFormat(format);
                  }}
                  disabled={isConverting}
                >
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Select output format" />
                  </SelectTrigger>
                  <SelectContent>
                    {compatibleFormats.map((format) => (
                      <SelectItem key={format.id} value={format.id}>
                        {format.name} (.{format.extension})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Advanced Options - Inline */}
              {outputFormat && (
                <>
                  {outputFormat.category === 'video' && (
                    <div className="space-y-4 pt-4 border-t border-border">
                      {/* Video Codec */}
                      <div className="space-y-2">
                        <Label className="text-xs">Video Codec</Label>
                        <Select
                          value={conversionOptions.videoCodec || 'default'}
                          onValueChange={(value) => setConversionOptions({ ...conversionOptions, videoCodec: value === 'default' ? undefined : value })}
                          disabled={isConverting}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select video codec" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="default">Auto (Recommended)</SelectItem>
                            <SelectItem value="libx264">H.264 (MP4, AVI, MOV)</SelectItem>
                            <SelectItem value="libx265">H.265 (MP4)</SelectItem>
                            <SelectItem value="libvpx">VP8 (WebM)</SelectItem>
                            <SelectItem value="libvpx-vp9">VP9 (WebM)</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Video Bitrate */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <Label className="text-xs">Video Bitrate</Label>
                          <span className="text-xs text-muted-foreground">{conversionOptions.videoBitrate || '2M'}</span>
                        </div>
                        <Slider
                          min={0.5}
                          max={10}
                          step={0.5}
                          value={[parseFloat(conversionOptions.videoBitrate?.replace('M', '') || '2')]}
                          onValueChange={(vals) => setConversionOptions({ ...conversionOptions, videoBitrate: `${vals[0]}M` })}
                          disabled={isConverting}
                        />
                        <p className="text-xs text-muted-foreground">Higher bitrate = better quality, larger file</p>
                      </div>

                      {/* Resolution */}
                      <div className="space-y-2">
                        <Label className="text-xs">Resolution</Label>
                        <Select
                          value={conversionOptions.videoResolution || 'original'}
                          onValueChange={(value) => setConversionOptions({ ...conversionOptions, videoResolution: value === 'original' ? undefined : value })}
                          disabled={isConverting}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select resolution" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="original">Original</SelectItem>
                            <SelectItem value="1920x-1">1080p (1920x1080)</SelectItem>
                            <SelectItem value="1280x-1">720p (1280x720)</SelectItem>
                            <SelectItem value="854x-1">480p (854x480)</SelectItem>
                            <SelectItem value="640x-1">360p (640x360)</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* FPS */}
                      <div className="space-y-2">
                        <Label className="text-xs">Frame Rate (FPS)</Label>
                        <Select
                          value={conversionOptions.videoFps?.toString() || 'original'}
                          onValueChange={(value) => setConversionOptions({ ...conversionOptions, videoFps: value === 'original' ? undefined : parseInt(value) })}
                          disabled={isConverting}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select frame rate" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="original">Original</SelectItem>
                            <SelectItem value="60">60 fps</SelectItem>
                            <SelectItem value="30">30 fps</SelectItem>
                            <SelectItem value="24">24 fps</SelectItem>
                            <SelectItem value="15">15 fps</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Audio Bitrate */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <Label className="text-xs">Audio Bitrate</Label>
                          <span className="text-xs text-muted-foreground">{conversionOptions.audioBitrate || '128k'}</span>
                        </div>
                        <Slider
                          min={64}
                          max={320}
                          step={32}
                          value={[parseInt(conversionOptions.audioBitrate?.replace('k', '') || '128')]}
                          onValueChange={(vals) => setConversionOptions({ ...conversionOptions, audioBitrate: `${vals[0]}k` })}
                          disabled={isConverting}
                        />
                      </div>
                    </div>
                  )}

                  {outputFormat.category === 'audio' && (
                    <div className="space-y-4 pt-4 border-t border-border">
                      {/* Audio Codec */}
                      <div className="space-y-2">
                        <Label className="text-xs">Audio Codec</Label>
                        <Select
                          value={conversionOptions.audioCodec || 'default'}
                          onValueChange={(value) => setConversionOptions({ ...conversionOptions, audioCodec: value === 'default' ? undefined : value })}
                          disabled={isConverting}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select audio codec" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="default">Auto (Recommended)</SelectItem>
                            <SelectItem value="libmp3lame">MP3 (LAME)</SelectItem>
                            <SelectItem value="aac">AAC</SelectItem>
                            <SelectItem value="libvorbis">Vorbis (OGG)</SelectItem>
                            <SelectItem value="libopus">Opus</SelectItem>
                            <SelectItem value="flac">FLAC (Lossless)</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Bitrate */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <Label className="text-xs">Bitrate</Label>
                          <span className="text-xs text-muted-foreground">{conversionOptions.audioBitrate || '192k'}</span>
                        </div>
                        <Slider
                          min={64}
                          max={320}
                          step={32}
                          value={[parseInt(conversionOptions.audioBitrate?.replace('k', '') || '192')]}
                          onValueChange={(vals) => setConversionOptions({ ...conversionOptions, audioBitrate: `${vals[0]}k` })}
                          disabled={isConverting}
                        />
                      </div>

                      {/* Sample Rate */}
                      <div className="space-y-2">
                        <Label className="text-xs">Sample Rate</Label>
                        <Select
                          value={conversionOptions.audioSampleRate?.toString() || 'original'}
                          onValueChange={(value) => setConversionOptions({ ...conversionOptions, audioSampleRate: value === 'original' ? undefined : parseInt(value) })}
                          disabled={isConverting}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select sample rate" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="original">Original</SelectItem>
                            <SelectItem value="48000">48 kHz (Studio)</SelectItem>
                            <SelectItem value="44100">44.1 kHz (CD Quality)</SelectItem>
                            <SelectItem value="22050">22.05 kHz</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      {/* Channels */}
                      <div className="space-y-2">
                        <Label className="text-xs">Channels</Label>
                        <Select
                          value={conversionOptions.audioChannels?.toString() || 'original'}
                          onValueChange={(value) => setConversionOptions({ ...conversionOptions, audioChannels: value === 'original' ? undefined : parseInt(value) })}
                          disabled={isConverting}
                        >
                          <SelectTrigger className="w-full">
                            <SelectValue placeholder="Select channels" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="original">Original</SelectItem>
                            <SelectItem value="2">Stereo (2 channels)</SelectItem>
                            <SelectItem value="1">Mono (1 channel)</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>
                    </div>
                  )}

                  {outputFormat.category === 'image' && (
                    <div className="space-y-4 pt-4 border-t border-border">
                      {/* Quality */}
                      <div className="space-y-2">
                        <div className="flex items-center justify-between">
                          <Label className="text-xs">Quality</Label>
                          <span className="text-xs text-muted-foreground">{conversionOptions.imageQuality || 85}%</span>
                        </div>
                        <Slider
                          min={1}
                          max={100}
                          step={1}
                          value={[conversionOptions.imageQuality || 85]}
                          onValueChange={(vals) => setConversionOptions({ ...conversionOptions, imageQuality: vals[0] })}
                          disabled={isConverting}
                        />
                      </div>

                      {/* Width */}
                      <div>
                        <Label className="text-xs mb-1.5">Width (px)</Label>
                        <Input
                          type="number"
                          value={conversionOptions.imageWidth || ''}
                          onChange={(e) => setConversionOptions({ ...conversionOptions, imageWidth: e.target.value ? parseInt(e.target.value) : undefined })}
                          placeholder="Original"
                          disabled={isConverting}
                        />
                        <p className="text-xs text-muted-foreground mt-1">Leave empty to keep original</p>
                      </div>

                      {/* Height */}
                      <div>
                        <Label className="text-xs mb-1.5">Height (px)</Label>
                        <Input
                          type="number"
                          value={conversionOptions.imageHeight || ''}
                          onChange={(e) => setConversionOptions({ ...conversionOptions, imageHeight: e.target.value ? parseInt(e.target.value) : undefined })}
                          placeholder="Original"
                          disabled={isConverting}
                        />
                        <p className="text-xs text-muted-foreground mt-1">Leave empty to maintain aspect ratio</p>
                      </div>
                    </div>
                  )}
                </>
              )}

              {/* Convert button */}
              <Button
                onClick={handleConvert}
                disabled={isConvertDisabled}
                className="w-full"
              >
                {isConverting
                  ? 'Converting...'
                  : `Convert ${selectedFiles.length} File${selectedFiles.length > 1 ? 's' : ''}`}
              </Button>
              <Button onClick={handleReset} variant="outline" className="w-full">
                Reset
              </Button>
            </CardContent>
          </Card>
        )}
      </div>

      {/* Right Column: Results */}
      <div className="space-y-6">
        {/* Download All Button */}
        {completedCount > 0 && (
          <Card>
            <CardContent>
              <Button
                onClick={handleDownloadAll}
                className="w-full"
              >
                Download All ({completedCount} file{completedCount > 1 ? 's' : ''})
                {completedCount > 1 && ' as ZIP'}
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Conversion previews */}
        {conversionJobs.length > 0 && (
          <div className="space-y-4">
            {conversionJobs.map((job) => (
              <ConversionPreview
                key={job.id}
                job={job}
                onRetry={() => handleRetry(job.id)}
              />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
