import React from 'react';
import { RefreshCw, Download, ChevronDown } from 'lucide-react';

export interface FilterBarOption {
  value: string;
  label: string;
}

export interface FilterBarProps {
  range: string;
  onRangeChange: (value: string) => void;
  rangeOptions: FilterBarOption[];
  cohorts?: FilterBarOption[];
  cohort?: string;
  onCohortChange?: (value: string) => void;
  programmes?: FilterBarOption[];
  programme?: string;
  onProgrammeChange?: (value: string) => void;
  classes?: FilterBarOption[];
  classId?: string;
  onClassChange?: (value: string) => void;
  onRefresh: () => void;
  onExport?: () => void;
  exporting?: boolean;
  exportOptions?: { label: string; onClick: () => void }[];
  loading?: boolean;
}

/**
 * Header filter row for /reports. Time-range picker, optional cohort /
 * programme / class dropdowns, refresh button, optional export dropdown.
 */
export function FilterBar({
  range,
  onRangeChange,
  rangeOptions,
  cohorts,
  cohort,
  onCohortChange,
  programmes,
  programme,
  onProgrammeChange,
  classes,
  classId,
  onClassChange,
  onRefresh,
  onExport,
  exporting = false,
  exportOptions,
  loading = false,
}: FilterBarProps) {
  const [exportOpen, setExportOpen] = React.useState(false);
  const exportRef = React.useRef<HTMLDivElement>(null);

  React.useEffect(() => {
    if (!exportOpen) return;
    const onDoc = (e: MouseEvent) => {
      if (exportRef.current && !exportRef.current.contains(e.target as Node)) {
        setExportOpen(false);
      }
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [exportOpen]);

  const selectClass =
    'bg-card border border-border rounded-xl px-3 py-2 text-xs font-bold text-text focus:outline-none focus:border-primary cursor-pointer min-w-[8rem]';

  return (
    <div className="bg-card border border-border rounded-[1.5rem] p-4 shadow-sm flex flex-col md:flex-row md:flex-wrap md:items-center gap-3">
      <div className="flex items-center gap-2">
        <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Range</span>
        <select
          className={selectClass}
          value={range}
          onChange={(e) => onRangeChange(e.target.value)}
          aria-label="Time range"
        >
          {rangeOptions.map((o) => (
            <option key={o.value} value={o.value}>
              {o.label}
            </option>
          ))}
        </select>
      </div>

      {cohorts && onCohortChange && (
        <div className="flex items-center gap-2">
          <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Cohort</span>
          <select
            className={selectClass}
            value={cohort ?? ''}
            onChange={(e) => onCohortChange(e.target.value)}
            aria-label="Cohort"
          >
            <option value="">All cohorts</option>
            {cohorts.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </div>
      )}

      {programmes && onProgrammeChange && (
        <div className="flex items-center gap-2">
          <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Programme</span>
          <select
            className={selectClass}
            value={programme ?? ''}
            onChange={(e) => onProgrammeChange(e.target.value)}
            aria-label="Programme"
          >
            <option value="">All</option>
            {programmes.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </div>
      )}

      {classes && onClassChange && (
        <div className="flex items-center gap-2">
          <span className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">Class</span>
          <select
            className={selectClass}
            value={classId ?? ''}
            onChange={(e) => onClassChange(e.target.value)}
            aria-label="Class"
          >
            <option value="">All classes</option>
            {classes.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
        </div>
      )}

      <div className="flex-1" />

      <button
        type="button"
        onClick={onRefresh}
        disabled={loading}
        className="px-3 py-2 bg-muted hover:bg-muted/80 text-text rounded-xl text-xs font-black uppercase tracking-wider cursor-pointer flex items-center gap-1.5 transition-all disabled:opacity-50"
      >
        <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
        Refresh
      </button>

      {exportOptions && exportOptions.length > 0 && (
        <div ref={exportRef} className="relative">
          <button
            type="button"
            onClick={() => onExport ? onExport() : setExportOpen((v) => !v)}
            disabled={exporting}
            className="px-3 py-2 bg-primary text-white rounded-xl text-xs font-black uppercase tracking-wider cursor-pointer flex items-center gap-1.5 transition-all hover:bg-primary/90 disabled:opacity-50"
          >
            <Download size={14} />
            Export
            <ChevronDown size={12} />
          </button>
          {!onExport && exportOpen && (
            <div className="absolute right-0 top-full mt-2 w-56 bg-card border border-border rounded-xl shadow-2xl z-30 overflow-hidden">
              {exportOptions.map((o, i) => (
                <button
                  key={i}
                  type="button"
                  onClick={() => {
                    o.onClick();
                    setExportOpen(false);
                  }}
                  className="w-full px-4 py-2.5 text-left text-xs font-bold text-text hover:bg-muted transition-colors flex items-center gap-2 border-b border-border/40 last:border-0"
                >
                  <Download size={12} className="text-text-muted" />
                  {o.label}
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default FilterBar;