import React, { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  ArrowDownTrayIcon,
  XMarkIcon,
  ArrowPathIcon,
} from "@heroicons/react/24/solid";
import sampleImage from "../../assets/images/no-image.png";

const imageExtensions = [
  ".jpg",
  ".jpeg",
  ".png",
  ".gif",
  ".bmp",
  ".webp",
  ".svg",
];

interface ShowImageProps {
  src?: string;
  size?: number | string;
  className?: string;
  noOpen?: boolean;
}

const ShowImage: React.FC<ShowImageProps> = ({
  src = sampleImage,
  size,
  className,
  noOpen = false,
}) => {
  const [open, setOpen] = useState(false);
  const [rotation, setRotation] = useState(0);

  const handleOpen = () => {
    !noOpen && setOpen(true);
  };
  const handleClose = () => setOpen(false);

  const handleDownload = () => {
    if (!src) return;
    const link = document.createElement("a");
    link.href = src;
    const filename = src.split("/").pop() || "document";
    link.download = filename;
    link.click();
  };

  const handleRotate = () => {
    setRotation((prev) => prev + 90);
  };

  const getFileExtension = () => {
    if (!src) return "";
    const filename = src.split("/").pop() || "";
    const lastDotIndex = filename.lastIndexOf(".");
    if (lastDotIndex === -1) return "";
    return filename.substring(lastDotIndex + 1).toLowerCase();
  };

  const isImage = () => {
    if (!src) return false;
    const ext = getFileExtension();
    return imageExtensions.includes(`.${ext}`);
  };

  if (!src) {
    return <span className="text-gray-400 italic">-</span>;
  }

  if (!isImage()) {
    const ext = getFileExtension();
    const buttonText = ext ? `دانلود سند ${ext}` : "دانلود سند";

    return (
      <button
        onClick={handleDownload}
        className="inline-flex items-center gap-2 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white text-sm font-semibold px-4 py-2 rounded-lg shadow-lg transition-shadow duration-300 focus:outline-none focus:ring-2 focus:ring-blue-400"
        type="button"
      >
        <ArrowDownTrayIcon className="w-5 h-5" />
        {buttonText}
      </button>
    );
  }

  return (
    <>
      <img
        src={src}
        alt="thumbnail"
        onClick={handleOpen}
        className={`${className} cursor-pointer rounded-lg  select-none transition-transform duration-300 ease-in-out hover:scale-105 ${
          size
            ? typeof size === "number"
              ? `w-[${size}px] h-[${size}px]`
              : `w-full h-full`
            : "w-16 h-16"
        }`}
        style={{
          width: typeof size === "number" ? size : undefined,
          height: typeof size === "number" ? size : undefined,
        }}
        draggable={false}
      />

      <AnimatePresence>
        {open && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            transition={{ duration: 0.25 }}
            className="fixed inset-0 z-50 flex items-center justify-center bg-opacity-70 backdrop-blur-sm"
            aria-modal="true"
            role="dialog"
          >
            <motion.div
              initial={{ scale: 0.85, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.85, opacity: 0 }}
              transition={{ duration: 0.2, ease: "easeOut" }}
              className="relative max-w-[90vw] max-h-[90vh] min-w-[40vw] min-h-[40vh] rounded-2xl overflow-hidden bg-white dark:bg-dark-600 shadow-2xl flex flex-col items-center justify-center"
            >
              <img
                src={src}
                alt="full-size"
                style={{ transform: `rotate(${rotation}deg)` }}
                className="max-w-full max-h-[80vh] transition-transform duration-500 ease-in-out select-none"
                draggable={false}
              />

              <div className="absolute top-4 right-4 flex space-x-3">
                <button
                  onClick={handleDownload}
                  title="دانلود تصویر"
                  className="flex items-center cursor-pointer justify-center bg-white bg-opacity-90 hover:bg-opacity-100 p-3 rounded-full shadow-lg transition-shadow duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  type="button"
                >
                  <ArrowDownTrayIcon className="w-6 h-6 text-primary-700" />
                </button>

                <button
                  onClick={handleRotate}
                  title="چرخش تصویر"
                  className="flex items-center cursor-pointer justify-center bg-white bg-opacity-90 hover:bg-opacity-100 p-3 rounded-full shadow-lg transition-shadow duration-200 focus:outline-none focus:ring-2 focus:ring-gray-400"
                  type="button"
                >
                  <ArrowPathIcon className="w-6 h-6 text-primary-700" />
                </button>
              </div>

              <button
                onClick={handleClose}
                className="absolute cursor-pointer top-4 left-4 bg-white bg-opacity-90 hover:bg-opacity-100 p-3 rounded-full shadow-lg transition-shadow duration-200 focus:outline-none focus:ring-2 focus:ring-red-500"
                type="button"
                aria-label="Close"
              >
                <XMarkIcon className="w-6 h-6 text-red-600" />
              </button>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

export default ShowImage;
