import React, { useState, useEffect } from 'react'
import {
  View, Text, ScrollView, StyleSheet,
  TouchableOpacity, RefreshControl,
} from 'react-native'
import { apiFetch } from '../lib/api'

interface StatCardProps {
  label: string
  value: string
  color: string
  icon: string
}

function StatCard({ label, value, color, icon }: StatCardProps) {
  return (
    <View style={[styles.statCard, { borderLeftColor: color }]}>
      <Text style={styles.statIcon}>{icon}</Text>
      <Text style={[styles.statValue, { color }]}>{value}</Text>
      <Text style={styles.statLabel}>{label}</Text>
    </View>
  )
}

export default function DashboardScreen() {
  const [data, setData]         = useState<any>(null)
  const [refreshing, setRefreshing] = useState(false)

  async function load() {
    try {
      const [invData] = await Promise.all([
        apiFetch('/invoices?limit=200'),
      ])
      const invoices = invData.items ?? []
      const sent    = invoices.filter((i: any) => i.status === 'sent')
      const paid    = invoices.filter((i: any) => i.status === 'paid')
      setData({
        outstanding: sent.reduce((s: number, i: any) => s + i.total, 0),
        collected:   paid.reduce((s: number, i: any) => s + (i.paidAmount ?? i.total), 0),
        sentCount:   sent.length,
        paidCount:   paid.length,
      })
    } catch (e) {
      // ignore — show empty state
    }
  }

  useEffect(() => { load() }, [])

  const onRefresh = async () => { setRefreshing(true); await load(); setRefreshing(false) }
  const fmt = (n: number) => new Intl.NumberFormat('th-TH', { maximumFractionDigits: 0 }).format(n)

  return (
    <ScrollView
      style={styles.container}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor='#0D9394' />}
    >
      <View style={styles.header}>
        <Text style={styles.greeting}>GPS Legal</Text>
        <Text style={styles.subGreeting}>Practice Overview</Text>
      </View>

      {data ? (
        <View style={styles.statsRow}>
          <StatCard label='Outstanding' value={`฿${fmt(data.outstanding)}`} color='#FF9F43' icon='⏳' />
          <StatCard label='Collected'  value={`฿${fmt(data.collected)}`}   color='#0D9394' icon='✅' />
        </View>
      ) : (
        <View style={styles.emptyCard}>
          <Text style={styles.emptyText}>Loading…</Text>
        </View>
      )}

      <Text style={styles.sectionTitle}>Quick Actions</Text>
      <View style={styles.actionsGrid}>
        {[
          { label: 'Log Time',        icon: '⏱' },
          { label: 'Add Expense',     icon: '🧾' },
          { label: 'Scan Document',   icon: '📷' },
          { label: 'AI Assistant',    icon: '🤖' },
        ].map(action => (
          <TouchableOpacity key={action.label} style={styles.actionCard}>
            <Text style={styles.actionIcon}>{action.icon}</Text>
            <Text style={styles.actionLabel}>{action.label}</Text>
          </TouchableOpacity>
        ))}
      </View>
    </ScrollView>
  )
}

const styles = StyleSheet.create({
  container:    { flex: 1, backgroundColor: '#F9FAFB' },
  header:       { padding: 20, paddingTop: 8 },
  greeting:     { fontSize: 22, fontWeight: '700', color: '#0D9394' },
  subGreeting:  { fontSize: 13, color: '#6B7280', marginTop: 2 },
  statsRow:     { flexDirection: 'row', gap: 12, paddingHorizontal: 16, marginBottom: 8 },
  statCard:     { flex: 1, backgroundColor: '#fff', borderRadius: 12, padding: 14, borderLeftWidth: 3, shadowColor: '#000', shadowOpacity: 0.05, shadowRadius: 6, elevation: 2 },
  statIcon:     { fontSize: 18, marginBottom: 4 },
  statValue:    { fontSize: 18, fontWeight: '700', fontVariant: ['tabular-nums'] },
  statLabel:    { fontSize: 11, color: '#6B7280', marginTop: 2 },
  emptyCard:    { margin: 16, padding: 20, backgroundColor: '#fff', borderRadius: 12, alignItems: 'center' },
  emptyText:    { color: '#9CA3AF', fontSize: 14 },
  sectionTitle: { fontSize: 13, fontWeight: '700', color: '#6B7280', marginTop: 12, marginBottom: 8, paddingHorizontal: 16, letterSpacing: 0.5 },
  actionsGrid:  { flexDirection: 'row', flexWrap: 'wrap', gap: 12, paddingHorizontal: 16 },
  actionCard:   { width: '45%', backgroundColor: '#fff', borderRadius: 12, padding: 16, alignItems: 'center', shadowColor: '#000', shadowOpacity: 0.05, shadowRadius: 6, elevation: 2 },
  actionIcon:   { fontSize: 26, marginBottom: 8 },
  actionLabel:  { fontSize: 13, fontWeight: '600', color: '#374151' },
})
