"use client";

import React, { useState, useEffect } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Button } from "@/shared/common/ui/button";
import {
  FileText,
  ImageIcon,
  FileIcon,
  VideoIcon,
  DownloadIcon,
  XIcon,
  Loader2,
} from "lucide-react";
import { cn } from "@/shared/lib/utils";
import { useToast } from "@/shared/common/ui/use-toast";

type FileType = "image" | "pdf" | "video" | "other";

interface FilePreviewProps {
  file: File | string; // Can accept File object or URL string
  type?: FileType; // Optional type hint
  className?: string;
  onRemove?: () => void;
  showDownload?: boolean;
}

export const FilePreview = ({
  file,
  type,
  className,
  onRemove,
  showDownload = true,
}: FilePreviewProps) => {
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [detectedType, setDetectedType] = useState<FileType>("other");
  const { toast } = useToast();

  useEffect(() => {
    const determineFileType = (): FileType => {
      if (type) return type;

      if (typeof file === "string") {
        const extension = file.split(".").pop()?.toLowerCase();
        if (["jpg", "jpeg", "png", "gif", "webp"].includes(extension || "")) {
          return "image";
        }
        if (extension === "pdf") return "pdf";
        if (["mp4", "webm", "ogg"].includes(extension || "")) return "video";
        return "other";
      }

      if (file.type.startsWith("image/")) return "image";
      if (file.type === "application/pdf") return "pdf";
      if (file.type.startsWith("video/")) return "video";
      return "other";
    };

    const generatePreview = async () => {
      setIsLoading(true);
      setDetectedType(determineFileType());

      try {
        if (typeof file === "string") {
          setPreviewUrl(file);
        } else {
          const url = URL.createObjectURL(file);
          setPreviewUrl(url);
        }
      } catch (error) {
        console.error("Error generating preview:", error);
        toast({
          title: "Error",
          description: "Could not generate file preview",
          variant: "destructive",
        });
      } finally {
        setIsLoading(false);
      }
    };

    generatePreview();

    return () => {
      if (previewUrl && typeof file !== "string") {
        URL.revokeObjectURL(previewUrl);
      }
    };
  }, [file, type]);

  const handleDownload = () => {
    if (!previewUrl) return;

    const link = document.createElement("a");
    link.href = previewUrl;
    link.download = typeof file === "string" ? "download" : file.name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const renderPreview = () => {
    if (isLoading) {
      return (
        <div className="flex items-center justify-center h-full">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      );
    }

    switch (detectedType) {
      case "image":
        return (
          <img
            src={previewUrl || ""}
            alt="Preview"
            className="object-contain w-full h-full"
            onLoad={() => setIsLoading(false)}
          />
        );
      case "pdf":
        return (
          <div className="flex flex-col items-center justify-center h-full p-4">
            <FileText className="h-16 w-16 text-red-500 dark:text-red-400" />
            <span className="mt-2 text-sm font-medium truncate text-foreground">
              {typeof file === "string" ? "PDF Document" : file.name}
            </span>
          </div>
        );
      case "video":
        return (
          <video
            controls
            className="w-full h-full"
            onLoadedData={() => setIsLoading(false)}>
            <source src={previewUrl || ""} type="video/mp4" />
            Your browser does not support the video tag.
          </video>
        );
      default:
        return (
          <div className="flex flex-col items-center justify-center h-full p-4">
            <FileIcon className="h-16 w-16 text-gray-400 dark:text-gray-500" />
            <span className="mt-2 text-sm font-medium truncate text-foreground">
              {typeof file === "string" ? "File" : file.name}
            </span>
          </div>
        );
    }
  };

  return (
    <>
      <div
        className={cn(
          "relative border rounded-md overflow-hidden bg-gray-50 dark:bg-gray-800 dark:border-gray-700 w-full h-40",
          className
        )}>
        {renderPreview()}

        <div className="absolute top-2 right-2 flex gap-2">
          {onRemove && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 bg-background/80 hover:bg-background"
              onClick={(e) => {
                e.stopPropagation();
                onRemove();
              }}>
              <XIcon className="h-4 w-4" />
            </Button>
          )}
          {showDownload && previewUrl && (
            <Button
              variant="ghost"
              size="icon"
              className="h-8 w-8 bg-background/80 hover:bg-background"
              onClick={(e) => {
                e.stopPropagation();
                handleDownload();
              }}>
              <DownloadIcon className="h-4 w-4" />
            </Button>
          )}
        </div>

        <Button
          variant="ghost"
          className="absolute inset-0 w-full h-full opacity-0 hover:opacity-100 hover:bg-background/20 dark:hover:bg-background/40"
          onClick={() => setIsDialogOpen(true)}>
          <span className="sr-only">View fullscreen</span>
        </Button>
      </div>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-[90vw] max-h-[90vh]">
          <DialogHeader>
            <DialogTitle>
              {typeof file === "string" ? "File Preview" : file.name}
            </DialogTitle>
          </DialogHeader>
          <div className="relative h-[70vh]">
            {detectedType === "image" && (
              <img
                src={previewUrl || ""}
                alt="Fullscreen preview"
                className="object-contain w-full h-full"
              />
            )}
            {detectedType === "pdf" && (
              <iframe
                src={previewUrl || ""}
                className="w-full h-full"
                title="PDF Preview"
              />
            )}
            {detectedType === "video" && (
              <video controls autoPlay className="w-full h-full">
                <source src={previewUrl || ""} type="video/mp4" />
              </video>
            )}
            {detectedType === "other" && (
              <div className="flex items-center justify-center h-full">
                <FileIcon className="h-16 w-16 text-gray-400 dark:text-gray-500" />
              </div>
            )}
          </div>
          <div className="flex justify-end gap-2">
            {showDownload && (
              <Button onClick={handleDownload} variant="outline">
                <DownloadIcon className="mr-2 h-4 w-4" />
                Download
              </Button>
            )}
            <Button onClick={() => setIsDialogOpen(false)}>Close</Button>
          </div>
        </DialogContent>
      </Dialog>
    </>
  );
};
