/**
 * CV6 AI Trading OS — Android App
 * React Native | Same design language as web frontend
 * Connects to the same FastAPI backend
 */

import React, { useState, useEffect, useCallback, useRef } from 'react'
import {
  View, Text, ScrollView, TouchableOpacity, StatusBar,
  SafeAreaView, ActivityIndicator, Dimensions, FlatList,
  StyleSheet, RefreshControl,
} from 'react-native'
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { API_BASE_URL, WS_BASE_URL, ENDPOINTS } from './config'

// ── Theme ────────────────────────────────────────────────────────────
const C = {
  bg:       '#070b14',
  panel:    '#0d1526',
  border:   '#1a2a4a',
  blue:     '#0ea5e9',
  cyan:     '#06b6d4',
  green:    '#22c55e',
  red:      '#ef4444',
  yellow:   '#f59e0b',
  text:     '#94a3b8',
  textBr:   '#e2e8f0',
  white:    '#ffffff',
}

// ── API client ───────────────────────────────────────────────────────
const api = axios.create({ baseURL: API_BASE_URL, timeout: 10000 })

const qc = new QueryClient({ defaultOptions: { queries: { refetchInterval: 5000, retry: 1 } } })

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

function Badge({ label, color }: { label: string; color: string }) {
  return (
    <View style={{ backgroundColor: color + '22', borderWidth: 1, borderColor: color + '66',
      paddingHorizontal: 6, paddingVertical: 2, borderRadius: 4 }}>
      <Text style={{ color, fontSize: 9, fontWeight: '700', letterSpacing: 1 }}>{label}</Text>
    </View>
  )
}

function Card({ children, style }: { children: React.ReactNode; style?: any }) {
  return (
    <View style={[{ backgroundColor: C.panel, borderWidth: 1, borderColor: C.border,
      borderRadius: 10, padding: 12, marginBottom: 10 }, style]}>
      {children}
    </View>
  )
}

function SectionHeader({ title, live }: { title: string; live?: boolean }) {
  return (
    <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, marginBottom: 10 }}>
      <Text style={{ color: C.textBr, fontSize: 11, fontWeight: '600',
        textTransform: 'uppercase', letterSpacing: 1, flex: 1 }}>{title}</Text>
      {live && <Badge label="LIVE" color={C.green} />}
    </View>
  )
}

// ── Screens ──────────────────────────────────────────────────────────

