"use client";

import React, { useState } from "react";
import {
  MdDescription,
  MdImage,
  MdDownload,
  MdOpenInNew,
} from "react-icons/md";
import { FiRotateCcw, FiX } from "react-icons/fi";

interface FileViewerModalProps {
  isOpen: boolean;
  onClose: () => void;
  file: {
    name: string;
    type?: string;
    webViewLink?: string;
    webContentLink?: string;
    driveFileId: string;
  };
}

const FileViewerModal: React.FC<FileViewerModalProps> = ({
  isOpen,
  onClose,
  file,
}) => {
  const [iframeLoadError, setIframeLoadError] = useState(false);

  if (!isOpen) return null;

  const getFileExtension = (filename: string) => {
    return filename.toLowerCase().split(".").pop() || "";
  };

  const getFileType = () => {
    const extension = getFileExtension(file.name);

    if (file.type) {
      return file.type;
    }

    // Fallback to extension-based detection
    if (["jpg", "jpeg", "png", "gif", "webp"].includes(extension)) {
      return `image/${extension === "jpg" ? "jpeg" : extension}`;
    } else if (extension === "pdf") {
      return "application/pdf";
    }

    return "unknown";
  };

  const fileType = getFileType();
  const isImage = fileType.startsWith("image/");
  const isPdf = fileType === "application/pdf";
  const extension = getFileExtension(file.name);

  const renderFileContent = () => {
    // Use iframe for all file types - Google Drive's universal viewer
    const viewerUrl = `https://drive.google.com/file/d/${file.driveFileId}/preview`;

    if (!iframeLoadError) {
      return (
        <div className="w-full h-[70vh] sm:h-[60vh]">
          <iframe
            src={viewerUrl}
            className="w-full h-full border-0 rounded-lg"
            title={file.name}
            onLoad={(e) => {
              setIframeLoadError(false);
            }}
            onError={() => {
              setIframeLoadError(true);
            }}
          />
        </div>
      );
    } else {
      // Fallback content when iframe fails
      return (
        <div className="flex flex-col items-center justify-center py-8 sm:py-12 text-center">
          <MdDescription className="h-12 w-12 sm:h-16 sm:w-16 text-gray-400 mb-4" />
          <h3 className="text-base sm:text-lg font-semibold text-gray-700 mb-2 px-4">
            {file.name}
          </h3>
          <p className="text-gray-500 mb-6 px-4">
            Preview failed to load for this file
          </p>
          <div className="flex flex-col sm:flex-row gap-3 sm:gap-4 px-4">
            <button
              onClick={() => {
                setIframeLoadError(false);
              }}
              className="bg-gray-500 text-white px-4 py-2 rounded-lg hover:bg-gray-600 flex items-center justify-center gap-2 text-sm touch-manipulation"
            >
              <FiRotateCcw size={16} />
              Retry Preview
            </button>
            {file.webViewLink && (
              <a
                href={file.webViewLink}
                target="_blank"
                rel="noopener noreferrer"
                className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 flex items-center justify-center gap-2 text-sm touch-manipulation"
              >
                <MdOpenInNew size={16} />
                Open in Google Drive
              </a>
            )}
            {file.webContentLink && (
              <a
                href={file.webContentLink}
                target="_blank"
                rel="noopener noreferrer"
                className="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 flex items-center justify-center gap-2 text-sm touch-manipulation"
              >
                <MdDownload size={16} />
                Download
              </a>
            )}
          </div>
        </div>
      );
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-auto bg-black bg-opacity-50 flex items-center justify-center p-2 sm:p-4">
      <div className="bg-white rounded-lg shadow-xl max-w-4xl w-full max-h-[95vh] sm:max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="border-b border-gray-200 bg-white rounded-t-lg flex-shrink-0">
          {/* Desktop Header */}
          <div className="hidden sm:flex justify-between items-center p-4">
            <div className="flex items-center gap-3">
              {isImage ? (
                <MdImage className="h-6 w-6 text-blue-500" />
              ) : isPdf ? (
                <MdDescription className="h-6 w-6 text-red-500" />
              ) : (
                <MdDescription className="h-6 w-6 text-gray-500" />
              )}
              <div>
                <h2 className="text-lg font-semibold text-gray-800 truncate">
                  {file.name}
                </h2>
                <p className="text-sm text-gray-500">
                  {extension.toUpperCase()} file
                </p>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <button
                onClick={onClose}
                className="text-gray-500 hover:text-gray-700 p-2 rounded-lg hover:bg-gray-100"
                title="Close"
              >
                <FiX size={20} />
              </button>
            </div>
          </div>

          {/* Mobile Header */}
          <div className="sm:hidden p-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-3 flex-grow min-w-0">
                {isImage ? (
                  <MdImage className="h-5 w-5 text-blue-500 flex-shrink-0" />
                ) : isPdf ? (
                  <MdDescription className="h-5 w-5 text-red-500 flex-shrink-0" />
                ) : (
                  <MdDescription className="h-5 w-5 text-gray-500 flex-shrink-0" />
                )}
                <div className="flex-grow min-w-0">
                  <h2 className="text-base font-semibold text-gray-800 truncate">
                    {file.name}
                  </h2>
                  <p className="text-xs text-gray-500">
                    {extension.toUpperCase()} file
                  </p>
                </div>
              </div>
              <button
                onClick={onClose}
                className="text-gray-500 hover:text-gray-700 p-2 rounded-lg hover:bg-gray-100 flex-shrink-0"
                title="Close"
              >
                <FiX size={18} />
              </button>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="flex-grow overflow-hidden p-2 sm:p-4">
          {renderFileContent()}
        </div>

        {/* Footer */}
        <div className="border-t border-gray-200 bg-gray-50 flex-shrink-0">
          {/* Desktop Footer */}
          <div className="hidden sm:flex justify-between items-center p-4">
            <div className="text-sm text-gray-600 flex items-center">
              {iframeLoadError ? "Preview failed" : "File preview"}
            </div>
            <div className="flex gap-4 items-center">
              {file.webContentLink && (
                <a
                  href={file.webContentLink}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-blue-600 hover:text-blue-800 text-sm font-medium flex items-center gap-2"
                >
                  <MdDownload size={16} />
                  Download
                </a>
              )}
              <button
                onClick={onClose}
                className="bg-gray-300 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-400 text-sm font-medium flex items-center"
              >
                Close
              </button>
            </div>
          </div>

          {/* Mobile Footer */}
          <div className="sm:hidden p-4">
            <div className="flex flex-col gap-3">
              <div className="text-xs text-gray-600 text-center">
                {iframeLoadError ? "Preview failed" : "File preview"}
              </div>
              <div className="flex flex-col gap-2">
                {file.webContentLink && (
                  <a
                    href={file.webContentLink}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="bg-blue-500 text-white py-3 px-4 rounded-lg hover:bg-blue-600 text-sm font-medium flex items-center justify-center gap-2 touch-manipulation"
                  >
                    <MdDownload size={18} />
                    Download File
                  </a>
                )}
                <button
                  onClick={onClose}
                  className="bg-gray-300 text-gray-700 py-3 px-4 rounded-lg hover:bg-gray-400 text-sm font-medium flex items-center justify-center touch-manipulation"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default FileViewerModal;
