import React, { useMemo, useState } from "react";
import { View, TextInput, ScrollView, StyleSheet, RefreshControl } from "react-native";
import { useQuery } from "@tanstack/react-query";
import { Card, H1, Muted, Row, Body, Pill } from "@/components/ui";
import { colors, radii, spacing } from "@/theme";

// Delta REST tickers endpoint (public). No auth needed.
const DELTA_URL = "https://api.india.delta.exchange/v2/tickers";

type Ticker = {
  symbol: string; mark_price: string; close: string;
  turnover_usd?: string; oi?: string;
  high?: string; low?: string; change_24h?: string;
};

async function fetchTickers(): Promise<Ticker[]> {
  const res = await fetch(DELTA_URL);
  const json = await res.json();
  return (json?.result ?? []) as Ticker[];
}

export default function ScreenerScreen() {
  const [q, setQ] = useState("");
  const { data, refetch, isFetching } = useQuery({
    queryKey: ["delta-tickers"],
    queryFn: fetchTickers,
    refetchInterval: 15_000,
  });

  const rows = useMemo(() => {
    const list = data ?? [];
    const term = q.trim().toUpperCase();
    return list
      .filter((t) => t.symbol.endsWith("USD") || t.symbol.endsWith("USDT"))
      .filter((t) => !term || t.symbol.includes(term))
      .sort((a, b) => Number(b.turnover_usd ?? 0) - Number(a.turnover_usd ?? 0))
      .slice(0, 60);
  }, [data, q]);

  return (
    <ScrollView
      style={{ backgroundColor: colors.bg }}
      contentContainerStyle={{ padding: spacing.lg }}
      refreshControl={<RefreshControl refreshing={isFetching} onRefresh={() => refetch()} tintColor={colors.primary} />}
    >
      <H1>Screener</H1>
      <Muted>{rows.length} coins · sorted by turnover</Muted>
      <View style={{ height: spacing.md }} />
      <TextInput
        style={styles.input} value={q} onChangeText={setQ}
        placeholder="Search symbol (BTC, ETH…)" placeholderTextColor={colors.textDim}
        autoCapitalize="characters"
      />
      <View style={{ height: spacing.md }} />
      {rows.map((t) => {
        const chg = Number(t.change_24h ?? 0);
        return (
          <Card key={t.symbol}>
            <Row style={{ justifyContent: "space-between" }}>
              <View style={{ flex: 1 }}>
                <Row>
                  <Body style={{ fontWeight: "700" }}>{t.symbol}</Body>
                  <Pill label={chg >= 0 ? "UP" : "DOWN"} tone={chg >= 0 ? "long" : "short"} />
                </Row>
                <Muted>H {t.high ?? "—"} · L {t.low ?? "—"}</Muted>
              </View>
              <View style={{ alignItems: "flex-end" }}>
                <Body style={{ fontWeight: "700" }}>{Number(t.mark_price ?? t.close).toFixed(4)}</Body>
                <Muted style={{ color: chg >= 0 ? colors.long : colors.short }}>
                  {chg >= 0 ? "+" : ""}{chg.toFixed(2)}%
                </Muted>
              </View>
            </Row>
          </Card>
        );
      })}
    </ScrollView>
  );
}

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