import React from "react";
import { View, ScrollView, RefreshControl, 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";

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

  const approve = (id: string) =>
    Alert.alert("Approve signal?", "This will open a position.", [
      { text: "Cancel", style: "cancel" },
      { text: "Approve", onPress: async () => {
        try { await api.approveSignal(id); await refresh(); }
        catch (e: any) { Alert.alert("Failed", String(e?.message ?? e)); }
      } },
    ]);

  const reject = async (id: string) => {
    try { await api.rejectSignal(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>Pending signals</H1>
      <Muted>{signals.length} awaiting review</Muted>
      <View style={{ height: spacing.md }} />
      {signals.length === 0 && <Muted>No pending signals — waiting for the strategy engine.</Muted>}
      {signals.map((s) => {
        const conf = Math.round((s.confidence ?? 0) * 100);
        return (
          <Card key={s._id}>
            <Row style={{ justifyContent: "space-between" }}>
              <View style={{ flex: 1 }}>
                <Row>
                  <Body style={{ fontWeight: "700" }}>{s.coin_symbol}</Body>
                  <Pill label={s.position_side} tone={s.position_side === "LONG" ? "long" : "short"} />
                  {s.algo_name && <Pill label={s.algo_name} tone="primary" />}
                </Row>
                <Muted>Entry {s.entry_price} · SL {s.stop_loss} · TP {s.take_profit}</Muted>
                <Muted>{s.leverage}× · {s.timeframe ?? "—"}</Muted>
              </View>
              <View style={{ alignItems: "flex-end" }}>
                <H2 style={{ color: conf >= 65 ? colors.long : colors.warn }}>{conf}%</H2>
                <Muted>confidence</Muted>
              </View>
            </Row>
            <View style={{ height: spacing.sm }} />
            <Muted>{s.rationale}</Muted>
            <View style={{ height: spacing.md }} />
            <Row style={{ gap: spacing.sm }}>
              <View style={{ flex: 1 }}>
                <PrimaryButton label="Approve" onPress={() => approve(s._id)} />
              </View>
              <View style={{ flex: 1 }}>
                <PrimaryButton label="Reject" tone="muted" onPress={() => reject(s._id)} />
              </View>
            </Row>
          </Card>
        );
      })}
    </ScrollView>
  );
}
