"use client";

import { useState, useCallback } from "react";
import { motion } from "framer-motion";
import { Image as ImageIcon, Zap } from "lucide-react";
import { FileUploader } from "@/components/tools/FileUploader";
import { ProgressBar } from "@/components/tools/ProgressBar";
import { ResultPreview } from "@/components/tools/ResultPreview";
import { ConfigPanel, type ConfigOption } from "@/components/tools/ConfigPanel";
import { Button } from "@/components/ui/button";
import { useUploadStore } from "@/store/uploadStore";
import { generateId } from "@/lib/utils";
import type { UploadedFile, ProcessedFile, ImageCompressConfig } from "@/types";

const imageAccept = {
  "image/*": [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp"],
};

const defaultConfig: ImageCompressConfig = {
  quality: 80,
  format: "original",
};

const configOptions: ConfigOption[] = [
  {
    id: "quality",
    type: "slider",
    label: "Compression Quality",
    description: "Lower quality = smaller file size",
    value: defaultConfig.quality,
    min: 1,
    max: 100,
    step: 1,
    suffix: "%",
    icon: <Zap className="h-4 w-4" />,
  },
  {
    id: "format",
    type: "select",
    label: "Output Format",
    description: "Convert to a different format (optional)",
    value: defaultConfig.format,
    options: [
      { label: "Original", value: "original" },
      { label: "JPEG", value: "jpeg" },
      { label: "PNG", value: "png" },
      { label: "WebP", value: "webp" },
    ],
  },
];

export default function ImageCompressPage() {
  const { files, addFile, removeFile, clearFiles, processingStatus, setProcessingStatus } =
    useUploadStore();

  const [config, setConfig] = useState<ImageCompressConfig>(defaultConfig);
  const [processedFiles, setProcessedFiles] = useState<ProcessedFile[]>([]);

  const handleFilesDrop = useCallback(
    (acceptedFiles: File[]) => {
      const newFiles: UploadedFile[] = acceptedFiles.map((file) => ({
        id: generateId(),
        file,
        name: file.name,
        size: file.size,
        type: file.type,
        uploadedAt: new Date(),
      }));

      newFiles.forEach((file) => addFile(file));
    },
    [addFile]
  );

  const handleConfigChange = (id: string, value: any) => {
    setConfig((prev) => ({ ...prev, [id]: value }));
  };

  const handleResetConfig = () => {
    setConfig(defaultConfig);
  };

  const handleProcess = async () => {
    if (files.length === 0) return;

    setProcessingStatus({
      status: "uploading",
      progress: 0,
      message: "Uploading images...",
    });

    try {
      // Simulate upload
      for (let i = 0; i <= 100; i += 10) {
        await new Promise((resolve) => setTimeout(resolve, 50));
        setProcessingStatus({
          status: "uploading",
          progress: i,
          message: `Uploading... ${i}%`,
        });
      }

      setProcessingStatus({
        status: "processing",
        progress: 0,
        message: "Compressing images...",
      });

      // Simulate processing
      for (let i = 0; i <= 100; i += 5) {
        await new Promise((resolve) => setTimeout(resolve, 100));
        setProcessingStatus({
          status: "processing",
          progress: i,
          message: `Compressing... ${i}%`,
        });
      }

      // Simulate completion
      const results: ProcessedFile[] = files.map((file) => ({
        id: generateId(),
        originalFile: file,
        processedUrl: "#",
        metadata: {
          format: config.format === "original" ? file.file.type.split("/")[1] : config.format,
          quality: config.quality,
          compressionRatio: Math.floor(Math.random() * 30) + 40, // Simulated 40-70%
        },
        createdAt: new Date(),
      }));

      setProcessedFiles(results);
      clearFiles();

      setProcessingStatus({
        status: "completed",
        progress: 100,
        message: "Compression complete!",
      });
    } catch (error) {
      setProcessingStatus({
        status: "failed",
        progress: 0,
        message: "Compression failed",
        error: error instanceof Error ? error.message : "Unknown error",
      });
    }
  };

  const handleDownload = (fileId: string) => {
    console.log("Downloading file:", fileId);
  };

  const canProcess = files.length > 0 && processingStatus.status !== "processing";

  return (
    <div className="p-6">
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <div className="mb-8">
          <div className="flex items-center gap-3">
            <div className="flex h-12 w-12 items-center justify-center rounded-lg bg-primary/10">
              <ImageIcon className="h-6 w-6 text-primary" />
            </div>
            <div>
              <h1 className="text-3xl font-bold">Image Compression</h1>
              <p className="text-muted-foreground">
                Optimize images for web and mobile without quality loss
              </p>
            </div>
          </div>
        </div>

        <div className="grid gap-6 lg:grid-cols-2">
          <div className="space-y-6">
            <FileUploader
              files={files}
              onFilesDrop={handleFilesDrop}
              onRemoveFile={removeFile}
              accept={imageAccept}
              maxSize={50 * 1024 * 1024} // 50MB
              maxFiles={20}
              disabled={processingStatus.status === "processing"}
            />

            <ConfigPanel
              title="Compression Settings"
              description="Configure compression options"
              options={configOptions.map((opt) => ({
                ...opt,
                value: config[opt.id as keyof ImageCompressConfig],
              }))}
              onChange={handleConfigChange}
              onReset={handleResetConfig}
            />

            {canProcess && (
              <Button onClick={handleProcess} size="lg" className="w-full">
                <Zap className="mr-2 h-4 w-4" />
                Compress Images
              </Button>
            )}
          </div>

          <div className="space-y-6">
            {processingStatus.status !== "idle" && (
              <ProgressBar progress={processingStatus} />
            )}

            {processedFiles.length > 0 && (
              <ResultPreview results={processedFiles} onDownload={handleDownload} />
            )}

            <div className="rounded-lg border border-border/40 bg-card/50 p-6">
              <h3 className="mb-3 font-semibold">Features</h3>
              <ul className="space-y-2 text-sm text-muted-foreground">
                <li>• Batch processing - compress multiple images at once</li>
                <li>• Smart compression - maintains visual quality</li>
                <li>• Format conversion - PNG to JPEG, WebP, and more</li>
                <li>• Up to 80% size reduction without quality loss</li>
              </ul>
            </div>
          </div>
        </div>
      </motion.div>
    </div>
  );
}
