import type { ReactNode } from "react";
import { STRATEGY_META } from "@/lib/fx/strategies";
import type { StrategyId } from "@/lib/fx/types";
import { pairLabel } from "@/lib/fx/format";
import { allPairIds } from "@/lib/fx/pairs";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
import { Switch } from "@/components/ui/switch";
import { useDesk } from "@/store/desk";
import { cn } from "@/lib/utils";

const STRATEGIES = Object.keys(STRATEGY_META) as StrategyId[];

export function BotPanel() {
  const bot = useDesk((s) => s.bot);
  const setBot = useDesk((s) => s.setBot);
  const armBot = useDesk((s) => s.armBot);
  const toggleBotPair = useDesk((s) => s.toggleBotPair);
  const meta = STRATEGY_META[bot.strategy];

  return (
    <section className="p-3 lg:p-4">
      <div className="mb-3 flex items-center justify-between gap-3">
        <div>
          <h2 className="text-sm font-medium">Execution bot</h2>
          <p className="text-micro text-muted-foreground">
            {bot.haltReason ? bot.haltReason : "Fires market orders on closed bars"}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <span className="text-micro uppercase tracking-[0.14em] text-muted-foreground">
            {bot.enabled ? "Armed" : "Idle"}
          </span>
          <Switch checked={bot.enabled} onCheckedChange={armBot} aria-label="Arm bot" />
        </div>
      </div>

      <div className="flex flex-col gap-3">
        <div className="flex flex-col gap-1.5">
          <Label>Strategy</Label>
          <Select value={bot.strategy} onValueChange={(v) => setBot({ strategy: v as StrategyId })}>
            <SelectTrigger>
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {STRATEGIES.map((id) => (
                <SelectItem key={id} value={id}>
                  {STRATEGY_META[id].label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          <p className="text-micro leading-snug text-muted-foreground">{meta.blurb}</p>
        </div>

        <Row label={`Risk ${bot.riskPct.toFixed(1)}%`}>
          <Slider
            min={0.25}
            max={3}
            step={0.25}
            value={[bot.riskPct]}
            onValueChange={([v]) => setBot({ riskPct: v ?? bot.riskPct })}
          />
        </Row>
        <Row label={`Max positions ${bot.maxPositions}`}>
          <Slider
            min={1}
            max={6}
            step={1}
            value={[bot.maxPositions]}
            onValueChange={([v]) => setBot({ maxPositions: v ?? bot.maxPositions })}
          />
        </Row>
        <div className="grid grid-cols-2 gap-3">
          <Row label={`SL ${bot.slAtrMult.toFixed(1)}× ATR`}>
            <Slider
              min={0.8}
              max={3}
              step={0.1}
              value={[bot.slAtrMult]}
              onValueChange={([v]) => setBot({ slAtrMult: v ?? bot.slAtrMult })}
            />
          </Row>
          <Row label={`TP ${bot.tpAtrMult.toFixed(1)}× ATR`}>
            <Slider
              min={1}
              max={4}
              step={0.1}
              value={[bot.tpAtrMult]}
              onValueChange={([v]) => setBot({ tpAtrMult: v ?? bot.tpAtrMult })}
            />
          </Row>
        </div>

        <div>
          <Label className="mb-2 block">Universe</Label>
          <div className="flex flex-wrap gap-1.5">
            {allPairIds().map((id) => {
              const on = bot.pairs.includes(id);
              return (
                <button
                  key={id}
                  type="button"
                  onClick={() => toggleBotPair(id)}
                  className={cn(
                    "h-8 rounded-md border px-2 text-2xs font-medium tracking-wide transition-colors duration-150",
                    on
                      ? "border-ring/40 bg-accent text-foreground"
                      : "border-border text-muted-foreground hover:bg-secondary",
                  )}
                >
                  {pairLabel(id)}
                </button>
              );
            })}
          </div>
        </div>

        <Button
          variant={bot.enabled ? "secondary" : "default"}
          size="lg"
          className="mt-1 w-full"
          onClick={() => armBot(!bot.enabled)}
        >
          {bot.enabled ? "Disarm bot" : "Arm bot"}
        </Button>
      </div>
    </section>
  );
}

function Row({ label, children }: { label: string; children: ReactNode }) {
  return (
    <div className="flex flex-col gap-2">
      <div className="flex items-center justify-between">
        <Label>{label}</Label>
      </div>
      {children}
    </div>
  );
}