function DashboardScreen() {
  const { data: dash, isLoading, refetch } = useQuery({
    queryKey: ['dashboard'],
    queryFn: () => api.get('/dashboard/').then(r => r.data),
    refetchInterval: 8000,
  })
  const [refreshing, setRefreshing] = useState(false)
  const onRefresh = useCallback(async () => {
    setRefreshing(true)
    await refetch()
    setRefreshing(false)
  }, [refetch])

  if (isLoading) return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: C.bg }}>
      <ActivityIndicator color={C.blue} size="large" />
      <Text style={{ color: C.text, marginTop: 12, fontSize: 12 }}>Loading CV6 Dashboard...</Text>
    </View>
  )

  const pnl  = dash?.pnl
  const risk = dash?.risk
  const ai   = dash?.ai_status
  const h    = dash?.system_health
  const port = dash?.portfolio ?? []

  return (
    <ScrollView style={{ flex: 1, backgroundColor: C.bg, padding: 14 }}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={C.blue} />}>

      {/* PnL Card */}
      <Card>
        <SectionHeader title="P&L Summary" live />
        <View style={{ flexDirection: 'row', gap: 12 }}>
          {[
            { label: 'Realized',   val: pnl?.realized_pnl ?? 0 },
            { label: 'Unrealized', val: pnl?.unrealized_pnl ?? 0 },
            { label: 'Net P&L',    val: pnl?.net_pnl ?? 0 },
          ].map(({ label, val }) => (
            <View key={label} style={{ flex: 1, alignItems: 'center' }}>
              <Text style={{ color: val >= 0 ? C.green : C.red, fontSize: 14, fontWeight: '700',
                fontFamily: 'monospace' }}>
                ₹{Math.abs(val).toFixed(0)}
              </Text>
              <Text style={{ color: C.text, fontSize: 9, marginTop: 2 }}>{label}</Text>
            </View>
          ))}
        </View>
        <View style={{ marginTop: 10, flexDirection: 'row', justifyContent: 'space-between' }}>
          <Text style={{ color: C.text, fontSize: 10 }}>
            Wins: <Text style={{ color: C.green }}>{pnl?.winning_trades ?? 0}</Text>
            {'  '}Losses: <Text style={{ color: C.red }}>{pnl?.losing_trades ?? 0}</Text>
          </Text>
          <Text style={{ color: C.blue, fontSize: 10 }}>
            Win Rate: {(pnl?.win_rate_pct ?? 0).toFixed(1)}%
          </Text>
        </View>
      </Card>

      {/* AI Status */}
      <Card>
        <SectionHeader title="AI Consensus" live={ai?.enabled} />
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 10 }}>
          <View style={{ width: 8, height: 8, borderRadius: 4,
            backgroundColor: ai?.enabled ? C.green : C.red }} />
          <Text style={{ color: C.textBr, fontSize: 12, fontWeight: '600' }}>
            {ai?.enabled ? 'Active' : 'Offline'}
          </Text>
          <Text style={{ color: C.text, fontSize: 10, flex: 1 }}>
            {(ai?.active_models ?? []).join(' · ')}
          </Text>
        </View>
      </Card>

      {/* Risk */}
      {risk && (
        <Card>
          <SectionHeader title="Risk Monitor" />
          <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
            <View>
              <Text style={{ color: C.text, fontSize: 9 }}>Margin Used</Text>
              <Text style={{ color: C.yellow, fontSize: 16, fontWeight: '700' }}>
                {risk.margin_utilization_pct.toFixed(1)}%
              </Text>
            </View>
            <View>
              <Text style={{ color: C.text, fontSize: 9 }}>Exposure</Text>
              <Text style={{ color: C.textBr, fontSize: 14, fontWeight: '600' }}>
                ₹{risk.current_exposure.toFixed(0)}
              </Text>
            </View>
            <View>
              <Text style={{ color: C.text, fontSize: 9 }}>Status</Text>
              <Text style={{ color: risk.risk_status === 'OK' ? C.green : C.red, fontSize: 12, fontWeight: '700' }}>
                {risk.risk_status}
              </Text>
            </View>
          </View>
        </Card>
      )}

      {/* Positions */}
      <Card>
        <SectionHeader title="Open Positions" live />
        {port.length === 0 ? (
          <Text style={{ color: C.text, fontSize: 11, textAlign: 'center', padding: 20 }}>
            No open positions
          </Text>
        ) : port.slice(0, 5).map((p: any, i: number) => (
          <View key={i} style={{ flexDirection: 'row', justifyContent: 'space-between',
            paddingVertical: 6, borderBottomWidth: 1, borderBottomColor: C.border }}>
            <Text style={{ color: C.textBr, fontSize: 11, fontWeight: '600', flex: 1 }}>{p.symbol}</Text>
            <Text style={{ color: C.textBr, fontSize: 11, fontFamily: 'monospace' }}>{p.ltp?.toFixed(2)}</Text>
            <Text style={{ color: p.pnl >= 0 ? C.green : C.red, fontSize: 11, fontFamily: 'monospace',
              minWidth: 70, textAlign: 'right' }}>
              {p.pnl >= 0 ? '+' : ''}₹{Math.abs(p.pnl).toFixed(2)}
            </Text>
          </View>
        ))}
      </Card>

      {/* System Health */}
      {h && (
        <Card>
          <SectionHeader title="System Health" />
          <View style={{ flexDirection: 'row', justifyContent: 'space-around' }}>
            {[
              { label: 'CPU',    val: h.cpu_pct,    color: C.blue },
              { label: 'RAM',    val: h.memory_pct, color: C.cyan },
              { label: 'Disk',   val: h.disk_pct,   color: C.yellow },
            ].map(({ label, val, color }) => (
              <View key={label} style={{ alignItems: 'center' }}>
                <Text style={{ color, fontSize: 18, fontWeight: '700' }}>{Math.round(val)}%</Text>
                <Text style={{ color: C.text, fontSize: 9 }}>{label}</Text>
              </View>
            ))}
          </View>
          <Text style={{ color: C.green, fontSize: 9, textAlign: 'center', marginTop: 8 }}>
            ● {h.status} · Uptime {Math.floor(h.uptime_seconds / 3600)}h
          </Text>
        </Card>
      )}
    </ScrollView>
  )
}

