"use client";

import { useEffect, useState } from "react";
import { getFileUrl, FileItem } from "@/lib/api";
import { X, Download, FileText, Image as ImageIcon, FileCode, File } from "lucide-react";

interface FilePreviewProps {
  file: FileItem;
  onClose?: () => void;
}

function getFileExtension(name: string): string {
  const parts = name.split(".");
  return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
}

function getFileIcon(type: string, ext: string) {
  if (type.startsWith("image/") || ["png", "jpg", "jpeg", "gif", "svg", "webp"].includes(ext)) {
    return <ImageIcon size={48} className="text-slack-blue" />;
  }
  if (type === "application/pdf" || ext === "pdf") {
    return <FileText size={48} className="text-slack-red" />;
  }
  if (["js", "ts", "jsx", "tsx", "py", "go", "java", "c", "cpp", "rb", "rs", "html", "css", "json", "yaml", "yml"].includes(ext)) {
    return <FileCode size={48} className="text-slack-green" />;
  }
  return <File size={48} className="text-gray-400" />;
}

export function FilePreview({ file, onClose }: FilePreviewProps) {
  const [url, setUrl] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const ext = getFileExtension(file.name);
  const isImage = file.type.startsWith("image/") || ["png", "jpg", "jpeg", "gif", "svg", "webp"].includes(ext);
  const isPdf = file.type === "application/pdf" || ext === "pdf";
  const isCode = ["js", "ts", "jsx", "tsx", "py", "go", "java", "c", "cpp", "rb", "rs", "html", "css", "json", "yaml", "yml"].includes(ext);
  const isText = file.type.startsWith("text/") || ext === "txt" || ext === "md";

  useEffect(() => {
    setLoading(true);
    setError("");
    getFileUrl(file.id)
      .then((res) => setUrl(res.url || file.url || null))
      .catch((err) => {
        console.error("Failed to get file URL:", err);
        setError("Failed to load file preview");
      })
      .finally(() => setLoading(false));
  }, [file.id, file.url]);

  const formatSize = (bytes: number | undefined) => {
    if (!bytes) return "";
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[90vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200">
          <div className="flex items-center gap-2 min-w-0">
            {getFileIcon(file.type, ext)}
            <div className="min-w-0">
              <h3 className="text-sm font-semibold text-gray-800 truncate">{file.name}</h3>
              <p className="text-xs text-gray-400">
                {formatSize(file.size)}
                {file.uploaded_by_user?.name && ` · ${file.uploaded_by_user.name}`}
                {file.created_at && ` · ${new Date(file.created_at).toLocaleDateString()}`}
              </p>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {url && (
              <a
                href={url}
                download={file.name}
                className="p-2 rounded-md text-gray-500 hover:text-slack-purple hover:bg-gray-100 transition-colors"
                title="Download"
              >
                <Download size={18} />
              </a>
            )}
            {onClose && (
              <button
                onClick={onClose}
                className="p-2 rounded-md text-gray-500 hover:text-slack-red hover:bg-gray-100 transition-colors"
                title="Close"
              >
                <X size={18} />
              </button>
            )}
          </div>
        </div>

        {/* Preview */}
        <div className="flex-1 overflow-auto p-4 flex items-center justify-center">
          {loading ? (
            <div className="text-gray-400 animate-pulse">Loading preview...</div>
          ) : error ? (
            <div className="text-slack-red text-sm">{error}</div>
          ) : !url ? (
            <div className="flex flex-col items-center text-gray-400">
              {getFileIcon(file.type, ext)}
              <p className="text-sm mt-2">Preview not available</p>
            </div>
          ) : isImage ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={url}
              alt={file.name}
              className="max-w-full max-h-[70vh] object-contain rounded"
            />
          ) : isPdf ? (
            <iframe
              src={url}
              title={file.name}
              className="w-full h-[70vh] rounded border border-gray-200"
            />
          ) : (isCode || isText) ? (
            <iframe
              src={url}
              title={file.name}
              className="w-full h-[70vh] rounded border border-gray-200 bg-gray-50"
            />
          ) : (
            <div className="flex flex-col items-center text-gray-400">
              {getFileIcon(file.type, ext)}
              <p className="text-sm mt-2">No preview available for this file type</p>
              <a
                href={url}
                download={file.name}
                className="mt-3 flex items-center gap-1.5 px-3 py-1.5 rounded-md bg-slack-purple text-white text-sm hover:bg-slack-darkpurple transition-colors"
              >
                <Download size={14} />
                Download
              </a>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default FilePreview;