import React, { useCallback,useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';

import { coworkService } from '../../services/cowork';
import { i18nService } from '../../services/i18n';
import { getCompactFolderName } from '../../utils/path';
import ChevronRightIcon from '../icons/ChevronRightIcon';
import ClockIcon from '../icons/ClockIcon';
import FolderIcon from '../icons/FolderIcon';
import FolderPlusIcon from '../icons/FolderPlusIcon';

// Custom tooltip for folder paths
interface PathTooltipProps {
  path: string;
  anchorRect: DOMRect | null;
  visible: boolean;
}

const PathTooltip: React.FC<PathTooltipProps> = ({ path, anchorRect, visible }) => {
  if (!visible || !anchorRect) return null;

  // Position tooltip above the item, centered
  const style: React.CSSProperties = {
    position: 'fixed',
    top: anchorRect.top - 8,
    left: anchorRect.left + anchorRect.width / 2,
    transform: 'translate(-50%, -100%)',
    maxWidth: '400px',
    zIndex: 10002,
  };

  return (
    <div
      style={style}
      className="px-3.5 py-2.5 text-[13px] leading-relaxed rounded-xl shadow-xl bg-background text-foreground border-border border break-all pointer-events-none"
    >
      {path}
    </div>
  );
};

interface FolderSelectorPopoverProps {
  isOpen: boolean;
  onClose: () => void;
  onSelectFolder: (path: string) => void;
  anchorRef: React.RefObject<HTMLElement>;
  portal?: boolean;
  placement?: 'top' | 'bottom';
}

const POPOVER_WIDTH = 224; // matches w-56
const POPOVER_VIEWPORT_MARGIN = 8;

const FolderSelectorPopover: React.FC<FolderSelectorPopoverProps> = ({
  isOpen,
  onClose,
  onSelectFolder,
  anchorRef,
  portal = false,
  placement = 'top',
}) => {
  const [recentFolders, setRecentFolders] = useState<string[]>([]);
  const [showRecentSubmenu, setShowRecentSubmenu] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [submenuPosition, setSubmenuPosition] = useState({ top: 0, left: 0 });
  const [tooltipState, setTooltipState] = useState<{
    visible: boolean;
    path: string;
    rect: DOMRect | null;
  }>({ visible: false, path: '', rect: null });
  const [portalStyle, setPortalStyle] = useState<React.CSSProperties>({});
  const popoverRef = useRef<HTMLDivElement>(null);
  const submenuRef = useRef<HTMLDivElement>(null);
  const recentFoldersRef = useRef<HTMLDivElement>(null);
  const tooltipTimerRef = useRef<NodeJS.Timeout | null>(null);
  const submenuCloseTimerRef = useRef<NodeJS.Timeout | null>(null);

  const updatePortalPosition = useCallback(() => {
    if (!anchorRef.current) return;
    const rect = anchorRef.current.getBoundingClientRect();
    const left = Math.min(
      Math.max(rect.left, POPOVER_VIEWPORT_MARGIN),
      window.innerWidth - POPOVER_WIDTH - POPOVER_VIEWPORT_MARGIN
    );
    const nextStyle: React.CSSProperties = {
      left,
      position: 'fixed',
      width: POPOVER_WIDTH,
      zIndex: 10000,
    };

    if (placement === 'top') {
      nextStyle.bottom = window.innerHeight - rect.top + 8;
    } else {
      nextStyle.top = rect.bottom + 8;
    }

    setPortalStyle(nextStyle);
  }, [anchorRef, placement]);

  // Cleanup timers on unmount
  useEffect(() => {
    return () => {
      if (tooltipTimerRef.current) {
        clearTimeout(tooltipTimerRef.current);
      }
      if (submenuCloseTimerRef.current) {
        clearTimeout(submenuCloseTimerRef.current);
      }
    };
  }, []);

  // Load recent folders when popover opens
  useLayoutEffect(() => {
    if (isOpen && portal) {
      updatePortalPosition();
    }
  }, [isOpen, portal, updatePortalPosition]);

  useEffect(() => {
    if (isOpen) {
      const loadRecentFolders = async () => {
        setIsLoading(true);
        try {
          const folders = await coworkService.getRecentCwds(10);
          setRecentFolders(folders);
        } catch (error) {
          console.error('Failed to load recent folders:', error);
          setRecentFolders([]);
        } finally {
          setIsLoading(false);
        }
      };
      loadRecentFolders();
    } else {
      setShowRecentSubmenu(false);
      // Clear tooltip and submenu timer when popover closes
      setTooltipState({ visible: false, path: '', rect: null });
      if (tooltipTimerRef.current) {
        clearTimeout(tooltipTimerRef.current);
        tooltipTimerRef.current = null;
      }
      if (submenuCloseTimerRef.current) {
        clearTimeout(submenuCloseTimerRef.current);
        submenuCloseTimerRef.current = null;
      }
    }
  }, [isOpen, portal, updatePortalPosition]);

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

    window.addEventListener('resize', updatePortalPosition);
    window.addEventListener('scroll', updatePortalPosition, true);

    return () => {
      window.removeEventListener('resize', updatePortalPosition);
      window.removeEventListener('scroll', updatePortalPosition, true);
    };
  }, [isOpen, portal, updatePortalPosition]);

  // Handle click outside
  useEffect(() => {
    if (!isOpen) return;

    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Node;
      const isInsidePopover = popoverRef.current?.contains(target);
      const isInsideSubmenu = submenuRef.current?.contains(target);
      const isInsideAnchor = anchorRef.current?.contains(target);

      if (!isInsidePopover && !isInsideSubmenu && !isInsideAnchor) {
        onClose();
      }
    };

    document.addEventListener('mousedown', handleClickOutside, true);
    return () => document.removeEventListener('mousedown', handleClickOutside, true);
  }, [isOpen, onClose, anchorRef]);

  // Handle escape key
  useEffect(() => {
    if (!isOpen) return;

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    document.addEventListener('keydown', handleEscape);
    return () => document.removeEventListener('keydown', handleEscape);
  }, [isOpen, onClose]);

  // Calculate submenu position relative to the Recent Folders button
  useEffect(() => {
    if (showRecentSubmenu && recentFoldersRef.current) {
      const rect = recentFoldersRef.current.getBoundingClientRect();
      setSubmenuPosition({
        top: rect.top,
        left: rect.right + 4, // 4px gap
      });
    }
  }, [showRecentSubmenu]);

  const isWindowsDriveRoot = (dirPath: string): boolean => {
    if (window.electron.platform !== 'win32') return false;
    return /^[a-zA-Z]:[/\\]?$/.test(dirPath.trim());
  };

  const handleAddFolder = async () => {
    onClose();
    try {
      const result = await window.electron.dialog.selectDirectory();
      if (result.success && result.path) {
        if (isWindowsDriveRoot(result.path)) {
          window.dispatchEvent(new CustomEvent('app:showToast', { detail: i18nService.t('folderDriveRootNotAllowed') }));
          return;
        }
        onSelectFolder(result.path);
      }
    } catch (error) {
      console.error('Failed to select directory:', error);
    }
  };

  const handleSelectRecentFolder = (path: string) => {
    if (isWindowsDriveRoot(path)) {
      window.dispatchEvent(new CustomEvent('app:showToast', { detail: i18nService.t('folderDriveRootNotAllowed') }));
      return;
    }
    onSelectFolder(path);
    onClose();
  };

  const handleFolderMouseEnter = useCallback((path: string, event: React.MouseEvent<HTMLButtonElement>) => {
    const rect = event.currentTarget.getBoundingClientRect();
    // Clear any existing timer
    if (tooltipTimerRef.current) {
      clearTimeout(tooltipTimerRef.current);
    }
    // Show tooltip after a short delay
    tooltipTimerRef.current = setTimeout(() => {
      setTooltipState({
        visible: true,
        path: getCompactFolderName(path, 120) || i18nService.t('noFolderSelected'),
        rect,
      });
    }, 300);
  }, []);

  const handleFolderMouseLeave = useCallback(() => {
    if (tooltipTimerRef.current) {
      clearTimeout(tooltipTimerRef.current);
      tooltipTimerRef.current = null;
    }
    setTooltipState({ visible: false, path: '', rect: null });
  }, []);

  const truncatePath = (path: string, maxLength = 40): string => {
    if (!path) return i18nService.t('noFolderSelected');
    return getCompactFolderName(path, maxLength) || i18nService.t('noFolderSelected');
  };

  const handleSubmenuMouseEnter = useCallback(() => {
    if (submenuCloseTimerRef.current) {
      clearTimeout(submenuCloseTimerRef.current);
      submenuCloseTimerRef.current = null;
    }
    setShowRecentSubmenu(true);
  }, []);

  const handleSubmenuMouseLeave = useCallback(() => {
    if (submenuCloseTimerRef.current) {
      clearTimeout(submenuCloseTimerRef.current);
    }
    submenuCloseTimerRef.current = setTimeout(() => {
      setShowRecentSubmenu(false);
      submenuCloseTimerRef.current = null;
    }, 150);
  }, []);

  if (!isOpen) return null;

  const popoverContent = (
    <>
      {/* Main popover */}
      <div
        ref={popoverRef}
        style={portal ? portalStyle : undefined}
        className={`${portal ? '' : 'absolute bottom-full left-0 mb-2'} w-56 rounded-lg border border-border bg-surface shadow-lg z-50`}
      >
        {/* Add Folder option */}
        <button
          onClick={handleAddFolder}
          className="w-full flex items-center gap-3 px-3 py-2.5 text-sm text-foreground hover:bg-surface-raised transition-colors rounded-t-lg"
        >
          <FolderPlusIcon className="h-4 w-4 text-secondary" />
          <span>{i18nService.t('addFolder')}</span>
        </button>

        {/* Recent Folders option */}
        <div
          ref={recentFoldersRef}
          className="relative"
          onMouseEnter={handleSubmenuMouseEnter}
          onMouseLeave={handleSubmenuMouseLeave}
        >
          <button
            className="w-full flex items-center justify-between gap-3 px-3 py-2.5 text-sm text-foreground hover:bg-surface-raised transition-colors rounded-b-lg"
          >
            <div className="flex items-center gap-3">
              <ClockIcon className="h-4 w-4 text-secondary" />
              <span>{i18nService.t('recentFolders')}</span>
            </div>
            <ChevronRightIcon className="h-3 w-3 text-secondary" />
          </button>
        </div>
      </div>

      {/* Recent folders submenu - rendered as a portal-like fixed element */}
      {showRecentSubmenu && (
        <div
          ref={submenuRef}
          className="fixed w-64 max-h-80 overflow-y-auto rounded-lg border border-border bg-surface shadow-lg z-[10001]"
          style={{ top: submenuPosition.top, left: submenuPosition.left }}
          onMouseEnter={handleSubmenuMouseEnter}
          onMouseLeave={handleSubmenuMouseLeave}
        >
          {isLoading ? (
            <div className="px-3 py-2.5 text-sm text-secondary">
              {i18nService.t('loading')}
            </div>
          ) : recentFolders.length === 0 ? (
            <div className="px-3 py-2.5 text-sm text-secondary">
              {i18nService.t('noRecentFolders')}
            </div>
          ) : (
            recentFolders.map((folder, index) => (
              <button
                key={index}
                onClick={() => handleSelectRecentFolder(folder)}
                onMouseEnter={(e) => handleFolderMouseEnter(folder, e)}
                onMouseLeave={handleFolderMouseLeave}
                className="w-full flex items-center gap-2 px-3 py-2 text-sm text-foreground hover:bg-surface-raised transition-colors text-left first:rounded-t-lg last:rounded-b-lg"
              >
                <FolderIcon className="h-4 w-4 flex-shrink-0 text-secondary" />
                <span className="truncate">{truncatePath(folder)}</span>
              </button>
            ))
          )}
        </div>
      )}

      {/* Path tooltip */}
      <PathTooltip
        path={tooltipState.path}
        anchorRect={tooltipState.rect}
        visible={tooltipState.visible}
      />
    </>
  );

  return portal ? createPortal(popoverContent, document.body) : popoverContent;
};

export default FolderSelectorPopover;
