

import { useState, useCallback } from 'react';
import { useConverter } from '@/hooks/use-converter';
import type { SupportedFormat } from '@/core/types';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Download,
  Trash2,
  PlayCircle,
  Loader2,
  Sparkles,
} from 'lucide-react';
import DropZone from '@/components/drop-zone';
import FormatSelector from '@/components/format-selector';
import QueueItemRow from '@/components/queue-item-row';

export function FileProcessor() {
  const {
    queue,
    isProcessing,
    addFile,
    removeItem,
    processAll,
    clearCompleted,
    downloadItem,
    downloadAll,
    getOutputFormats,
  } = useConverter();

  // Track files being staged (not yet added to queue)
  const [stagedFiles, setStagedFiles] = useState<
    Array<{ file: File; targetFormat: SupportedFormat | null }>
  >([]);

  const handleFilesAdded = useCallback(
    (files: File[]) => {
      const newStaged = files.map((file) => {
        const formats = getOutputFormats(file);
        return {
          file,
          targetFormat: formats[0] || null,
        };
      });
      setStagedFiles((prev) => [...prev, ...newStaged]);
    },
    [getOutputFormats]
  );

  const handleAddToQueue = useCallback(() => {
    stagedFiles.forEach(({ file, targetFormat }) => {
      if (targetFormat) {
        addFile(file, targetFormat);
      }
    });
    setStagedFiles([]);
  }, [stagedFiles, addFile]);

  const handleRemoveStaged = useCallback((index: number) => {
    setStagedFiles((prev) => prev.filter((_, i) => i !== index));
  }, []);

  const handleFormatChange = useCallback((index: number, format: SupportedFormat) => {
    setStagedFiles((prev) =>
      prev.map((item, i) =>
        i === index ? { ...item, targetFormat: format } : item
      )
    );
  }, []);

  const hasCompleted = queue.some((item) => item.status === 'complete');
  const hasPending = queue.some((item) => item.status === 'pending');

  return (
    <div className="w-full max-w-3xl mx-auto space-y-6">
      {/* Header */}
      <div className="text-center space-y-2">
        <h1 className="text-4xl font-bold flex items-center justify-center gap-3">
          <Sparkles className="w-8 h-8 text-primary" />
          K-Convert
        </h1>
        <p className="text-muted-foreground">
          Privacy-first file conversion. Everything happens in your browser.
        </p>
      </div>

      {/* Drop Zone */}
      <Card>
        <CardContent className="p-6">
          <DropZone onFilesAdded={handleFilesAdded} disabled={isProcessing} />
        </CardContent>
      </Card>

      {/* Staged Files */}
      {stagedFiles.length > 0 && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg">Select output formats</CardTitle>
            <CardDescription>
              Choose the format for each file before converting
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-3">
            {stagedFiles.map((item, index) => (
              <div
                key={`${item.file.name}-${index}`}
                className="flex items-center gap-3 p-3 rounded-lg bg-muted/50"
              >
                <div className="flex-1 truncate font-medium">
                  {item.file.name}
                </div>
                <FormatSelector
                  file={item.file}
                  selectedFormat={item.targetFormat}
                  onFormatChange={(fmt) => handleFormatChange(index, fmt)}
                />
                <Button
                  size="icon"
                  variant="ghost"
                  onClick={() => handleRemoveStaged(index)}
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            ))}
            <Button onClick={handleAddToQueue} className="w-full mt-4">
              Add to Queue
            </Button>
          </CardContent>
        </Card>
      )}

      {/* Queue */}
      {queue.length > 0 && (
        <Card>
          <CardHeader className="pb-3">
            <div className="flex items-center justify-between">
              <CardTitle className="text-lg">Conversion Queue</CardTitle>
              <div className="flex gap-2">
                {hasCompleted && (
                  <>
                    <Button
                      size="sm"
                      variant="outline"
                      onClick={downloadAll}
                      className="gap-1"
                    >
                      <Download className="w-4 h-4" /> Download All
                    </Button>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={clearCompleted}
                    >
                      Clear Done
                    </Button>
                  </>
                )}
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <ScrollArea className="max-h-[400px]">
              <div className="space-y-3">
                {queue.map((item) => (
                  <QueueItemRow
                    key={item.id}
                    item={item}
                    onDownload={() => downloadItem(item)}
                    onRemove={() => removeItem(item.id)}
                  />
                ))}
              </div>
            </ScrollArea>

            {hasPending && (
              <Button
                onClick={processAll}
                disabled={isProcessing}
                className="w-full mt-4 gap-2"
                size="lg"
              >
                {isProcessing ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" /> Converting...
                  </>
                ) : (
                  <>
                    <PlayCircle className="w-4 h-4" /> Convert All
                  </>
                )}
              </Button>
            )}
          </CardContent>
        </Card>
      )}
    </div>
  );
}
