import { useState, useEffect, useRef } from "react";
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, ReferenceLine } from "recharts";

// ─── Simulated live data (replace with real MT5 API/websocket in production) ───
function useSimulatedBot(strategy, params) {
  const [log, setLog] = useState([]);
  const [trades, setTrades] = useState([]);
  const [price, setPrice] = useState(1.08542);
  const [priceHistory, setPriceHistory] = useState(() =>
    Array.from({ length: 60 }, (_, i) => ({
      t: i,
      price: 1.0854 + (Math.random() - 0.5) * 0.003,
    }))
  );
  const [equity, setEquity] = useState(10000);
  const [running, setRunning] = useState(false);
  const tickRef = useRef(0);

  useEffect(() => {
    if (!running) return;
    const id = setInterval(() => {
      tickRef.current++;
      const t = tickRef.current;

      // Simulate price walk
      setPrice((p) => {
        const next = +(p + (Math.random() - 0.499) * 0.0003).toFixed(5);
        setPriceHistory((h) => [...h.slice(-99), { t, price: next }]);
        return next;
      });

      // Occasionally fire a signal
      if (t % 8 === 0) {
        const side = Math.random() > 0.5 ? "BUY" : "SELL";
        const entry = price;
        const pnl = (Math.random() - 0.45) * 30;
        const trade = {
          id: t,
          time: new Date().toLocaleTimeString(),
          side,
          entry: entry.toFixed(5),
          pnl: pnl.toFixed(2),
          status: pnl > 0 ? "WIN" : "LOSS",
        };
        setTrades((prev) => [trade, ...prev].slice(0, 30));
        setEquity((e) => +(e + pnl).toFixed(2));
        setLog((l) =>
          [
            `[${trade.time}] Signal: ${side} @ ${entry.toFixed(5)} → P&L: $${pnl.toFixed(2)}`,
            ...l,
          ].slice(0, 100)
        );
      }
    }, 800);
    return () => clearInterval(id);
  }, [running, price]);

  return { log, trades, price, priceHistory, equity, running, setRunning };
}

// ─── Components ───────────────────────────────────────────────────────────────

const STRATEGIES = ["MA_CROSSOVER", "RSI", "BOLLINGER", "MACD"];

const defaultParams = {
  MA_CROSSOVER: { fast_ma: 10, slow_ma: 50 },
  RSI: { rsi_period: 14, rsi_overbought: 70, rsi_oversold: 30 },
  BOLLINGER: { bb_period: 20, bb_std: 2.0 },
  MACD: { macd_fast: 12, macd_slow: 26, macd_signal: 9 },
};

function Badge({ children, color }) {
  const colors = {
    green: "bg-emerald-500/20 text-emerald-400 border-emerald-500/30",
    red: "bg-red-500/20 text-red-400 border-red-500/30",
    blue: "bg-sky-500/20 text-sky-400 border-sky-500/30",
    yellow: "bg-amber-500/20 text-amber-400 border-amber-500/30",
  };
  return (
    <span className={`px-2 py-0.5 text-xs rounded border font-mono ${colors[color]}`}>
      {children}
    </span>
  );
}

function StatCard({ label, value, sub, color = "white" }) {
  const textColor = { white: "text-white", green: "text-emerald-400", red: "text-red-400" }[color];
  return (
    <div className="bg-zinc-900 border border-zinc-700/60 rounded-xl p-4 flex flex-col gap-1">
      <span className="text-zinc-500 text-xs tracking-widest uppercase">{label}</span>
      <span className={`text-2xl font-bold font-mono ${textColor}`}>{value}</span>
      {sub && <span className="text-zinc-600 text-xs">{sub}</span>}
    </div>
  );
}

function ParamInput({ label, value, onChange }) {
  return (
    <label className="flex flex-col gap-1">
      <span className="text-zinc-400 text-xs">{label}</span>
      <input
        type="number"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        className="bg-zinc-800 border border-zinc-700 rounded px-2 py-1 text-sm text-white font-mono w-full focus:outline-none focus:border-sky-500"
      />
    </label>
  );
}

// ─── Main App ──────────────────────────────────────────────────────────────────

