import type { ReactNode } from "react";
import { X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { formatLots, formatPrice, formatSignedUsd, formatTime, pairLabel, sideLabel } from "@/lib/fx/format";
import { pipsBetween } from "@/lib/fx/pairs";
import { pnlOf, useDesk } from "@/store/desk";
import { cn } from "@/lib/utils";

export function BottomDock() {
  return (
    <Tabs defaultValue="positions" className="h-full min-h-0">
      <div className="flex items-center justify-between border-b border-border px-3">
        <TabsList className="bg-transparent p-0">
          <TabsTrigger value="positions" className="rounded-none border-b-2 border-transparent data-[state=active]:border-foreground data-[state=active]:bg-transparent">
            Positions
          </TabsTrigger>
          <TabsTrigger value="blotter" className="rounded-none border-b-2 border-transparent data-[state=active]:border-foreground data-[state=active]:bg-transparent">
            Blotter
          </TabsTrigger>
          <TabsTrigger value="log" className="rounded-none border-b-2 border-transparent data-[state=active]:border-foreground data-[state=active]:bg-transparent">
            Log
          </TabsTrigger>
        </TabsList>
        <span className="text-2xs uppercase tracking-[0.14em] text-muted-foreground">Paper fills</span>
      </div>
      <TabsContent value="positions" className="overflow-auto">
        <PositionsTable />
      </TabsContent>
      <TabsContent value="blotter" className="overflow-auto">
        <BlotterTable />
      </TabsContent>
      <TabsContent value="log" className="overflow-auto">
        <EventLog />
      </TabsContent>
    </Tabs>
  );
}

function PositionsTable() {
  const positions = useDesk((s) => s.positions);
  const market = useDesk((s) => s.market);
  const closePosition = useDesk((s) => s.closePosition);
  const lastFillId = useDesk((s) => s.lastFillId);

  if (!positions.length) {
    return <Empty>No open risk. Arm the bot or send a market order.</Empty>;
  }

  return (
    <table className="w-full min-w-[720px] text-left text-xs">
      <thead className="sticky top-0 bg-card text-2xs uppercase tracking-[0.12em] text-muted-foreground">
        <tr>
          <Th>Pair</Th>
          <Th>Side</Th>
          <Th>Lots</Th>
          <Th>Entry</Th>
          <Th>Mark</Th>
          <Th>Pips</Th>
          <Th>P&L</Th>
          <Th>SL</Th>
          <Th>TP</Th>
          <Th>Src</Th>
          <Th></Th>
        </tr>
      </thead>
      <tbody>
        {positions.map((p) => {
          const m = market[p.pair]!;
          const mark = p.side === "buy" ? m.bid : m.ask;
          const pips =
            p.side === "buy" ? pipsBetween(p.pair, mark, p.entry) : pipsBetween(p.pair, p.entry, mark);
          const pnl = pnlOf(p, market);
          return (
            <tr
              key={p.id}
              className={cn("border-t border-border", lastFillId === p.id && "bg-accent/60")}
            >
              <Td className="font-medium">{pairLabel(p.pair)}</Td>
              <Td>
                <Badge variant={p.side === "buy" ? "up" : "down"}>{sideLabel(p.side)}</Badge>
              </Td>
              <Td className="font-mono tabular">{formatLots(p.lots)}</Td>
              <Td className="font-mono tabular">{formatPrice(p.pair, p.entry)}</Td>
              <Td className="font-mono tabular">{formatPrice(p.pair, mark)}</Td>
              <Td className={cn("font-mono tabular", pips >= 0 ? "text-up" : "text-down")}>
                {pips.toFixed(1)}
              </Td>
              <Td className={cn("font-mono tabular", pnl >= 0 ? "text-up" : "text-down")}>
                {formatSignedUsd(pnl)}
              </Td>
              <Td className="font-mono tabular text-muted-foreground">
                {p.sl != null ? formatPrice(p.pair, p.sl) : "—"}
              </Td>
              <Td className="font-mono tabular text-muted-foreground">
                {p.tp != null ? formatPrice(p.pair, p.tp) : "—"}
              </Td>
              <Td className="uppercase text-muted-foreground">{p.source}</Td>
              <Td>
                <Button variant="ghost" size="icon" aria-label="Close position" onClick={() => closePosition(p.id)}>
                  <X className="size-3.5" />
                </Button>
              </Td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}

function BlotterTable() {
  const fills = useDesk((s) => s.fills);
  if (!fills.length) return <Empty>Fills will land here.</Empty>;
  return (
    <table className="w-full min-w-[640px] text-left text-xs">
      <thead className="sticky top-0 bg-card text-2xs uppercase tracking-[0.12em] text-muted-foreground">
        <tr>
          <Th>Time</Th>
          <Th>Pair</Th>
          <Th>Side</Th>
          <Th>Lots</Th>
          <Th>Price</Th>
          <Th>P&L</Th>
          <Th>Reason</Th>
          <Th>Src</Th>
        </tr>
      </thead>
      <tbody>
        {fills.map((f) => (
          <tr key={`${f.id}-${f.closedAt ?? f.openedAt}`} className="border-t border-border">
            <Td className="font-mono tabular text-muted-foreground">
              {formatTime(f.closedAt ?? f.openedAt)}
            </Td>
            <Td>{pairLabel(f.pair)}</Td>
            <Td>
              <Badge variant={f.side === "buy" ? "up" : "down"}>{sideLabel(f.side)}</Badge>
            </Td>
            <Td className="font-mono tabular">{formatLots(f.lots)}</Td>
            <Td className="font-mono tabular">{formatPrice(f.pair, f.price)}</Td>
            <Td
              className={cn(
                "font-mono tabular",
                f.pnl == null ? "text-muted-foreground" : f.pnl >= 0 ? "text-up" : "text-down",
              )}
            >
              {f.pnl == null ? "open" : formatSignedUsd(f.pnl)}
            </Td>
            <Td className="text-muted-foreground">{f.reason}</Td>
            <Td className="uppercase text-muted-foreground">{f.source}</Td>
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function EventLog() {
  const events = useDesk((s) => s.events);
  if (!events.length) return <Empty>Desk is quiet.</Empty>;
  return (
    <ul className="divide-y divide-border">
      {events.map((e) => (
        <li key={e.id} className="flex items-start gap-3 px-3 py-2 text-xs">
          <span className="font-mono tabular text-muted-foreground">{formatTime(e.t)}</span>
          <span
            className={cn(
              "min-w-0 flex-1 leading-snug",
              e.tone === "up" ? "text-up" : e.tone === "down" ? "text-down" : "text-foreground",
            )}
          >
            {e.text}
          </span>
        </li>
      ))}
    </ul>
  );
}

function Th({ children }: { children?: ReactNode }) {
  return <th className="px-3 py-2 font-medium">{children}</th>;
}

function Td({ children, className }: { children: ReactNode; className?: string }) {
  return <td className={cn("px-3 py-2 align-middle", className)}>{children}</td>;
}

function Empty({ children }: { children: ReactNode }) {
  return <p className="px-4 py-8 text-center text-sm text-muted-foreground">{children}</p>;
}
