// src/components/FilterPanel.tsx
import React, { useState, useEffect } from 'react';
import {
  DndContext,
  closestCenter,
  PointerSensor,
  useSensor,
  useSensors,
} from '@dnd-kit/core';
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy,
  useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import type { TooltipColumn } from '../App'; // Use type from App

// Represents a single sortable filter category
const SortableFilterItem: React.FC<{ 
    item: TooltipColumn; 
    options: string[];
    selectedValues: string[];
    onSelectionChange: (category: string, values: string[]) => void;
    onVisibilityChange: (id: string) => void;
}> = ({ item, options, selectedValues, onSelectionChange, onVisibilityChange }) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
  } = useSortable({ id: item.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    marginBottom: '15px',
  };

  return (
    <div ref={setNodeRef} style={style}>
      <details className="filter-group">
        <summary>
          <input
            type="checkbox"
            checked={item.visible}
            onChange={() => onVisibilityChange(item.id)}
            onClick={(e) => e.stopPropagation()} // Prevent details from closing when clicking checkbox
            style={{ marginRight: '10px' }}
          />
          <span {...attributes} {...listeners} style={{ cursor: 'grab' }}>
            {item.name}
          </span>
        </summary>
        <div className="filter-options">
          {options.map(option => (
            <div key={option} className="filter-option">
              <input
                type="checkbox"
                id={`${item.id}-${option}`}
                value={option}
                checked={selectedValues.includes(option)}
                onChange={() => {
                    const newSelection = selectedValues.includes(option)
                        ? selectedValues.filter(v => v !== option)
                        : [...selectedValues, option];
                    onSelectionChange(item.name, newSelection);
                }}
              />
              <label htmlFor={`${item.id}-${option}`}>{option}</label>
            </div>
          ))}
        </div>
      </details>
    </div>
  );
};


interface FilterPanelProps {
  filters: Record<string, string[]>;
  tooltipColumns: TooltipColumn[];
  setTooltipColumns: (columns: TooltipColumn[]) => void;
  onFilterChange: (selectedFilters: Record<string, string[]>) => void;
  isLoading: boolean;
}

const FilterPanel: React.FC<FilterPanelProps> = ({ filters, tooltipColumns, setTooltipColumns, onFilterChange, isLoading }) => {
  const [selectedFilters, setSelectedFilters] = useState<Record<string, string[]>>({});

  useEffect(() => {
    setSelectedFilters({});
  }, [filters]);

  const sensors = useSensors(useSensor(PointerSensor));

  const handleDragEnd = (event: any) => {
    const { active, over } = event;
    if (active.id !== over.id) {
      const oldIndex = tooltipColumns.findIndex(c => c.id === active.id);
      const newIndex = tooltipColumns.findIndex(c => c.id === over.id);
      setTooltipColumns(arrayMove(tooltipColumns, oldIndex, newIndex));
    }
  };

  const handleVisibilityChange = (id: string) => {
    setTooltipColumns(
        tooltipColumns.map(c => c.id === id ? { ...c, visible: !c.visible } : c)
    );
  };
  
  const handleSelectionChange = (category: string, values: string[]) => {
    setSelectedFilters(prev => ({
      ...prev,
      [category]: values,
    }));
  };

  const handleApplyClick = () => {
      onFilterChange(selectedFilters);
  };

  const handleResetClick = () => {
    setSelectedFilters({});
    onFilterChange({});
  };

  if (Object.keys(filters).length === 0) {
    return <div>Upload a file to see filter options.</div>;
  }

  return (
    <>
      {/* Styles can be moved to a CSS file, but are here for simplicity */}
      <style>{`
        .filter-panel { padding-top: 20px; }
        .filter-group summary { font-weight: bold; cursor: pointer; padding: 5px; background-color: #444; border-radius: 4px; display: flex; align-items: center; }
        .filter-options { max-height: 200px; overflow-y: auto; padding: 10px; background-color: #2a2a2a; border-radius: 4px; margin-top: 5px;}
        .filter-option { display: flex; align-items: center; margin-bottom: 5px; }
        .filter-option input { margin-right: 10px; }
        .filter-buttons { margin-top: 20px; display: flex; justify-content: space-between; }
        .filter-buttons button { width: 48%; padding: 10px; border: none; border-radius: 4px; cursor: pointer; }
        .apply-button { background-color: #4CAF50; color: white; }
        .reset-button { background-color: #f44336; color: white; }
        .filter-buttons button:disabled { background-color: #555; cursor: not-allowed; }
      `}</style>
      <div className="filter-panel">
        <h3>Filters & Tooltip Settings</h3>
        <p style={{fontSize: '0.8em', color: '#aaa'}}>Drag category to reorder tooltip. Uncheck to hide from tooltip.</p>
        <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
            <SortableContext items={tooltipColumns} strategy={verticalListSortingStrategy}>
                {tooltipColumns.map(col => (
                    <SortableFilterItem
                        key={col.id}
                        item={col}
                        options={filters[col.name] || []}
                        selectedValues={selectedFilters[col.name] || []}
                        onSelectionChange={handleSelectionChange}
                        onVisibilityChange={handleVisibilityChange}
                    />
                ))}
            </SortableContext>
        </DndContext>
        <div className="filter-buttons">
          <button onClick={handleApplyClick} disabled={isLoading} className="apply-button">
            {isLoading ? 'Loading...' : 'Apply Filters'}
          </button>
          <button onClick={handleResetClick} disabled={isLoading} className="reset-button">
            Reset
          </button>
        </div>
      </div>
    </>
  );
};

export default FilterPanel;