import React, { useState, useMemo, useEffect, useRef, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Search, Check, X, Filter } from 'lucide-react';
import { cn } from '../lib/utils';

type FilterType = 'equals' | 'notEquals' | 'contains' | 'startsWith' | 'endsWith' | 'greaterThan' | 'lessThan' | 'between';

interface FilterCondition {
  type: FilterType;
  value: string;
  value2?: string;
}

interface ColumnFilterPopoverProps {
  uniqueValues: string[];
  selectedValues: string[];
  onToggle: (val: string) => void;
  onSelectAll: (vals: string[]) => void;
  onClear: () => void;
  onClose: () => void;
  title?: string;
  className?: string;
  zIndex?: number;
  triggerId?: string;
}

export function ColumnFilterPopover({
  uniqueValues,
  selectedValues,
  onToggle,
  onSelectAll,
  onClear,
  onClose,
  title,
  className,
  zIndex = 50,
  triggerId
}: ColumnFilterPopoverProps) {
  const [search, setSearch] = useState('');
  const [activeTab, setActiveTab] = useState<'values' | 'condition'>('values');
  const [condition, setCondition] = useState<FilterCondition>({ type: 'equals', value: '' });
  const [conditionResult, setConditionResult] = useState<string[]>([]);
  const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);
  const [position, setPosition] = useState({ top: 0, left: 0 });

  const updatePosition = useCallback(() => {
    if (!triggerId) return;
    const trigger = document.getElementById(triggerId);
    if (!trigger) return;

    const rect = trigger.getBoundingClientRect();
    setPosition({
      top: rect.bottom + window.scrollY + 4,
      left: Math.min(rect.left + window.scrollX, window.innerWidth + window.scrollX - 300)
    });
  }, [triggerId]);

  useEffect(() => {
    const container = document.createElement('div');
    container.id = 'filter-portal-' + Math.random().toString(36).substring(2, 9);
    container.style.position = 'absolute';
    container.style.zIndex = '9999';
    container.style.top = '0';
    container.style.left = '0';
    container.style.width = '100%';
    container.style.pointerEvents = 'none';
    document.body.appendChild(container);
    setPortalContainer(container);

    updatePosition();

    // Update on scroll and resize
    window.addEventListener('scroll', updatePosition, true);
    window.addEventListener('resize', updatePosition);

    return () => {
      window.removeEventListener('scroll', updatePosition, true);
      window.removeEventListener('resize', updatePosition);
      if (document.body.contains(container)) {
        document.body.removeChild(container);
      }
    };
  }, [updatePosition]);

  const isDraggingRef = React.useRef(false);
  const dragStartRef = React.useRef<number | null>(null);
  const safeUniqueValues = uniqueValues || [];
  const safeSelectedValues = selectedValues || [];
  const hoveredIndexRef = React.useRef<number | null>(null);
  const selectedValuesRef = React.useRef<string[]>(safeSelectedValues);
  const onSelectAllRef = React.useRef(onSelectAll);
  const filteredValuesRef = React.useRef<string[]>([]);
  const didDragRef = React.useRef(false);
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState<number | null>(null);
  const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
  const [lastClickedIndex, setLastClickedIndex] = useState<number | null>(null);
  const listRef = React.useRef<HTMLDivElement>(null);

  const filteredValues = useMemo(() => {
    return safeUniqueValues.filter(v => 
      String(v || '').toLowerCase().includes(search.toLowerCase())
    );
  }, [safeUniqueValues, search]);

  filteredValuesRef.current = filteredValues;
  selectedValuesRef.current = safeSelectedValues;
  onSelectAllRef.current = onSelectAll;

  const isAllSelected = safeSelectedValues.length === safeUniqueValues.length && safeUniqueValues.length > 0;

  const applyCondition = () => {
    const results: string[] = [];
    const valNum = parseFloat(condition.value);
    const val2Num = condition.value2 ? parseFloat(condition.value2) : 0;

    filteredValues.forEach(v => {
      const strVal = String(v || '');
      const numVal = parseFloat(v);

      let matches = false;

      switch (condition.type) {
        case 'equals':
          matches = strVal.toLowerCase() === condition.value.toLowerCase();
          break;
        case 'notEquals':
          matches = strVal.toLowerCase() !== condition.value.toLowerCase();
          break;
        case 'contains':
          matches = strVal.toLowerCase().includes(condition.value.toLowerCase());
          break;
        case 'startsWith':
          matches = strVal.toLowerCase().startsWith(condition.value.toLowerCase());
          break;
        case 'endsWith':
          matches = strVal.toLowerCase().endsWith(condition.value.toLowerCase());
          break;
        case 'greaterThan':
          matches = !isNaN(numVal) && !isNaN(valNum) && numVal > valNum;
          break;
        case 'lessThan':
          matches = !isNaN(numVal) && !isNaN(valNum) && numVal < valNum;
          break;
        case 'between':
          matches = !isNaN(numVal) && !isNaN(val2Num) && numVal >= valNum && numVal <= val2Num;
          break;
      }

      if (matches) results.push(v);
    });

    setConditionResult(results);
    onSelectAll(results);
    setActiveTab('values');
    onClose();
  };

  const handleMouseDown = (index: number) => {
    isDraggingRef.current = true;
    dragStartRef.current = index;
    hoveredIndexRef.current = index;
    didDragRef.current = false;
    setIsDragging(true);
    setDragStart(index);
    setHoveredIndex(index);
  };

  const handleMouseEnter = (index: number) => {
    if (isDraggingRef.current && dragStartRef.current !== null) {
      hoveredIndexRef.current = index;
      setHoveredIndex(index);
    }
  };

  React.useEffect(() => {
    const handleGlobalMouseUp = () => {
      if (isDraggingRef.current) {
        const start = dragStartRef.current;
        const end = hoveredIndexRef.current;
        
        if (start !== null && end !== null && start !== end) {
          const s = Math.min(start, end);
          const e = Math.max(start, end);
          const itemsToSelect = filteredValuesRef.current.slice(s, e + 1);
          const newSelected = new Set([...selectedValuesRef.current]);
          itemsToSelect.forEach(v => newSelected.add(v));
          onSelectAllRef.current(Array.from(newSelected));
          didDragRef.current = true;
          setTimeout(() => { didDragRef.current = false; }, 100);
        }

        isDraggingRef.current = false;
        dragStartRef.current = null;
        hoveredIndexRef.current = null;
        setIsDragging(false);
        setDragStart(null);
        setHoveredIndex(null);
      }
    };
    document.addEventListener('mouseup', handleGlobalMouseUp);
    return () => document.removeEventListener('mouseup', handleGlobalMouseUp);
  }, []);

  return (
    <div className="fixed inset-0 z-0 pointer-events-none">
      {portalContainer && createPortal(
        <div
          className={cn(
            "absolute w-72 bg-slate-800 border border-slate-700 rounded-lg shadow-2xl p-3 flex flex-col gap-3 animate-in fade-in zoom-in-95 duration-100 pointer-events-auto",
            className
          )}
          style={{ 
            zIndex: 9999,
            top: position.top,
            left: position.left
          }} 
          onClick={(e) => e.stopPropagation()}
        >
          <button
            onClick={onClose}
            className="absolute top-2 right-2 text-slate-500 hover:text-white p-1 rounded transition-colors z-10"
          >
            <X className="w-4 h-4" />
          </button>

          {title && <div className="text-[10px] font-bold text-slate-500 uppercase tracking-wider px-1">{title}</div>}

          <div className="flex gap-1 border-b border-slate-700 pb-2">
            <button
              onClick={() => setActiveTab('values')}
              className={cn(
                "flex-1 px-2 py-1 text-[10px] font-bold rounded transition-colors",
                activeTab === 'values' ? "bg-blue-600 text-white" : "text-slate-400 hover:text-white"
              )}
            >
              Values ({safeSelectedValues.length})
            </button>
            <button
              onClick={() => setActiveTab('condition')}
              className={cn(
                "flex-1 px-2 py-1 text-[10px] font-bold rounded transition-colors flex items-center justify-center gap-1",
                activeTab === 'condition' ? "bg-blue-600 text-white" : "text-slate-400 hover:text-white"
              )}
            >
              <Filter className="w-3 h-3" />
              Condition
            </button>
          </div>

          {activeTab === 'values' ? (
            <>
              <div className="relative">
                <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-500" />
                <input
                  type="text"
                  placeholder="Filter values..."
                  value={search}
                  onChange={e => setSearch(e.target.value)}
                  onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                      e.preventDefault();
                      if (search) {
                        onSelectAll(filteredValues);
                      }
                      onClose();
                    }
                  }}
                  className="w-full bg-slate-900 border border-slate-700 rounded p-1.5 pl-8 pr-7 text-xs text-white focus:outline-none focus:border-blue-500"
                  autoFocus
                />
                {search && (
                  <button
                    onClick={() => setSearch('')}
                    className="absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 hover:text-white"
                  >
                    <X className="w-3 h-3" />
                  </button>
                )}
              </div>

              <div 
                ref={listRef}
                className="max-h-48 overflow-y-auto space-y-0.5 pr-1 custom-scrollbar"
              >
                {filteredValues.map((val, idx) => {
                  const isDragSelected = isDragging && dragStart !== null && hoveredIndex !== null &&
                    ((idx >= dragStart && idx <= hoveredIndex) || (idx <= dragStart && idx >= hoveredIndex));
                  return (
                    <div
                      key={val}
                      role="checkbox"
                      aria-checked={safeSelectedValues.includes(val)}
                      tabIndex={0}
                      onMouseDown={(e) => { e.preventDefault(); handleMouseDown(idx); }}
                      onMouseEnter={() => handleMouseEnter(idx)}
                      onClick={(e) => {
                        if (didDragRef.current) return;
                        if (e.shiftKey && lastClickedIndex !== null) {
                          const start = Math.min(lastClickedIndex, idx);
                          const end = Math.max(lastClickedIndex, idx);
                          const itemsToSelect = filteredValues.slice(start, end + 1);
                          const newSelected = new Set([...safeSelectedValues, ...itemsToSelect]);
                          onSelectAll(Array.from(newSelected));
                        } else {
                          onToggle(val);
                        }
                        setLastClickedIndex(idx);
                      }}
                      onKeyDown={(e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); onToggle(val); setLastClickedIndex(idx); } }}
                      className={cn(
                        "flex items-center gap-2 p-1.5 rounded cursor-pointer group transition-colors select-none",
                        isDragSelected ? "bg-blue-600/40" : "hover:bg-slate-700/50"
                      )}
                    >
                      <div className={cn(
                        "w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors",
                        selectedValues.includes(val) ? "bg-blue-600 border-blue-600" : "border-slate-600 bg-slate-900 group-hover:border-slate-500"
                      )}>
                        {safeSelectedValues.includes(val) && <Check className="w-3 h-3 text-white" />}
                      </div>
                      <span className="text-xs text-slate-300 truncate" title={val}>{val || '(Empty)'}</span>
                    </div>
                  );
                })}
                {filteredValues.length === 0 && (
                  <div className="text-[10px] text-slate-500 text-center py-4 italic">No values found</div>
                )}
              </div>

              <div className="flex items-center justify-between pt-2 border-t border-slate-700 mt-1">
                <div className="flex items-center gap-3">
                  <button
                    onClick={() => {
                      if (isAllSelected) {
                        onSelectAll([]);
                      } else {
                        onSelectAll(safeUniqueValues);
                      }
                    }}
                    className="text-[10px] font-black text-indigo-400 hover:text-indigo-300 transition-colors uppercase tracking-tight"
                  >
                    {isAllSelected ? 'Deselect All' : 'Select All'}
                  </button>
                  <span className="text-slate-600 font-bold">•</span>
                  <button
                    onClick={onClear}
                    className="text-[10px] font-bold text-slate-400 hover:text-white transition-colors uppercase tracking-tight"
                  >
                    Clear
                  </button>
                </div>
                <button
                  onClick={onClose}
                  className="px-4 py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-[10px] font-black rounded transition-colors shadow-lg active:scale-95 uppercase"
                >
                  OK
                </button>
              </div>
            </>
          ) : (
            <>
              <div className="space-y-2">
                <div>
                  <label className="text-[10px] text-slate-400 uppercase">Condition Type</label>
                  <select
                    value={condition.type}
                    onChange={e => setCondition({ ...condition, type: e.target.value as FilterType })}
                    className="w-full mt-1 bg-slate-900 border border-slate-700 rounded p-1.5 text-xs text-white focus:outline-none focus:border-blue-500"
                  >
                    <option value="equals">Equals (=)</option>
                    <option value="notEquals">Not Equals (≠)</option>
                    <option value="contains">Contains</option>
                    <option value="startsWith">Starts With</option>
                    <option value="endsWith">Ends With</option>
                    <option value="greaterThan">Greater Than (&gt;)</option>
                    <option value="lessThan">Less Than (&lt;)</option>
                    <option value="between">Between</option>
                  </select>
                </div>

                <div>
                  <label className="text-[10px] text-slate-400 uppercase">Value</label>
                  <input
                    type="text"
                    value={condition.value}
                    onChange={e => setCondition({ ...condition, value: e.target.value })}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        e.preventDefault();
                        applyCondition();
                      }
                    }}
                    placeholder="Enter value..."
                    className="w-full mt-1 bg-slate-900 border border-slate-700 rounded p-1.5 text-xs text-white focus:outline-none focus:border-blue-500"
                  />
                </div>

                {condition.type === 'between' && (
                  <div>
                    <label className="text-[10px] text-slate-400 uppercase">And</label>
                    <input
                      type="text"
                      value={condition.value2 || ''}
                      onChange={e => setCondition({ ...condition, value2: e.target.value })}
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          e.preventDefault();
                          applyCondition();
                        }
                      }}
                      placeholder="Enter second value..."
                      className="w-full mt-1 bg-slate-900 border border-slate-700 rounded p-1.5 text-xs text-white focus:outline-none focus:border-blue-500"
                    />
                  </div>
                )}

                <button
                  onClick={applyCondition}
                  className="w-full py-1.5 bg-blue-600 hover:bg-blue-700 text-white text-[10px] font-bold rounded transition-colors"
                >
                  Apply Condition
                </button>
              </div>

              {conditionResult.length > 0 && (
                <div className="text-[10px] text-green-400 text-center pt-2 border-t border-slate-700">
                  Found {conditionResult.length} matching value{conditionResult.length !== 1 ? 's' : ''}
                </div>
              )}
            </>
          )}
        </div>,
        portalContainer
      )}
    </div>
  );
}
