import React from "react";
import { View, ScrollView, StyleSheet, RefreshControl, Text, Alert } from "react-native";
import { Card, H1, H2, Muted, Body, Pill, Row, PrimaryButton } from "@/components/ui";
import { colors, spacing } from "@/theme";
import { useBackendStream } from "@/hooks/useBackendStream";
import { api } from "@/api/client";

function fmt(n: number | undefined, digits = 2) {
  if (n == null || Number.isNaN(n)) return "—";
  return Number(n).toLocaleString(undefined, { maximumFractionDigits: digits });
}

export default function DashboardScreen() {
  const { positions, account, connected, refresh } = useBackendStream();
  const [busy, setBusy] = React.useState(false);
  const onRefresh = async () => { setBusy(true); await refresh(); setBusy(false); };

  const totalPnl = positions.reduce((s, p) => s + (p.pnl ?? 0), 0);
  const live = positions.filter((p) => p.execution_mode !== "paper").length;
  const paper = positions.length - live;

  const close = (id: string) =>
    Alert.alert("Close position?", "Market close now.", [
      { text: "Cancel", style: "cancel" },
      { text: "Close", style: "destructive", onPress: async () => {
        try { await api.closePosition(id); await refresh(); }
        catch (e: any) { Alert.alert("Failed", String(e?.message ?? e)); }
      } },
    ]);

  return (
    <ScrollView
      style={{ backgroundColor: colors.bg }}
      contentContainerStyle={{ padding: spacing.lg }}
      refreshControl={<RefreshControl refreshing={busy} onRefresh={onRefresh} tintColor={colors.primary} />}
    >
      <H1>Dashboard</H1>
      <Muted>{connected ? "Live stream connected" : "Connecting…"}</Muted>

      <View style={{ height: spacing.md }} />

      <Row style={{ gap: spacing.sm }}>
        <Card style={styles.kpi}>
          <Muted>Wallet</Muted>
          <Text style={styles.kpiVal}>{account?.balance != null ? `$${fmt(account.balance)}` : "—"}</Text>
          <Muted>{account?.currency ?? ""}</Muted>
        </Card>
        <Card style={styles.kpi}>
          <Muted>Open PnL</Muted>
          <Text style={[styles.kpiVal, { color: totalPnl >= 0 ? colors.long : colors.short }]}>
            {totalPnl >= 0 ? "+" : ""}{fmt(totalPnl)}
          </Text>
          <Muted>{positions.length} positions</Muted>
        </Card>
      </Row>

      <Row style={{ gap: spacing.sm }}>
        <Pill label={`${live} live`} tone="primary" />
        <Pill label={`${paper} paper`} tone="warn" />
      </Row>

      <View style={{ height: spacing.md }} />
      <H2>Active positions</H2>
      {positions.length === 0 && <Muted>No open positions.</Muted>}
      {positions.map((p) => (
        <Card key={p._id}>
          <Row style={{ justifyContent: "space-between" }}>
            <View style={{ flex: 1 }}>
              <Row>
                <Body style={{ fontWeight: "700" }}>{p.coin_symbol}</Body>
                <Pill label={p.position_side} tone={p.position_side === "LONG" ? "long" : "short"} />
                <Pill label={p.execution_mode === "paper" ? "Paper" : "Live"} tone={p.execution_mode === "paper" ? "warn" : "primary"} />
              </Row>
              <Muted>Entry {fmt(p.entry_price, 4)} · Now {fmt(p.current_price, 4)} · {p.leverage}×</Muted>
              <Muted>SL {fmt(p.stop_loss, 4)} · TP {fmt(p.take_profit, 4)}</Muted>
            </View>
            <View style={{ alignItems: "flex-end" }}>
              <Text style={{ color: p.pnl >= 0 ? colors.long : colors.short, fontWeight: "700" }}>
                {p.pnl >= 0 ? "+" : ""}{fmt(p.pnl)}
              </Text>
              <Muted>{(p.pnl_pct ?? 0).toFixed(2)}%</Muted>
            </View>
          </Row>
          <View style={{ height: spacing.sm }} />
          <PrimaryButton label="Close" tone="danger" onPress={() => close(p._id)} />
        </Card>
      ))}
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  kpi: { flex: 1 },
  kpiVal: { color: colors.text, fontSize: 22, fontWeight: "700", marginVertical: 2 },
});
