"use client";

/**
 * Filter sidebar for the corpus graph. Controlled — all state lives in
 * GraphView. node_types toggles let the chair thin the graph (precedent is
 * always on; halacha is Phase 2 and shown disabled to telegraph the roadmap).
 */

import {
  Accordion,
  AccordionContent,
  AccordionItem,
  AccordionTrigger,
} from "@/components/ui/accordion";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { Switch } from "@/components/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import type { GraphFacets } from "@/lib/api/graph";
import type { ColorBy, SizeBy } from "@/components/graph/graph-canvas";
import { getIsraelYear } from "@/lib/format-date";

export type GraphControls = {
  practiceArea: string;
  source: string;
  minCitations: number;
  q: string;
  court: string;
  precedentLevel: string;
  chair: string;
  district: string;
  yearFrom: number;
  yearTo: number;
  colorBy: ColorBy;
  sizeBy: SizeBy;
  showTopics: boolean;
  showPracticeAreas: boolean;
  showHalachot: boolean;
  showGaps: boolean;
  showDigests: boolean;
};

const ALL = "__all__";
// Floor covers the oldest dated precedent in the corpus (currently ע"א 725/81 →
// 1982); ceiling tracks the current year so the range never ages out.
const YEAR_FLOOR = 1980;
const CURRENT_YEAR = getIsraelYear(new Date()) ?? new Date().getFullYear();
const YEARS = Array.from(
  { length: CURRENT_YEAR - YEAR_FLOOR + 1 },
  (_, i) => CURRENT_YEAR - i,
);

const COLOR_BY: { value: ColorBy; label: string }[] = [
  { value: "type", label: "סוג נקודה" },
  { value: "practice_area", label: "תחום" },
  { value: "precedent_level", label: "דרגת סמכות" },
  { value: "community", label: "אשכול (זיהוי אוטומטי)" },
  { value: "recency", label: "עדכניות" },
];

const SIZE_BY: { value: SizeBy; label: string }[] = [
  { value: "indegree", label: "ציטוטים נכנסים" },
  { value: "pagerank", label: "השפעה (PageRank)" },
  { value: "betweenness", label: "גשריות (Betweenness)" },
];

const PRACTICE_AREAS: { value: string; label: string }[] = [
  { value: "rishuy_uvniya", label: "רישוי ובנייה" },
  { value: "betterment_levy", label: "היטל השבחה" },
  { value: "compensation_197", label: "פיצויים (ס׳ 197)" },
];

const SOURCES: { value: string; label: string }[] = [
  { value: "external_upload", label: "פסיקה חיצונית" },
  { value: "internal_committee", label: "החלטות ועדה" },
  { value: "cited_only", label: "מוזכר בלבד" },
];

const MIN_CITATIONS = [0, 1, 2, 3, 5];

