import { useEffect, useState, useRef } from 'react';
import { useSegment } from './SegmentContext';
import type { Segment } from './types';

export interface SegmentSelectorProps {
  /** Placeholder text when no segment selected */
  placeholder?: string;
  /** Whether to show comparison mode toggle */
  showComparisonToggle?: boolean;
  /** Called when segment selection changes */
  onSegmentChange?: (segment: Segment | null) => void;
  /** Custom CSS class */
  className?: string;
  /** Disabled state */
  disabled?: boolean;
}

/**
 * Dropdown selector for choosing segments
 */
export function SegmentSelector({
  placeholder = 'All Traffic',
  showComparisonToggle = false,
  onSegmentChange,
  className,
  disabled = false,
}: SegmentSelectorProps) {
  const {
    selectedSegment,
    comparisonSegment,
    availableSegments,
    loading,
    error,
    selectSegment,
    setComparisonSegment,
    loadSegments,
  } = useSegment();

  const [isOpen, setIsOpen] = useState(false);
  const [comparisonMode, setComparisonMode] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Load segments on mount
  useEffect(() => {
    if (availableSegments.length === 0) {
      loadSegments();
    }
  }, [availableSegments.length, loadSegments]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, []);

  const handleSelect = (segment: Segment | null) => {
    if (comparisonMode) {
      setComparisonSegment(segment);
    } else {
      selectSegment(segment);
      onSegmentChange?.(segment);
    }
    setIsOpen(false);
  };

  const toggleComparisonMode = () => {
    setComparisonMode(!comparisonMode);
    if (comparisonMode) {
      setComparisonSegment(null);
    }
  };

  // Group segments by built-in vs custom
  const builtInSegments = availableSegments.filter((s) => s.isBuiltIn);
  const customSegments = availableSegments.filter((s) => !s.isBuiltIn);

  const currentSegment = comparisonMode ? comparisonSegment : selectedSegment;
  const displayText = currentSegment?.name || placeholder;

  return (
    <div
      ref={dropdownRef}
      className={className}
      style={{
        position: 'relative',
        display: 'inline-block',
        minWidth: '200px',
      }}
    >
      {/* Main selector button */}
      <button
        type="button"
        disabled={disabled || loading}
        onClick={() => setIsOpen(!isOpen)}
        style={{
          width: '100%',
          padding: '8px 12px',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'space-between',
          backgroundColor: disabled ? '#f5f5f5' : '#fff',
          border: '1px solid #ddd',
          borderRadius: '6px',
          cursor: disabled ? 'not-allowed' : 'pointer',
          fontSize: '14px',
          color: currentSegment ? '#333' : '#666',
        }}
      >
        <span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          {comparisonMode && (
            <span
              style={{
                padding: '2px 6px',
                backgroundColor: '#e3f2fd',
                color: '#1976d2',
                borderRadius: '4px',
                fontSize: '11px',
                fontWeight: 500,
              }}
            >
              Compare
            </span>
          )}
          {loading ? 'Loading...' : displayText}
        </span>
        <svg
          width="12"
          height="12"
          viewBox="0 0 12 12"
          style={{
            transform: isOpen ? 'rotate(180deg)' : 'rotate(0deg)',
            transition: 'transform 0.2s',
          }}
        >
          <path d="M2 4l4 4 4-4" stroke="#666" strokeWidth="1.5" fill="none" />
        </svg>
      </button>

      {/* Dropdown menu */}
      {isOpen && (
        <div
          style={{
            position: 'absolute',
            top: '100%',
            left: 0,
            right: 0,
            marginTop: '4px',
            backgroundColor: '#fff',
            border: '1px solid #ddd',
            borderRadius: '6px',
            boxShadow: '0 4px 12px rgba(0,0,0,0.1)',
            zIndex: 1000,
            maxHeight: '320px',
            overflowY: 'auto',
          }}
        >
          {/* Comparison toggle */}
          {showComparisonToggle && (
            <div
              style={{
                padding: '8px 12px',
                borderBottom: '1px solid #eee',
              }}
            >
              <label
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '8px',
                  cursor: 'pointer',
                  fontSize: '13px',
                }}
              >
                <input
                  type="checkbox"
                  checked={comparisonMode}
                  onChange={toggleComparisonMode}
                />
                Comparison Mode
              </label>
            </div>
          )}

          {/* All Traffic option */}
          <div
            onClick={() => handleSelect(null)}
            style={{
              padding: '10px 12px',
              cursor: 'pointer',
              backgroundColor: !currentSegment ? '#f0f7ff' : 'transparent',
              borderBottom: '1px solid #eee',
            }}
          >
            <div style={{ fontWeight: !currentSegment ? 600 : 400 }}>{placeholder}</div>
            <div style={{ fontSize: '12px', color: '#666' }}>No segment filter applied</div>
          </div>

          {/* Built-in segments */}
          {builtInSegments.length > 0 && (
            <>
              <div
                style={{
                  padding: '8px 12px',
                  fontSize: '11px',
                  fontWeight: 600,
                  color: '#666',
                  textTransform: 'uppercase',
                  backgroundColor: '#fafafa',
                }}
              >
                Built-in Segments
              </div>
              {builtInSegments.map((segment) => (
                <div
                  key={segment.id}
                  onClick={() => handleSelect(segment)}
                  style={{
                    padding: '10px 12px',
                    cursor: 'pointer',
                    backgroundColor:
                      currentSegment?.id === segment.id ? '#f0f7ff' : 'transparent',
                  }}
                >
                  <div
                    style={{ fontWeight: currentSegment?.id === segment.id ? 600 : 400 }}
                  >
                    {segment.name}
                  </div>
                  {segment.description && (
                    <div style={{ fontSize: '12px', color: '#666' }}>
                      {segment.description}
                    </div>
                  )}
                </div>
              ))}
            </>
          )}

          {/* Custom segments */}
          {customSegments.length > 0 && (
            <>
              <div
                style={{
                  padding: '8px 12px',
                  fontSize: '11px',
                  fontWeight: 600,
                  color: '#666',
                  textTransform: 'uppercase',
                  backgroundColor: '#fafafa',
                }}
              >
                Custom Segments
              </div>
              {customSegments.map((segment) => (
                <div
                  key={segment.id}
                  onClick={() => handleSelect(segment)}
                  style={{
                    padding: '10px 12px',
                    cursor: 'pointer',
                    backgroundColor:
                      currentSegment?.id === segment.id ? '#f0f7ff' : 'transparent',
                  }}
                >
                  <div
                    style={{ fontWeight: currentSegment?.id === segment.id ? 600 : 400 }}
                  >
                    {segment.name}
                  </div>
                  {segment.description && (
                    <div style={{ fontSize: '12px', color: '#666' }}>
                      {segment.description}
                    </div>
                  )}
                </div>
              ))}
            </>
          )}

          {error && (
            <div
              style={{
                padding: '12px',
                color: '#d32f2f',
                fontSize: '13px',
                textAlign: 'center',
              }}
            >
              {error}
            </div>
          )}
        </div>
      )}

      {/* Selected segments display (when comparison mode active) */}
      {showComparisonToggle && selectedSegment && comparisonSegment && (
        <div
          style={{
            marginTop: '8px',
            padding: '8px',
            backgroundColor: '#f5f5f5',
            borderRadius: '4px',
            fontSize: '12px',
          }}
        >
          <div>
            <strong>Primary:</strong> {selectedSegment.name}
          </div>
          <div>
            <strong>Compare:</strong> {comparisonSegment.name}
          </div>
        </div>
      )}
    </div>
  );
}
