import React from 'react'
import { SKILL_LEVEL_OPTIONS } from '../../constants/skillLevels'
import MultiSelectCombo from '../MultiSelectCombo'
import ExerciseFocusRulePicker from '../ExerciseFocusRulePicker'
import CatalogRulePicker from '../CatalogRulePicker'

const LEVEL_FILTER_OPTS = SKILL_LEVEL_OPTIONS.filter((o) => o.level != null)

/**
 * Filter-Dialog für die Übungsliste (gleiche Logik wie zuvor inline in ExercisesListPage).
 */
export default function ExerciseListFilterModal({
  open,
  onClose,
  filters,
  setFilters,
  focusOptions,
  styleOptions,
  trainingTypeOptions,
  targetGroupOptions,
  skillOptions,
  visibilityOptions,
  statusOptions,
  savingExercisePrefs,
  onSaveStandard,
  onResetAll,
}) {
  if (!open) return null

  return (
    <div
      className="admin-modal-backdrop"
      role="presentation"
      onClick={(e) => {
        if (e.target === e.currentTarget) onClose()
      }}
    >
      <div
        className="admin-modal-sheet exercise-filter-modal"
        data-testid="exercise-list-filter-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="exercise-filter-modal-title"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="admin-modal-sheet__header">
          <h3 id="exercise-filter-modal-title" className="admin-modal-sheet__title">
            Übungen filtern
          </h3>
          <button type="button" className="btn btn-secondary admin-modal-sheet__close" onClick={onClose}>
            Schließen
          </button>
        </div>
        <div className="admin-modal-sheet__body exercise-filter-modal__scroll">
          <p className="muted" style={{ marginTop: 0, marginBottom: '14px' }}>
            Zwischen den Bereichen gilt <strong>UND</strong>. Fokusbereiche: mehrere „+ mit“ bedeuten alle müssen
            gesetzt sein; „− ohne“ schließt Übungen aus, die diesen Fokus zusätzlich haben. Stilrichtung /
            Trainingsstil / Zielgruppe: mehrere „+“ = alle zutreffend (UND); „−“ verbietet die Zuordnung. Unter
            „Freigabe“: Sichtbarkeit / Status mit „+“ = eine davon (ODER); „−“ blendet aus.
          </p>

          <section className="exercise-filter-section">
            <h4 className="exercise-filter-section-title">Zuordnung</h4>
            <ExerciseFocusRulePicker
              focusOptions={focusOptions}
              focusRules={filters.focus_rules}
              focusOnlyWithout={filters.focus_only_without}
              legacyFocusAreaIds={filters.focus_area_ids}
              onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
            />
            <div className="exercise-filters-modal-grid exercise-filters-modal-grid--catalog" style={{ marginTop: '12px' }}>
              <CatalogRulePicker
                label="Stilrichtung"
                hint="+ alle nötig (UND). − verbietet Zuordnung."
                options={styleOptions}
                rules={filters.style_direction_rules}
                rulesFieldName="style_direction_rules"
                placeholder="Stil …"
                onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
              />
              <CatalogRulePicker
                label="Trainingsstil"
                hint="+ alle nötig (UND). − verbietet Zuordnung."
                options={trainingTypeOptions}
                rules={filters.training_type_rules}
                rulesFieldName="training_type_rules"
                placeholder="Trainingsstil …"
                onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
              />
              <CatalogRulePicker
                label="Zielgruppe"
                hint="+ alle nötig (UND). − verbietet Zuordnung."
                options={targetGroupOptions}
                rules={filters.target_group_rules}
                rulesFieldName="target_group_rules"
                placeholder="Gruppe …"
                onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
              />
            </div>
          </section>

          <section className="exercise-filter-section">
            <h4 className="exercise-filter-section-title">Fähigkeit und zugehörige Stufe</h4>
            <div className="exercise-filter-skill-block">
              <label className="form-label">Fähigkeit</label>
              <MultiSelectCombo
                value={filters.skill_ids}
                onChange={(v) => setFilters({ ...filters, skill_ids: v })}
                options={skillOptions}
                placeholder="Fähigkeit suchen …"
              />
              <p className="exercise-filter-skill-hint">
                Die Stufen filtern nach dem Niveau der Zuordnung Übung ↔ Fähigkeit (von–bis).
              </p>
              <div className="exercise-filter-skill-levels-row">
                <label className="exercise-filter-skill-level-field">
                  <span className="exercise-filter-skill-level-caption">von</span>
                  <select
                    className="form-input exercise-filter-level-select"
                    title="Mindest-Stufe"
                    value={filters.skill_min_level}
                    onChange={(e) => setFilters({ ...filters, skill_min_level: e.target.value })}
                  >
                    <option value="">–</option>
                    {LEVEL_FILTER_OPTS.map((o) => (
                      <option key={o.value} value={String(o.level)} title={o.label}>
                        {o.level}
                      </option>
                    ))}
                  </select>
                </label>
                <span className="exercise-filter-skill-dash" aria-hidden>
                  –
                </span>
                <label className="exercise-filter-skill-level-field">
                  <span className="exercise-filter-skill-level-caption">bis</span>
                  <select
                    className="form-input exercise-filter-level-select"
                    title="Höchst-Stufe"
                    value={filters.skill_max_level}
                    onChange={(e) => setFilters({ ...filters, skill_max_level: e.target.value })}
                  >
                    <option value="">–</option>
                    {LEVEL_FILTER_OPTS.map((o) => (
                      <option key={`m-${o.value}`} value={String(o.level)} title={o.label}>
                        {o.level}
                      </option>
                    ))}
                  </select>
                </label>
              </div>
            </div>
          </section>

          <section className="exercise-filter-section">
            <h4 className="exercise-filter-section-title">Ausblenden / Liste</h4>
            <p className="muted" style={{ marginTop: 0, marginBottom: '12px', fontSize: '13px' }}>
              Sichtbarkeit und Status steuern Sie unter „Freigabe“ mit + und −. Hier nur globale Listen-Optionen.
            </p>
            <div style={{ marginTop: '6px', display: 'flex', flexDirection: 'column', gap: '12px' }}>
              <label
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '10px',
                  cursor: filters.focus_only_without ? 'not-allowed' : 'pointer',
                  opacity: filters.focus_only_without ? 0.55 : 1,
                }}
              >
                <input
                  type="checkbox"
                  disabled={!!filters.focus_only_without}
                  checked={!!filters.exclude_without_focus}
                  onChange={(e) =>
                    setFilters((prev) => ({
                      ...prev,
                      exclude_without_focus: e.target.checked,
                      ...(e.target.checked ? { focus_only_without: false } : {}),
                    }))
                  }
                />
                <span>Übungen ohne Fokusbereich ausblenden</span>
              </label>
              <label style={{ display: 'flex', alignItems: 'center', gap: '10px', cursor: 'pointer' }}>
                <input
                  type="checkbox"
                  checked={!!filters.include_archived}
                  onChange={(e) => setFilters({ ...filters, include_archived: e.target.checked })}
                />
                <span>Archivierte Übungen einblenden (ohne Haken werden sie standardmäßig ausgeblendet)</span>
              </label>
            </div>
          </section>

          <section className="exercise-filter-section exercise-filter-section--last">
            <h4 className="exercise-filter-section-title">Freigabe</h4>
            <p className="muted" style={{ marginTop: 0, marginBottom: '10px', fontSize: '12px' }}>
              Pro Übung nur ein Wert: mehrere „+“ bedeuten „eine davon“ (ODER). „−“ blendet Werte aus.
            </p>
            <div className="exercise-filters-modal-grid exercise-filters-modal-grid--two exercise-filters-modal-grid--catalog">
              <CatalogRulePicker
                label="Sichtbarkeit"
                options={visibilityOptions}
                rules={filters.visibility_rules}
                rulesFieldName="visibility_rules"
                idKind="string"
                placeholder="Sichtbarkeit …"
                onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
              />
              <CatalogRulePicker
                label="Status"
                options={statusOptions}
                rules={filters.status_rules}
                rulesFieldName="status_rules"
                idKind="string"
                placeholder="Status …"
                onPatch={(patch) => setFilters((prev) => ({ ...prev, ...patch }))}
              />
            </div>
          </section>
        </div>
        <div className="exercise-filter-modal__footer">
          <button type="button" className="btn btn-secondary" disabled={savingExercisePrefs} onClick={onSaveStandard}>
            {savingExercisePrefs ? 'Speichern…' : 'Als Standard speichern'}
          </button>
          <button type="button" className="btn" onClick={onResetAll}>
            Alle Filter zurücksetzen
          </button>
          <button type="button" className="btn btn-primary" onClick={onClose}>
            Fertig
          </button>
        </div>
      </div>
    </div>
  )
}