function MarketWatchScreen() {
  const SYMBOLS = ['NIFTY 50','BANKNIFTY','RELIANCE','TCS','INFY','HDFCBANK','ICICIBANK','SBIN']
  const SEED: Record<string, any> = {
    'NIFTY 50':  { ltp: 24732.45, chg: 0.35 }, 'BANKNIFTY': { ltp: 52362.10, chg: 0.72 },
    'RELIANCE':  { ltp: 2950.40, chg: -0.12 }, 'TCS':       { ltp: 3718.65, chg: 0.28 },
    'INFY':      { ltp: 1956.80, chg: 0.41 },  'HDFCBANK':  { ltp: 1687.30, chg: 0.19 },
    'ICICIBANK': { ltp: 1232.70, chg: -0.25 }, 'SBIN':      { ltp: 812.45, chg: 0.53 },
  }
  return (
    <ScrollView style={{ flex: 1, backgroundColor: C.bg, padding: 14 }}>
      <Card>
        <SectionHeader title="Market Watch" live />
        {SYMBOLS.map((sym) => {
          const s = SEED[sym]
          const up = s.chg >= 0
          return (
            <View key={sym} style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 10,
              borderBottomWidth: 1, borderBottomColor: C.border }}>
              <Text style={{ color: C.textBr, fontSize: 12, fontWeight: '600', flex: 1 }}>{sym}</Text>
              <Text style={{ color: C.textBr, fontSize: 12, fontFamily: 'monospace', marginRight: 12 }}>
                {s.ltp.toFixed(2)}
              </Text>
              <Text style={{ color: up ? C.green : C.red, fontSize: 11, fontFamily: 'monospace', minWidth: 60, textAlign: 'right' }}>
                {up ? '+' : ''}{s.chg.toFixed(2)}%
              </Text>
            </View>
          )
        })}
      </Card>
    </ScrollView>
  )
}

// ── Tab Navigation ────────────────────────────────────────────────────

const TABS = ['Dashboard', 'Market', 'AI', 'History', 'Settings'] as const
type Tab = typeof TABS[number]

function BottomTab({ tabs, active, onPress }: { tabs: readonly string[]; active: string; onPress: (t: string) => void }) {
  return (
    <View style={{ flexDirection: 'row', backgroundColor: C.panel, borderTopWidth: 1, borderTopColor: C.border }}>
      {tabs.map((t) => (
        <TouchableOpacity key={t} onPress={() => onPress(t)}
          style={{ flex: 1, alignItems: 'center', paddingVertical: 10 }}>
          <Text style={{ fontSize: 18 }}>
            {t === 'Dashboard' ? '📊' : t === 'Market' ? '📈' : t === 'AI' ? '🧠' : t === 'History' ? '📋' : '⚙️'}
          </Text>
          <Text style={{ color: active === t ? C.blue : C.text, fontSize: 9, marginTop: 2, fontWeight: active === t ? '700' : '400' }}>
            {t}
          </Text>
        </TouchableOpacity>
      ))}
    </View>
  )
}

function App() {
  const [activeTab, setActiveTab] = useState<Tab>('Dashboard')

  const screen = () => {
    switch (activeTab) {
      case 'Dashboard': return <DashboardScreen />
      case 'Market':    return <MarketWatchScreen />
      default: return (
        <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: C.bg }}>
          <Text style={{ color: C.textBr, fontSize: 14 }}>{activeTab}</Text>
          <Text style={{ color: C.text, fontSize: 11, marginTop: 6 }}>Coming soon</Text>
        </View>
      )
    }
  }

  return (
    <QueryClientProvider client={qc}>
      <StatusBar barStyle="light-content" backgroundColor={C.panel} />
      <SafeAreaView style={{ flex: 1, backgroundColor: C.bg }}>
        {/* Header */}
        <View style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: C.panel,
          paddingHorizontal: 16, paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: C.border }}>
          <Text style={{ fontSize: 14, color: C.blue, fontWeight: '800', flex: 1 }}>CV6</Text>
          <Text style={{ fontSize: 10, color: C.text }}>AI TRADING OS</Text>
          <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: C.green, marginLeft: 12 }} />
        </View>
        {screen()}
        <BottomTab tabs={TABS} active={activeTab} onPress={(t) => setActiveTab(t as Tab)} />
      </SafeAreaView>
    </QueryClientProvider>
  )
}

export default App
