import { useState } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { Info, Save, SlidersHorizontal } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { PageHeader, SectionCard } from "@/components/ledger/Primitives";
import { useLedger } from "@/lib/ledger-store";

export const Route = createFileRoute("/settings/rules")({
  head: () => ({
    meta: [
      { title: "Booking rules — Abdelouhab" },
      { name: "description", content: "Control how AI suggestions become auto-ready bookings." },
      { property: "og:title", content: "Booking rules — Abdelouhab" },
      { property: "og:description", content: "Confidence thresholds, auto-sync and per-client booking rules." },
    ],
  }),
  component: RulesPage,
});

function RulesPage() {
  const { settings, updateSettings, clients, setClientRule } = useLedger();

  return (
    <div className="space-y-6">
      <PageHeader
        eyebrow="Configuration"
        title="Booking rules"
        subtitle="Control how AI suggestions become auto-ready bookings."
      />

      <div className="flex items-start gap-3 rounded-xl border border-border bg-surface px-4 py-3">
        <Info size={18} className="mt-0.5 text-primary" aria-hidden="true" />
        <div>
          <p className="text-[13.5px] font-medium">SnelStart is the system of record</p>
          <p className="mt-0.5 text-[13px] leading-6 text-muted-foreground">
            Abdelouhab prepares and validates bookkeeping work before approved entries are synced to SnelStart.
          </p>
        </div>
      </div>

      <div className="grid gap-4 lg:grid-cols-2">
        <SectionCard title="Confidence threshold" description="When a suggestion becomes auto-ready" bodyClassName="space-y-4 p-5">
          <p className="num font-display text-[30px] leading-none">{settings.threshold}%</p>
          <Slider
            value={[settings.threshold]}
            min={50}
            max={99}
            step={1}
            aria-label="Auto-ready confidence threshold"
            onValueChange={(v) => updateSettings({ threshold: v[0] ?? 85 })}
          />
          <p className="text-[13px] text-muted-foreground">
            Auto-ready above {settings.threshold}% confidence. Below the threshold, invoices land in Needs review.
          </p>
        </SectionCard>

        <SectionCard title="Auto-sync" description="Hands-off syncing to SnelStart" bodyClassName="space-y-4 p-5">
          <div className="flex items-center justify-between gap-4">
            <Label htmlFor="autosync" className="text-[13.5px]">
              Allow auto-sync when Auto-ready
            </Label>
            <Switch
              id="autosync"
              checked={settings.autoSync}
              onCheckedChange={(v) => updateSettings({ autoSync: v })}
            />
          </div>
          <p className="text-[13px] leading-6 text-muted-foreground">
            When enabled, invoices that reach Auto-ready are queued for SnelStart without a manual approval step.
            Clients without a SnelStart connection are always skipped.
          </p>
        </SectionCard>
      </div>

      <SectionCard title="Global rule" description="Applies to every client" bodyClassName="p-5">
        <RuleEditor value={settings.globalRule} onSave={(v) => updateSettings({ globalRule: v })} />
      </SectionCard>

      <SectionCard title="Client rules" description="Per-administratie booking behaviour" bodyClassName="grid gap-4 p-5 md:grid-cols-2">
        {clients.map((c) => (
          <div key={c.id} className="rounded-lg border border-border p-4">
            <div className="flex items-center gap-2">
              <SlidersHorizontal size={16} className="text-primary" aria-hidden="true" />
              <p className="text-[14px] font-medium">{c.name}</p>
            </div>
            <div className="mt-3">
              <RuleEditor
                value={settings.clientRules[c.id] ?? ""}
                onSave={(v) => setClientRule(c.id, v)}
              />
            </div>
          </div>
        ))}
      </SectionCard>
    </div>
  );
}

function RuleEditor({ value, onSave }: { value: string; onSave: (v: string) => void }) {
  const [draft, setDraft] = useState(value);
  return (
    <div className="flex flex-wrap items-end gap-2">
      <div className="min-w-[240px] flex-1">
        <Label className="text-[12px] text-muted-foreground">Rule</Label>
        <Input value={draft} onChange={(e) => setDraft(e.target.value)} className="mt-1 h-9 bg-surface" />
      </div>
      <Button variant="outline" onClick={() => onSave(draft)}>
        <Save size={16} /> Save
      </Button>
    </div>
  );
}
