'use client';

import React, { useState, useRef, useEffect } from 'react';
import { createPortal } from 'react-dom';
import Link from 'next/link';
import { useSearchParams } from 'next/navigation';
import { CatalogRecord } from '@/types/catalog';
import { MetaCatalogService } from '@/lib/meta/catalog-service';

interface CatalogActionMenuProps {
  catalog: CatalogRecord;
  onSyncNow: (id: string) => Promise<void>;
  onDelete: (id: string) => Promise<void>;
  shop?: string;
}

export function CatalogActionMenu({
  catalog,
  onSyncNow,
  onDelete,
  shop,
}: CatalogActionMenuProps) {
  const searchParams = useSearchParams();
  const currentShop = shop || searchParams?.get('shop') || searchParams?.get('shopify_domain') || '';
  const [isOpen, setIsOpen] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isSyncing, setIsSyncing] = useState(false);
  const [mounted, setMounted] = useState(false);
  const [menuPos, setMenuPos] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
  const buttonRef = useRef<HTMLButtonElement>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    setMounted(true);
  }, []);

  const updatePosition = () => {
    if (!buttonRef.current) return;
    const rect = buttonRef.current.getBoundingClientRect();
    const dropdownWidth = 192;
    const dropdownHeight = 160;

    // Calculate left: align to button right edge, bounded within viewport
    let left = rect.right - dropdownWidth;
    if (left < 8) left = 8;
    if (left + dropdownWidth > window.innerWidth - 8) {
      left = window.innerWidth - dropdownWidth - 8;
    }

    // Calculate top: open downward if space allows, otherwise open upward
    let top = rect.bottom + 6;
    if (rect.bottom + dropdownHeight > window.innerHeight - 10 && rect.top > dropdownHeight) {
      top = rect.top - dropdownHeight - 6;
    }

    setMenuPos({ top, left });
  };

  const handleToggle = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (!isOpen) {
      updatePosition();
      setIsOpen(true);
    } else {
      setIsOpen(false);
    }
  };

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

    const handleClickOutside = (e: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(e.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(e.target as Node)
      ) {
        setIsOpen(false);
      }
    };

    const handleScrollOrResize = () => {
      setIsOpen(false);
    };

    document.addEventListener('mousedown', handleClickOutside);
    window.addEventListener('scroll', handleScrollOrResize, true);
    window.addEventListener('resize', handleScrollOrResize);

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      window.removeEventListener('scroll', handleScrollOrResize, true);
      window.removeEventListener('resize', handleScrollOrResize);
    };
  }, [isOpen]);

  const handleSyncClick = async (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsOpen(false);
    setIsSyncing(true);
    try {
      await onSyncNow(catalog.id);
    } finally {
      setIsSyncing(false);
    }
  };

  const handleDeleteClick = async (e: React.MouseEvent) => {
    e.stopPropagation();
    setIsOpen(false);
    if (confirm(`Are you sure you want to delete catalog "${catalog.name}"? This action cannot be undone.`)) {
      setIsDeleting(true);
      try {
        await onDelete(catalog.id);
      } finally {
        setIsDeleting(false);
      }
    }
  };

  const fbUrl = catalog.fb_catalog_url || MetaCatalogService.getCommerceManagerUrl(
    catalog.fb_catalog_id,
    catalog.fb_business_id
  );

  return (
    <>
      <button
        ref={buttonRef}
        type="button"
        onClick={handleToggle}
        disabled={isSyncing || isDeleting}
        className="p-1.5 text-slate-400 hover:text-slate-700 rounded-lg hover:bg-slate-100 transition disabled:opacity-40"
        title="Actions"
      >
        <i className="fa-solid fa-ellipsis text-base" />
      </button>

      {isOpen && mounted && typeof document !== 'undefined' && createPortal(
        <div
          ref={dropdownRef}
          style={{
            position: 'fixed',
            top: `${menuPos.top}px`,
            left: `${menuPos.left}px`,
            zIndex: 99999,
          }}
          className="w-48 rounded-2xl shadow-2xl bg-white border border-slate-200 ring-1 ring-black/5 py-1.5 focus:outline-none animate-in fade-in-50 zoom-in-95 duration-100"
          onClick={e => e.stopPropagation()}
        >
          <Link
            href={currentShop ? `/catalog/edit/${catalog.id}?shop=${encodeURIComponent(currentShop)}` : `/catalog/edit/${catalog.id}`}
            onClick={() => setIsOpen(false)}
            className="flex items-center gap-2.5 px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition"
          >
            <i className="fa-solid fa-pen-to-square text-xs text-slate-400 w-3.5 text-center" />
            <span>Edit settings</span>
          </Link>

          <button
            type="button"
            onClick={handleSyncClick}
            className="w-full text-left flex items-center gap-2.5 px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition"
          >
            <i className="fa-solid fa-arrows-rotate text-xs text-theme w-3.5 text-center" />
            <span>Sync now</span>
          </button>

          <a
            href={fbUrl}
            target="_blank"
            rel="noreferrer"
            onClick={() => setIsOpen(false)}
            className="flex items-center gap-2.5 px-4 py-2 text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition"
          >
            <i className="fa-solid fa-arrow-up-right-from-square text-xs text-theme w-3.5 text-center" />
            <span>View in Facebook</span>
          </a>

          <div className="h-px bg-slate-100 my-1"></div>

          <button
            type="button"
            onClick={handleDeleteClick}
            className="w-full text-left flex items-center gap-2.5 px-4 py-2 text-xs font-semibold text-rose-600 hover:bg-rose-50 transition"
          >
            <i className="fa-regular fa-trash-can text-xs w-3.5 text-center" />
            <span>Delete catalog</span>
          </button>
        </div>,
        document.body
      )}
    </>
  );
}
