// Simple chart screen: symbol picker + candlestick line chart via
// react-native-gifted-charts, with live tick updates from public REST.
import React, { useEffect, useMemo, useState } from "react";
import { View, TextInput, ScrollView, StyleSheet, ActivityIndicator, TouchableOpacity, Text, Alert } from "react-native";
import { useQuery } from "@tanstack/react-query";
import { LineChart } from "react-native-gifted-charts";
import { Card, H1, H2, Muted, Row, Pill, PrimaryButton, Body } from "@/components/ui";
import { colors, radii, spacing } from "@/theme";
import { api } from "@/api/client";

const CANDLES_URL = (sym: string) =>
  `https://api.india.delta.exchange/v2/history/candles?symbol=${encodeURIComponent(sym)}&resolution=15m&count=96`;

async function fetchCandles(sym: string) {
  const res = await fetch(CANDLES_URL(sym));
  const json = await res.json();
  return (json?.result ?? []) as Array<{ time: number; open: number; high: number; low: number; close: number }>;
}

export default function ChartScreen() {
  const [sym, setSym] = useState("BTCUSD");
  const [input, setInput] = useState("BTCUSD");
  const { data, isFetching, refetch } = useQuery({
    queryKey: ["candles", sym],
    queryFn: () => fetchCandles(sym),
    refetchInterval: 15_000,
  });

  const points = useMemo(() =>
    (data ?? []).slice().reverse().map((c) => ({ value: Number(c.close) })), [data]);

  const last = points.at(-1)?.value ?? 0;
  const first = points[0]?.value ?? 0;
  const chg = first ? ((last - first) / first) * 100 : 0;

  const takeTrade = (side: "LONG" | "SHORT") => {
    if (!last) return;
    const stop = side === "LONG" ? last * 0.985 : last * 1.015;
    const target = side === "LONG" ? last * 1.03 : last * 0.97;
    Alert.alert(`Open ${side} on ${sym}?`,
      `Entry ~${last.toFixed(4)}\nSL ${stop.toFixed(4)} · TP ${target.toFixed(4)}\nSize $100 · 5×`,
      [
        { text: "Cancel", style: "cancel" },
        { text: "Open", onPress: async () => {
          try {
            await api.placeManualTrade({
              coin_symbol: sym, position_side: side,
              entry_price: last, stop_loss: stop, take_profit: target,
              order_size_value: 100, leverage: 5, order_sizing_type: "FIXED_AMOUNT",
            });
            Alert.alert("Submitted");
          } catch (e: any) { Alert.alert("Failed", String(e?.message ?? e)); }
        } },
      ]);
  };

  return (
    <ScrollView style={{ backgroundColor: colors.bg }} contentContainerStyle={{ padding: spacing.lg }}>
      <H1>Chart</H1>
      <Muted>{sym} · 15m</Muted>
      <View style={{ height: spacing.md }} />
      <Row style={{ gap: spacing.sm }}>
        <TextInput
          style={styles.input} value={input} onChangeText={setInput}
          autoCapitalize="characters" placeholder="Symbol"
          placeholderTextColor={colors.textDim}
        />
        <TouchableOpacity onPress={() => setSym(input.trim().toUpperCase() || "BTCUSD")} style={styles.go}>
          <Text style={{ color: "#04120b", fontWeight: "700" }}>Load</Text>
        </TouchableOpacity>
      </Row>
      <View style={{ height: spacing.md }} />

      <Card>
        <Row style={{ justifyContent: "space-between" }}>
          <View>
            <H2>{last ? last.toFixed(4) : "—"}</H2>
            <Muted>Last close · 24-window</Muted>
          </View>
          <Pill label={`${chg >= 0 ? "+" : ""}${chg.toFixed(2)}%`} tone={chg >= 0 ? "long" : "short"} />
        </Row>
        <View style={{ height: spacing.md }} />
        {isFetching && !points.length ? (
          <ActivityIndicator color={colors.primary} />
        ) : (
          <LineChart
            data={points}
            hideDataPoints
            thickness={2}
            color={chg >= 0 ? colors.long : colors.short}
            startFillColor={chg >= 0 ? colors.long : colors.short}
            endFillColor={colors.bg}
            areaChart
            startOpacity={0.35}
            endOpacity={0.02}
            initialSpacing={0}
            hideRules
            yAxisTextStyle={{ color: colors.textMuted, fontSize: 10 }}
            xAxisLabelTextStyle={{ color: colors.textMuted, fontSize: 10 }}
            xAxisColor={colors.border}
            yAxisColor={colors.border}
            spacing={4}
            height={220}
          />
        )}
        <View style={{ height: spacing.md }} />
        <Row style={{ gap: spacing.sm }}>
          <View style={{ flex: 1 }}><PrimaryButton label="LONG" onPress={() => takeTrade("LONG")} /></View>
          <View style={{ flex: 1 }}><PrimaryButton label="SHORT" tone="danger" onPress={() => takeTrade("SHORT")} /></View>
        </Row>
        <View style={{ height: spacing.sm }} />
        <TouchableOpacity onPress={() => refetch()} style={{ alignSelf: "center" }}>
          <Muted>Refresh</Muted>
        </TouchableOpacity>
      </Card>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  input: {
    flex: 1, backgroundColor: colors.surface, color: colors.text,
    borderColor: colors.border, borderWidth: 1, borderRadius: radii.md,
    paddingHorizontal: spacing.md, paddingVertical: 10, fontSize: 15,
  },
  go: {
    backgroundColor: colors.primary, paddingHorizontal: spacing.lg,
    paddingVertical: 10, borderRadius: radii.md, justifyContent: "center",
  },
});