export function GraphFilterPanel({
  controls,
  onChange,
  facets,
}: {
  controls: GraphControls;
  onChange: (patch: Partial<GraphControls>) => void;
  facets?: GraphFacets;
}) {
  return (
    <Card className="bg-surface border-rule shadow-sm w-[300px] shrink-0 max-h-full overflow-y-auto">
      <CardContent className="space-y-5 p-4">
        <div className="text-[0.8rem] font-semibold text-navy border-b border-rule-soft pb-2">
          פילטרים וסינון
        </div>
        <div className="space-y-1.5">
          <Label htmlFor="graph-search" className="text-xs text-ink-muted">
            חיפוש פסיקה
          </Label>
          <Input
            id="graph-search"
            value={controls.q}
            placeholder="מספר תיק או שם…"
            onChange={(e) => onChange({ q: e.target.value })}
          />
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-ink-muted">תחום</Label>
          <Select
            value={controls.practiceArea || ALL}
            onValueChange={(v) => onChange({ practiceArea: v === ALL ? "" : v })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL}>כל התחומים</SelectItem>
              {PRACTICE_AREAS.map((p) => (
                <SelectItem key={p.value} value={p.value}>
                  {p.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-ink-muted">מקור</Label>
          <Select
            value={controls.source || ALL}
            onValueChange={(v) => onChange({ source: v === ALL ? "" : v })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value={ALL}>כל המקורות</SelectItem>
              {SOURCES.map((s) => (
                <SelectItem key={s.value} value={s.value}>
                  {s.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-ink-muted">מינימום ציטוטים נכנסים</Label>
          <Select
            value={String(controls.minCitations)}
            onValueChange={(v) => onChange({ minCitations: Number(v) })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {MIN_CITATIONS.map((n) => (
                <SelectItem key={n} value={String(n)}>
                  {n === 0 ? "הצג הכל" : `${n}+`}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <Separator />

        <div className="space-y-1.5">
          <Label className="text-xs text-ink-muted">צביעה לפי</Label>
          <Select
            value={controls.colorBy}
            onValueChange={(v) => onChange({ colorBy: v as GraphControls["colorBy"] })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {COLOR_BY.map((c) => (
                <SelectItem key={c.value} value={c.value}>
                  {c.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <div className="space-y-1.5">
          <Label className="text-xs text-ink-muted">גודל נקודה לפי</Label>
          <Select
            value={controls.sizeBy}
            onValueChange={(v) => onChange({ sizeBy: v as GraphControls["sizeBy"] })}
          >
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {SIZE_BY.map((s) => (
                <SelectItem key={s.value} value={s.value}>
                  {s.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>

        <Accordion type="single" collapsible className="border-0">
          <AccordionItem value="advanced" className="border-0">
            <AccordionTrigger className="py-1 text-xs text-ink-muted hover:no-underline">
              סינון מתקדם
            </AccordionTrigger>
            <AccordionContent className="space-y-4 pt-2">
              <FacetSelect
                label="בית משפט / ערכאה"
                value={controls.court}
                options={facets?.courts ?? []}
                onChange={(v) => onChange({ court: v })}
              />
              <FacetSelect
                label="דרגת סמכות"
                value={controls.precedentLevel}
                options={facets?.precedent_levels ?? []}
                onChange={(v) => onChange({ precedentLevel: v })}
              />
              <FacetSelect
                label="יו״ר"
                value={controls.chair}
                options={facets?.chairs ?? []}
                onChange={(v) => onChange({ chair: v })}
              />
              <FacetSelect
                label="מחוז"
                value={controls.district}
                options={facets?.districts ?? []}
                onChange={(v) => onChange({ district: v })}
              />
              <div className="grid grid-cols-2 gap-2">
                <YearSelect
                  label="משנה"
                  value={controls.yearFrom}
                  onChange={(v) => onChange({ yearFrom: v })}
                />
                <YearSelect
                  label="עד שנה"
                  value={controls.yearTo}
                  onChange={(v) => onChange({ yearTo: v })}
                />
              </div>
            </AccordionContent>
          </AccordionItem>
        </Accordion>

        <Separator />

        <div className="space-y-3">
          <div className="text-[0.8rem] font-semibold text-navy border-b border-rule-soft pb-2">
            שכבות הגרף
          </div>
          <ToggleRow
            label="נקודות-נושא"
            swatch="#a97d3a"
            checked={controls.showTopics}
            onCheckedChange={(v) => onChange({ showTopics: v })}
          />
          <ToggleRow
            label="נקודות-תחום"
            swatch="#4a7c59"
            checked={controls.showPracticeAreas}
            onCheckedChange={(v) => onChange({ showPracticeAreas: v })}
          />
          <ToggleRow
            label="חוסרי מחקר (פסיקה חסרה)"
            swatch="#a54242"
            checked={controls.showGaps}
            onCheckedChange={(v) => onChange({ showGaps: v })}
          />
          <ToggleRow
            label="יומונים (כל יום)"
            swatch="#b8894a"
            checked={controls.showDigests}
            onCheckedChange={(v) => onChange({ showDigests: v })}
          />
        </div>

        {/* Stage-2 gate — halacha layer is dense, gated by default (mockup 11) */}
        <div className="rounded-lg border border-gold bg-gold-wash p-3.5 space-y-2">
          <div className="flex items-center gap-2">
            <h4 className="text-sm font-semibold text-navy m-0">שלב ב׳ — שכבת הלכות</h4>
            <Switch
              className="ms-auto"
              checked={controls.showHalachot}
              onCheckedChange={(v) => onChange({ showHalachot: v })}
              aria-label="הצגת שכבת ההלכות"
            />
          </div>
          <p className="text-[0.72rem] text-ink-muted leading-relaxed m-0">
            הפעלת שכבת ההלכות (1,454 צמתים). מגודרת כברירת-מחדל בשל הצפיפות —
            הדלקה מציגה את הקשרים הלכה←פסיקה.
          </p>
        </div>
      </CardContent>
    </Card>
  );
}

function FacetSelect({
  label,
  value,
  options,
  onChange,
}: {
  label: string;
  value: string;
  options: string[];
  onChange: (v: string) => void;
}) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs text-ink-muted">{label}</Label>
      <Select value={value || ALL} onValueChange={(v) => onChange(v === ALL ? "" : v)}>
        <SelectTrigger>
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value={ALL}>הכל</SelectItem>
          {options.map((o) => (
            <SelectItem key={o} value={o}>
              {o}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
}

function YearSelect({
  label,
  value,
  onChange,
}: {
  label: string;
  value: number;
  onChange: (v: number) => void;
}) {
  return (
    <div className="space-y-1.5">
      <Label className="text-xs text-ink-muted">{label}</Label>
      <Select
        value={value ? String(value) : ALL}
        onValueChange={(v) => onChange(v === ALL ? 0 : Number(v))}
      >
        <SelectTrigger>
          <SelectValue />
        </SelectTrigger>
        <SelectContent>
          <SelectItem value={ALL}>—</SelectItem>
          {YEARS.map((y) => (
            <SelectItem key={y} value={String(y)}>
              {y}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );
}

function ToggleRow({
  label,
  checked,
  onCheckedChange,
  disabled,
  swatch,
}: {
  label: string;
  checked: boolean;
  onCheckedChange: (v: boolean) => void;
  disabled?: boolean;
  swatch?: string;
}) {
  return (
    <div className={`flex items-center gap-2.5 ${disabled ? "opacity-55" : ""}`}>
      {swatch ? (
        <span
          className="inline-block size-2.5 rounded-full shrink-0 ring-1 ring-black/10"
          style={{ backgroundColor: swatch }}
          aria-hidden
        />
      ) : null}
      <span className={`text-sm ${disabled ? "text-ink-muted/50" : "text-ink-soft"}`}>
        {label}
      </span>
      <Switch
        className="ms-auto"
        checked={checked}
        onCheckedChange={onCheckedChange}
        disabled={disabled}
      />
    </div>
  );
}
