'use client';

import {useState, useRef, useEffect} from 'react';
import {createPortal} from 'react-dom';
import {Button} from '@astryxdesign/core/Button';
import {Icon} from '@astryxdesign/core/Icon';
import {useToast} from '@astryxdesign/core/Toast';
import {ICONS} from '@/shared/utils/icons';
import {exportData, ExportFormat, ExportColumn} from '@/shared/utils/export/exportManager';

export interface DownloadDropdownProps {
  filename: string;
  title: string;
  subtitle?: string;
  columns: ExportColumn[];
  data: Record<string, any>[];
  variant?: 'primary' | 'secondary' | 'ghost';
  size?: 'sm' | 'md';
}

export function DownloadDropdown({
  filename,
  title,
  subtitle,
  columns,
  data,
  variant = 'primary',
  size = 'sm',
}: DownloadDropdownProps) {
  const toast = useToast();
  const [isOpen, setIsOpen] = useState(false);
  const [loadingFormat, setLoadingFormat] = useState<ExportFormat | null>(null);
  const [coords, setCoords] = useState<{top: number; left: number} | null>(null);
  const [mounted, setMounted] = useState(false);
  
  const buttonWrapperRef = useRef<HTMLDivElement>(null);
  const menuRef = useRef<HTMLDivElement>(null);

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

  // Close dropdown on click outside or window/container scroll
  useEffect(() => {
    if (!isOpen) return;

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

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

    window.addEventListener('scroll', handleScroll, {capture: true, passive: true});
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      window.removeEventListener('scroll', handleScroll, {capture: true});
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  const handleToggle = () => {
    if (!isOpen && buttonWrapperRef.current) {
      const rect = buttonWrapperRef.current.getBoundingClientRect();
      const leftPos = Math.max(12, rect.right - 224);
      
      // Smart vertical flip: if space below < 180px, open UPWARDS above button
      const spaceBelow = window.innerHeight - rect.bottom;
      const menuHeight = 168; // 3 items padding height
      let topPos: number;

      if (spaceBelow < menuHeight && rect.top > menuHeight) {
        topPos = rect.top - menuHeight - 6;
      } else {
        topPos = rect.bottom + 6;
      }

      setCoords({top: topPos, left: leftPos});
    }
    setIsOpen((prev) => !prev);
  };

  const handleSelectFormat = async (fmt: ExportFormat) => {
    console.log('[DownloadDropdown] Selected format:', fmt);
    setIsOpen(false);
    setLoadingFormat(fmt);

    try {
      await exportData({
        filename,
        title,
        subtitle,
        columns,
        data,
        format: fmt,
      });

      const label = fmt === 'pdf' ? 'PDF' : fmt === 'excel' ? 'Excel' : 'CSV';
      console.log(`[DownloadDropdown] Success toast for ${label}`);
      toast({
        body: `✓ ${label} downloaded successfully`,
      });
    } catch (err) {
      console.error('[DownloadDropdown] Export failed:', err);
      toast({
        body: '❌ Download failed. Unable to generate file.',
      });
    } finally {
      setLoadingFormat(null);
    }
  };

  const getButtonLabel = () => {
    if (loadingFormat) {
      const fmtName = loadingFormat === 'pdf' ? 'PDF' : loadingFormat === 'excel' ? 'Excel' : 'CSV';
      return `Generating ${fmtName}...`;
    }
    return 'Download';
  };

  return (
    <div className="inline-block text-left">
      <div ref={buttonWrapperRef}>
        <Button
          size={size}
          variant={variant}
          label={getButtonLabel()}
          icon={<Icon icon={ICONS.download} size="sm" />}
          isLoading={loadingFormat !== null}
          isDisabled={loadingFormat !== null}
          onClick={handleToggle}
        />
      </div>

      {isOpen && !loadingFormat && mounted && coords
        ? createPortal(
            <div
              ref={menuRef}
              onMouseDown={(e) => e.stopPropagation()}
              style={{
                position: 'fixed',
                top: `${coords.top}px`,
                left: `${coords.left}px`,
                zIndex: 99999,
              }}
              className="w-56 rounded-xl border border-zinc-700 bg-[#18181b] backdrop-blur-xl shadow-2xl z-[99999] py-1.5 divide-y divide-zinc-800 select-none"
            >
              <button
                type="button"
                className="w-full text-left px-4 py-3 hover:bg-white/10 flex items-center gap-3 transition-colors cursor-pointer"
                onClick={() => handleSelectFormat('pdf')}
              >
                <span className="text-xl">📄</span>
                <div>
                  <div className="font-semibold text-sm text-white">PDF Document</div>
                  <div className="text-xs text-zinc-300">.pdf file format</div>
                </div>
              </button>

              <button
                type="button"
                className="w-full text-left px-4 py-3 hover:bg-white/10 flex items-center gap-3 transition-colors cursor-pointer"
                onClick={() => handleSelectFormat('excel')}
              >
                <span className="text-xl">📊</span>
                <div>
                  <div className="font-semibold text-sm text-white">Excel Spreadsheet</div>
                  <div className="text-xs text-zinc-300">.xlsx file format</div>
                </div>
              </button>

              <button
                type="button"
                className="w-full text-left px-4 py-3 hover:bg-white/10 flex items-center gap-3 transition-colors cursor-pointer"
                onClick={() => handleSelectFormat('csv')}
              >
                <span className="text-xl">📑</span>
                <div>
                  <div className="font-semibold text-sm text-white">CSV Data File</div>
                  <div className="text-xs text-zinc-300">.csv file format</div>
                </div>
              </button>
            </div>,
            document.body
          )
        : null}
    </div>
  );
}