export default function App() {
  const [strategy, setStrategy] = useState("MA_CROSSOVER");
  const [params, setParams] = useState(defaultParams);
  const [symbol, setSymbol] = useState("EURUSD");
  const [lotSize, setLotSize] = useState(0.1);
  const [slPips, setSlPips] = useState(30);
  const [tpPips, setTpPips] = useState(60);
  const [dryRun, setDryRun] = useState(true);

  const { log, trades, price, priceHistory, equity, running, setRunning } = useSimulatedBot(strategy, params[strategy]);

  const winRate = trades.length
    ? ((trades.filter((t) => t.status === "WIN").length / trades.length) * 100).toFixed(1)
    : "—";
  const totalPnl = trades.reduce((s, t) => s + parseFloat(t.pnl), 0).toFixed(2);
  const equityColor = equity >= 10000 ? "green" : "red";

  function updateParam(strat, key, val) {
    setParams((p) => ({ ...p, [strat]: { ...p[strat], [key]: +val } }));
  }

  return (
    <div
      style={{
        fontFamily: "'IBM Plex Mono', 'Courier New', monospace",
        background: "#0a0a0f",
        minHeight: "100vh",
        color: "#e4e4e7",
      }}
    >
      {/* Google Fonts */}
      <style>{`@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600;700&display=swap');
      ::-webkit-scrollbar{width:4px;height:4px}::-webkit-scrollbar-track{background:#18181b}::-webkit-scrollbar-thumb{background:#3f3f46;border-radius:2px}
      `}</style>

      {/* Header */}
      <header className="border-b border-zinc-800 px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg bg-sky-500/20 border border-sky-500/40 flex items-center justify-center text-sky-400 text-sm">⬡</div>
          <div>
            <h1 className="text-white font-bold text-lg leading-none">ForexBot MT5</h1>
            <p className="text-zinc-500 text-xs mt-0.5">MetaTrader 5 · Live Trading Dashboard</p>
          </div>
        </div>
        <div className="flex items-center gap-3">
          <Badge color={dryRun ? "yellow" : "red"}>{dryRun ? "DRY RUN" : "LIVE"}</Badge>
          <Badge color={running ? "green" : "blue"}>{running ? "● RUNNING" : "○ STOPPED"}</Badge>
          <button
            onClick={() => setRunning((r) => !r)}
            className={`px-4 py-2 rounded-lg text-sm font-semibold transition-all ${
              running
                ? "bg-red-500/20 border border-red-500/40 text-red-400 hover:bg-red-500/30"
                : "bg-sky-500/20 border border-sky-500/40 text-sky-400 hover:bg-sky-500/30"
            }`}
          >
            {running ? "Stop Bot" : "Start Bot"}
          </button>
        </div>
      </header>

      <div className="grid grid-cols-[320px_1fr] gap-0 min-h-[calc(100vh-65px)]">

        {/* ── Sidebar Config ── */}
        <aside className="border-r border-zinc-800 p-5 flex flex-col gap-5 overflow-y-auto">
          <section>
            <h2 className="text-zinc-400 text-xs tracking-widest uppercase mb-3">Connection</h2>
            <div className="flex flex-col gap-2">
              <label className="flex flex-col gap-1">
                <span className="text-zinc-400 text-xs">Symbol</span>
                <select
                  value={symbol}
                  onChange={(e) => setSymbol(e.target.value)}
                  className="bg-zinc-800 border border-zinc-700 rounded px-2 py-1 text-sm text-white font-mono focus:outline-none focus:border-sky-500"
                >
                  {["EURUSD","GBPUSD","USDJPY","AUDUSD","USDCAD","USDCHF","NZDUSD"].map(s=>(
                    <option key={s}>{s}</option>
                  ))}
                </select>
              </label>
              <label className="flex items-center gap-2 cursor-pointer">
                <div
                  onClick={() => setDryRun((d) => !d)}
                  className={`w-10 h-5 rounded-full transition-all relative ${dryRun ? "bg-amber-500/40" : "bg-red-500/40"}`}
                >
                  <div className={`absolute top-0.5 w-4 h-4 rounded-full transition-all ${dryRun ? "left-0.5 bg-amber-400" : "left-5 bg-red-400"}`} />
                </div>
                <span className="text-xs text-zinc-400">Dry Run (no real trades)</span>
              </label>
            </div>
          </section>

          <section>
            <h2 className="text-zinc-400 text-xs tracking-widest uppercase mb-3">Strategy</h2>
            <div className="grid grid-cols-2 gap-1 mb-3">
              {STRATEGIES.map((s) => (
                <button
                  key={s}
                  onClick={() => setStrategy(s)}
                  className={`py-1.5 px-2 rounded text-xs transition-all ${
                    strategy === s
                      ? "bg-sky-500/30 border border-sky-500/60 text-sky-300"
                      : "bg-zinc-800 border border-zinc-700 text-zinc-400 hover:border-zinc-500"
                  }`}
                >
                  {s.replace("_", " ")}
                </button>
              ))}
            </div>

            {/* Dynamic params */}
            <div className="flex flex-col gap-2">
              {Object.entries(params[strategy]).map(([key, val]) => (
                <ParamInput
                  key={key}
                  label={key.replace(/_/g, " ")}
                  value={val}
                  onChange={(v) => updateParam(strategy, key, v)}
                />
              ))}
            </div>
          </section>

          <section>
            <h2 className="text-zinc-400 text-xs tracking-widest uppercase mb-3">Risk Management</h2>
            <div className="flex flex-col gap-2">
              <ParamInput label="Lot Size" value={lotSize} onChange={setLotSize} />
              <ParamInput label="Stop Loss (pips)" value={slPips} onChange={setSlPips} />
              <ParamInput label="Take Profit (pips)" value={tpPips} onChange={setTpPips} />
            </div>
          </section>

          <div className="mt-auto text-zinc-600 text-xs leading-relaxed border-t border-zinc-800 pt-4">
            Connect this UI to <code className="text-zinc-400">trading_bot.py</code> via a local WebSocket or REST server for live data.
          </div>
        </aside>

        {/* ── Main Panel ── */}
        <main className="flex flex-col overflow-hidden">

          {/* Stats row */}
          <div className="grid grid-cols-4 gap-3 p-5 border-b border-zinc-800">
            <StatCard label="Live Price" value={price.toFixed(5)} sub={symbol} />
            <StatCard label="Equity" value={`$${equity.toLocaleString()}`} sub="Starting: $10,000" color={equityColor} />
            <StatCard label="Total P&L" value={`$${totalPnl}`} sub={`${trades.length} trades`} color={parseFloat(totalPnl) >= 0 ? "green" : "red"} />
            <StatCard label="Win Rate" value={`${winRate}%`} sub="Closed trades" color="white" />
          </div>

          {/* Price chart */}
          <div className="p-5 border-b border-zinc-800">
            <div className="flex items-center justify-between mb-3">
              <span className="text-zinc-400 text-xs tracking-widest uppercase">{symbol} Price Feed</span>
              <span className="text-zinc-600 text-xs">Last 100 ticks</span>
            </div>
            <ResponsiveContainer width="100%" height={160}>
              <LineChart data={priceHistory}>
                <XAxis dataKey="t" hide />
                <YAxis domain={["auto","auto"]} tick={{ fontSize: 10, fill: "#52525b" }} width={60} />
                <Tooltip
                  contentStyle={{ background: "#18181b", border: "1px solid #3f3f46", fontSize: 11 }}
                  formatter={(v) => [v.toFixed(5), "Price"]}
                  labelFormatter={() => ""}
                />
                <Line type="monotone" dataKey="price" stroke="#38bdf8" strokeWidth={1.5} dot={false} />
              </LineChart>
            </ResponsiveContainer>
          </div>

          <div className="grid grid-cols-2 flex-1 min-h-0">
            {/* Trade history */}
            <div className="border-r border-zinc-800 flex flex-col">
              <div className="px-5 py-3 border-b border-zinc-800">
                <span className="text-zinc-400 text-xs tracking-widest uppercase">Trade History</span>
              </div>
              <div className="overflow-y-auto flex-1">
                {trades.length === 0 ? (
                  <div className="text-zinc-600 text-xs p-5">No trades yet. Start the bot to begin.</div>
                ) : (
                  <table className="w-full text-xs">
                    <thead>
                      <tr className="text-zinc-600 border-b border-zinc-800">
                        {["Time","Side","Entry","P&L","Result"].map(h=>(
                          <th key={h} className="px-4 py-2 text-left font-normal">{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {trades.map((t) => (
                        <tr key={t.id} className="border-b border-zinc-800/50 hover:bg-zinc-800/30">
                          <td className="px-4 py-2 text-zinc-500">{t.time}</td>
                          <td className="px-4 py-2">
                            <Badge color={t.side === "BUY" ? "green" : "red"}>{t.side}</Badge>
                          </td>
                          <td className="px-4 py-2 text-zinc-300">{t.entry}</td>
                          <td className={`px-4 py-2 font-mono ${parseFloat(t.pnl) >= 0 ? "text-emerald-400" : "text-red-400"}`}>
                            {parseFloat(t.pnl) >= 0 ? "+" : ""}${t.pnl}
                          </td>
                          <td className="px-4 py-2">
                            <Badge color={t.status === "WIN" ? "green" : "red"}>{t.status}</Badge>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                )}
              </div>
            </div>

            {/* Log */}
            <div className="flex flex-col">
              <div className="px-5 py-3 border-b border-zinc-800">
                <span className="text-zinc-400 text-xs tracking-widest uppercase">Bot Log</span>
              </div>
              <div className="overflow-y-auto flex-1 p-4 flex flex-col gap-1">
                {log.length === 0 ? (
                  <span className="text-zinc-600 text-xs">Waiting for signals…</span>
                ) : (
                  log.map((l, i) => (
                    <div key={i} className={`text-xs font-mono ${
                      l.includes("BUY") ? "text-emerald-400" :
                      l.includes("SELL") ? "text-red-400" :
                      "text-zinc-500"
                    }`}>{l}</div>
                  ))
                )}
              </div>
            </div>
          </div>
        </main>
      </div>
    </div>
  );
}
