import type { ReactNode } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { formatPrice, pairLabel, sideLabel } from "@/lib/fx/format";
import { PAIRS } from "@/lib/fx/pairs";
import { useDesk } from "@/store/desk";

const LOT_PRESETS = [0.01, 0.1, 0.5, 1];

export function Ticket() {
  const selected = useDesk((s) => s.selected);
  const market = useDesk((s) => s.market[s.selected]);
  const ticket = useDesk((s) => s.ticket);
  const setTicket = useDesk((s) => s.setTicket);
  const marketOrder = useDesk((s) => s.marketOrder);
  const spec = PAIRS[selected];

  const fire = (side: "buy" | "sell") => {
    const res = marketOrder(side, ticket.lots, ticket.slPips, ticket.tpPips, "manual", "Manual market");
    if (!res.ok) {
      toast.error(res.error);
      return;
    }
    toast.success(`${sideLabel(side)} ${pairLabel(selected)} ${ticket.lots.toFixed(2)}`);
  };

  if (!market) return null;

  return (
    <section className="border-b border-border p-3 lg:p-4">
      <div className="mb-3 flex items-end justify-between">
        <div>
          <h2 className="text-sm font-medium">Market ticket</h2>
          <p className="text-micro text-muted-foreground">{pairLabel(selected)} · fill at bid / ask</p>
        </div>
        <div className="text-right font-mono text-xs tabular">
          <div className="text-up">{formatPrice(selected, market.ask)}</div>
          <div className="text-down">{formatPrice(selected, market.bid)}</div>
        </div>
      </div>

      <div className="grid grid-cols-3 gap-2">
        <Field label="Lots">
          <Input
            type="number"
            min={0.01}
            max={5}
            step={0.01}
            value={ticket.lots.toFixed(2)}
            onChange={(e) => setTicket({ lots: Number(e.target.value) })}
            className="font-mono tabular"
          />
        </Field>
        <Field label="SL pips">
          <Input
            type="number"
            min={0}
            step={1}
            value={ticket.slPips}
            onChange={(e) => setTicket({ slPips: Number(e.target.value) })}
            className="font-mono tabular"
          />
        </Field>
        <Field label="TP pips">
          <Input
            type="number"
            min={0}
            step={1}
            value={ticket.tpPips}
            onChange={(e) => setTicket({ tpPips: Number(e.target.value) })}
            className="font-mono tabular"
          />
        </Field>
      </div>

      <div className="mt-2 flex gap-1">
        {LOT_PRESETS.map((n) => (
          <button
            key={n}
            type="button"
            onClick={() => setTicket({ lots: n })}
            className={`h-8 flex-1 rounded-md border text-2xs font-mono tabular transition-colors duration-150 ${
              ticket.lots === n
                ? "border-ring/50 bg-accent text-foreground"
                : "border-border text-muted-foreground hover:bg-secondary"
            }`}
          >
            {n.toFixed(2)}
          </button>
        ))}
      </div>

      <div className="mt-3 grid grid-cols-2 gap-2">
        <Button variant="buy" size="lg" onClick={() => fire("buy")}>
          Buy market
        </Button>
        <Button variant="sell" size="lg" onClick={() => fire("sell")}>
          Sell market
        </Button>
      </div>
      <p className="mt-2 text-micro text-muted-foreground">
        Spread {spec.spreadPips.toFixed(1)} pips · SL/TP attached on fill
      </p>
    </section>
  );
}

function Field({ label, children }: { label: string; children: ReactNode }) {
  return (
    <label className="flex flex-col gap-1.5">
      <Label>{label}</Label>
      {children}
    </label>
  );
}
