import React, { useLayoutEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  ActivityIndicator,
  TouchableOpacity,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StatCard } from '../components/StatCard';
import { useStats } from '../hooks/useStats';

function formatTokens(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return String(n);
}

function formatCost(usd: number): string {
  if (usd >= 1) return `$${usd.toFixed(2)}`;
  return `$${usd.toFixed(4)}`;
}

export function DashboardScreen(): React.JSX.Element {
  const { stats, loading, error, refresh } = useStats();
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <TouchableOpacity onPress={refresh} style={styles.refreshBtn}>
          <Text style={styles.refreshText}>↻</Text>
        </TouchableOpacity>
      ),
    });
  }, [navigation, refresh]);

  if (loading && !stats) {
    return (
      <View style={styles.center}>
        <ActivityIndicator size="large" color="#7c3aed" />
        <Text style={styles.loadingText}>Loading stats…</Text>
      </View>
    );
  }

  if (error && !stats) {
    return (
      <View style={styles.center}>
        <Text style={styles.errorIcon}>⚠</Text>
        <Text style={styles.errorText}>{error}</Text>
        <TouchableOpacity onPress={refresh} style={styles.retryBtn}>
          <Text style={styles.retryText}>Retry</Text>
        </TouchableOpacity>
      </View>
    );
  }

  const savingRatio = stats?.saving_ratio ?? 0;
  const clampedRatio = Math.min(1, Math.max(0, savingRatio));

  return (
    <ScrollView style={styles.scroll} contentContainerStyle={styles.content}>
      {/* Stat grid */}
      <View style={styles.grid}>
        <View style={styles.row}>
          <StatCard
            value={stats ? formatTokens(stats.tokens_saved) : '—'}
            label="Tokens Saved"
            color="#7c3aed"
          />
          <View style={styles.gap} />
          <StatCard
            value={stats ? formatCost(stats.estimated_cost_saved_usd) : '—'}
            label="Est. Cost Saved"
            color="#22c55e"
          />
        </View>
        <View style={styles.rowSpacer} />
        <View style={styles.row}>
          <StatCard
            value={stats ? `${stats.avg_saving_pct.toFixed(1)}%` : '—'}
            label="Avg Saving %"
            color="#22c55e"
          />
          <View style={styles.gap} />
          <StatCard
            value={stats ? String(stats.total_requests) : '—'}
            label="Total Requests"
            color="#c9cdd8"
          />
        </View>
      </View>

      {/* Saving ratio bar */}
      <View style={styles.section}>
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>Match Rate</Text>
          <Text style={styles.sectionValue}>
            {stats ? `${(clampedRatio * 100).toFixed(0)}%` : '—'}
          </Text>
        </View>
        <View style={styles.trackOuter}>
          <View style={[styles.trackFill, { width: `${clampedRatio * 100}%` as `${number}%` }]} />
        </View>
        <View style={styles.trackLabels}>
          <Text style={styles.trackLabel}>
            {stats?.matched_requests ?? 0} matched
          </Text>
          <Text style={styles.trackLabel}>
            {stats?.total_requests ?? 0} total
          </Text>
        </View>
      </View>

      {/* Top Skill placeholder */}
      <View style={styles.section}>
        <Text style={styles.sectionTitle}>Top Skill</Text>
        <View style={styles.skillRow}>
          <Text style={styles.skillIcon}>🧩</Text>
          <View style={styles.skillInfo}>
            <Text style={styles.skillName}>—</Text>
            <Text style={styles.skillSub}>No data yet</Text>
          </View>
        </View>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  scroll: {
    flex: 1,
    backgroundColor: '#0f1117',
  },
  content: {
    padding: 16,
    paddingBottom: 32,
  },
  center: {
    flex: 1,
    backgroundColor: '#0f1117',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 12,
  },
  loadingText: {
    color: '#6b7280',
    fontSize: 14,
    marginTop: 8,
  },
  errorIcon: {
    fontSize: 32,
    color: '#ef4444',
  },
  errorText: {
    color: '#ef4444',
    fontSize: 14,
    textAlign: 'center',
    paddingHorizontal: 24,
  },
  retryBtn: {
    marginTop: 8,
    paddingHorizontal: 20,
    paddingVertical: 8,
    backgroundColor: '#1a1d27',
    borderRadius: 8,
    borderWidth: 1,
    borderColor: '#2a2d3a',
  },
  retryText: {
    color: '#7c3aed',
    fontWeight: '600',
  },
  refreshBtn: {
    marginRight: 16,
    padding: 4,
  },
  refreshText: {
    color: '#7c3aed',
    fontSize: 22,
    fontWeight: '700',
  },
  grid: {
    marginBottom: 20,
  },
  row: {
    flexDirection: 'row',
  },
  gap: {
    width: 12,
  },
  rowSpacer: {
    height: 12,
  },
  section: {
    backgroundColor: '#1a1d27',
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#2a2d3a',
    padding: 16,
    marginBottom: 16,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 10,
  },
  sectionTitle: {
    color: '#6b7280',
    fontSize: 11,
    textTransform: 'uppercase',
    letterSpacing: 0.8,
    fontWeight: '600',
  },
  sectionValue: {
    color: '#22c55e',
    fontSize: 14,
    fontWeight: '700',
  },
  trackOuter: {
    height: 8,
    backgroundColor: '#2a2d3a',
    borderRadius: 4,
    overflow: 'hidden',
  },
  trackFill: {
    height: '100%',
    backgroundColor: '#22c55e',
    borderRadius: 4,
  },
  trackLabels: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginTop: 6,
  },
  trackLabel: {
    color: '#6b7280',
    fontSize: 11,
  },
  skillRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 10,
    gap: 10,
  },
  skillIcon: {
    fontSize: 24,
  },
  skillInfo: {
    flex: 1,
  },
  skillName: {
    color: '#c9cdd8',
    fontSize: 15,
    fontWeight: '600',
  },
  skillSub: {
    color: '#6b7280',
    fontSize: 12,
    marginTop: 2,
  },
});
