import { Popover, PopoverButton, PopoverPanel } from "@headlessui/react";
import { CloseCircle, Document, Link2, More } from "iconsax-react";
import { useEffect, useState, type FC } from "react";
import { createPortal } from "react-dom";
import { timeAgo } from "../../../../../config/func";
import { isImageAttachment } from "./isImageAttachment";

type Props = {
  title: string;
  createdAt?: string;
  type: "file" | "link";
  url?: string;
  onEdit: () => void;
  onDelete: () => void;
};

const AttachmentItem: FC<Props> = ({ title, createdAt, type, url, onEdit, onDelete }) => {
  const [isPreviewOpen, setIsPreviewOpen] = useState(false);
  const isImage = type === "file" && isImageAttachment(url);

  useEffect(() => {
    if (!isPreviewOpen) return;

    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setIsPreviewOpen(false);
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [isPreviewOpen]);

  return (
    <>
      <div className="flex items-center justify-between gap-2">
        <div className="flex items-center gap-2 flex-1 min-w-0">
          {isImage && url ? (
            <button
              type="button"
              onClick={() => setIsPreviewOpen(true)}
              className="shrink-0 size-14 rounded-[10px] overflow-hidden bg-white outline-none"
            >
              <img src={url} alt={title} className="size-full object-cover" />
            </button>
          ) : (
            <div className="shrink-0 size-9 bg-white rounded-[10px] flex items-center justify-center">
              {type === "file" ? <Document size={20} color="#292D32" /> : <Link2 size={20} color="#292D32" />}
            </div>
          )}

          <div className="min-w-0">
            {isImage && url ? (
              <button
                type="button"
                onClick={() => setIsPreviewOpen(true)}
                className="text-xs font-bold text-[#0047FF] underline truncate block max-w-full text-right outline-none"
              >
                {title}
              </button>
            ) : url ? (
              <a href={url} target="_blank" rel="noopener noreferrer" className="text-xs font-bold text-[#0047FF] underline truncate block">
                {title}
              </a>
            ) : (
              <div className="text-xs font-bold truncate">{title}</div>
            )}
            {createdAt && <div className="text-[11px] mt-0.5">{timeAgo(createdAt)}</div>}
          </div>
        </div>

        <Popover className="relative shrink-0">
          <PopoverButton className="size-7 bg-white/60 rounded-[8px] flex items-center justify-center outline-none">
            <More size={18} color="#292D32" />
          </PopoverButton>

          <PopoverPanel anchor="bottom end" className="z-[80] mt-1 rounded-[10px] bg-white shadow-md text-right p-3">
            {({ close }) => (
              <>
                <button
                  type="button"
                  onClick={() => {
                    onEdit();
                    close();
                  }}
                  className="w-full text-sm text-right"
                >
                  ویرایش
                </button>

                <button
                  type="button"
                  onClick={() => {
                    onDelete();
                    close();
                  }}
                  className="w-full mt-3 text-sm text-right text-[#FF0000]"
                >
                  پاک کردن
                </button>
              </>
            )}
          </PopoverPanel>
        </Popover>
      </div>

      {isPreviewOpen &&
        url &&
        createPortal(
          <div className="fixed inset-0 z-[100] flex items-center justify-center p-4" role="dialog" aria-modal="true">
            <button
              type="button"
              aria-label="بستن"
              className="absolute inset-0 bg-black/70 outline-none"
              onClick={() => setIsPreviewOpen(false)}
            />

            <div className="relative z-10 max-w-[90vw] max-h-[90vh]">
              <button
                type="button"
                aria-label="بستن"
                onClick={() => setIsPreviewOpen(false)}
                className="absolute -top-3 -left-3 size-9 rounded-full bg-white flex items-center justify-center shadow outline-none"
              >
                <CloseCircle size={22} color="#292D32" />
              </button>

              <img src={url} alt={title} className="max-w-[90vw] max-h-[90vh] rounded-2xl object-contain bg-white" />
            </div>
          </div>,
          document.body,
        )}
    </>
  );
};

export default AttachmentItem;
