import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  RefreshControl,
  TouchableOpacity,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useQuery } from '@tanstack/react-query';
import { COLORS, FONT_SIZE, SPACING, RADIUS, TEXT, SHADOWS } from '../../theme';
import { useTheme } from '../../theme';
import { Spinner, EmptyState } from '../../components/ui';
import { analyticsAPI } from '../../services/api';
import { useTranslation } from '../../i18n';
import { ChatbotAnalytics } from '../../types';

export function AnalyticsScreen() {
  const { theme } = useTheme();
  const { t } = useTranslation();

  const { data, isLoading, refetch } = useQuery({
    queryKey: ['analytics-overview'],
    queryFn: analyticsAPI.overview,
  });

  if (isLoading) return <Spinner centered label={t.common.loading} />;

  const overview = data;
  const chatbots: ChatbotAnalytics[] = overview?.chatbots ?? [];
  const maxConvos = Math.max(...chatbots.map(c => c.conversations), 1);

  return (
    <SafeAreaView style={[styles.safe, { backgroundColor: theme.bg }]} edges={['bottom']}>
      <ScrollView
        contentContainerStyle={styles.scroll}
        showsVerticalScrollIndicator={false}
        refreshControl={
          <RefreshControl refreshing={isLoading} onRefresh={refetch} tintColor={COLORS.primary} />
        }>

        {/* Header */}
        <View style={styles.pageHeader}>
          <Text style={[styles.pageTitle, { color: theme.text }]}>{t.analytics.title}</Text>
          <Text style={[styles.pageSub, { color: theme.textSecondary }]}>{t.analytics.subtitle}</Text>
        </View>

        {/* Summary grid */}
        <View style={styles.summaryGrid}>
          <SummaryCard label={t.analytics.conversations} value={overview?.total_conversations ?? 0} icon="💬" color="#6366f1" theme={theme} />
          <SummaryCard label={t.analytics.messages} value={overview?.total_messages ?? 0} icon="✉️" color="#0ea5e9" theme={theme} />
          <SummaryCard label={t.analytics.chatbots} value={overview?.total_chatbots ?? 0} icon="🤖" color="#10b981" theme={theme} />
          <SummaryCard
            label={t.analytics.avg_conv}
            value={Number((overview?.avg_messages_per_conversation ?? 0).toFixed(1))}
            icon="📊"
            color="#f59e0b"
            theme={theme}
          />
        </View>

        {/* Per-chatbot breakdown */}
        {chatbots.length > 0 && (
          <>
            <Text style={[styles.sectionTitle, { color: theme.text }]}>{t.analytics.by_chatbot}</Text>
            {chatbots.map(bot => (
              <BotCard key={bot.chatbot_id} bot={bot} maxConvos={maxConvos} theme={theme} />
            ))}
          </>
        )}

        {chatbots.length === 0 && (
          <EmptyState
            icon={<Text style={{ fontSize: 48 }}>📊</Text>}
            title={t.analytics.empty_title}
            description={t.analytics.empty_desc}
          />
        )}
      </ScrollView>
    </SafeAreaView>
  );
}

function SummaryCard({
  label,
  value,
  icon,
  color,
  theme,
}: {
  label: string;
  value: number;
  icon: string;
  color: string;
  theme: any;
}) {
  return (
    <View style={[styles.summaryCard, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
      <View style={[styles.summaryIconBg, { backgroundColor: color + '18' }]}>
        <Text style={styles.summaryIcon}>{icon}</Text>
      </View>
      <Text style={[styles.summaryValue, { color: theme.text }]}>{value.toLocaleString()}</Text>
      <Text style={[styles.summaryLabel, { color: theme.textSecondary }]}>{label}</Text>
    </View>
  );
}

function BotCard({
  bot,
  maxConvos,
  theme,
}: {
  bot: ChatbotAnalytics;
  maxConvos: number;
  theme: any;
}) {
  const { t } = useTranslation();
  const [showGaps, setShowGaps] = React.useState(false);
  const pct = maxConvos > 0 ? (bot.conversations / maxConvos) * 100 : 0;
  const confidence = ((bot.avg_confidence ?? 0) * 100).toFixed(0);
  const unanswered = bot.unanswered_queries ?? [];

  return (
    <View style={[styles.botCard, { backgroundColor: theme.surface, borderColor: theme.border }, SHADOWS.sm]}>
      <View style={styles.botCardHeader}>
        <View style={[styles.botAvatar, { backgroundColor: COLORS.primaryUltraLight }]}>
          <Text style={[styles.botAvatarText, { color: COLORS.primaryDark }]}>
            {bot.chatbot_name[0]?.toUpperCase()}
          </Text>
        </View>
        <Text style={[styles.botName, { color: theme.text }]} numberOfLines={1}>{bot.chatbot_name}</Text>
      </View>

      <View style={styles.botStats}>
        <StatChip label={t.analytics.conversations} value={bot.conversations} theme={theme} />
        <StatChip label={t.analytics.messages} value={bot.messages} theme={theme} />
        <StatChip label={t.analytics.confidence} value={`${confidence}%`} theme={theme} />
      </View>

      {/* Bar */}
      <View>
        <View style={[styles.barTrack, { backgroundColor: theme.bgSecondary }]}>
          <View style={[styles.barFill, { width: `${pct}%` as any, backgroundColor: COLORS.primary }]} />
        </View>
        <Text style={[styles.barLabel, { color: theme.textMuted }]}>{bot.conversations} {t.analytics.conversations.toLowerCase()}</Text>
      </View>

      {/* Gap analysis */}
      {unanswered.length > 0 && (
        <View style={[gapStyles.section, { borderTopColor: theme.border }]}>
          <TouchableOpacity style={gapStyles.toggle} onPress={() => setShowGaps(v => !v)}>
            <View style={[gapStyles.badge, { backgroundColor: COLORS.warningBg }]}>
              <Text style={[gapStyles.badgeText, { color: COLORS.warning }]}>
                {t.analytics.unanswered(unanswered.length)}
              </Text>
            </View>
            <Text style={[gapStyles.toggleLabel, { color: theme.textSecondary }]}>
              {showGaps ? t.analytics.hide_gaps : t.analytics.show_gaps}
            </Text>
          </TouchableOpacity>
          {showGaps && unanswered.map((q, i) => (
            <View key={i} style={[gapStyles.queryRow, { borderBottomColor: theme.borderLight }]}>
              <Text style={[gapStyles.queryNum, { color: theme.textMuted }]}>{i + 1}.</Text>
              <Text style={[gapStyles.queryText, { color: theme.text }]}>{q.query}</Text>
              <View style={[gapStyles.countBadge, { backgroundColor: theme.bgSecondary }]}>
                <Text style={[gapStyles.countText, { color: theme.textSecondary }]}>{q.count}×</Text>
              </View>
            </View>
          ))}
        </View>
      )}
    </View>
  );
}

function StatChip({ label, value, theme }: { label: string; value: number | string; theme: any }) {
  return (
    <View style={[styles.statChip, { backgroundColor: theme.bgSecondary }]}>
      <Text style={[styles.statValue, { color: theme.text }]}>{value}</Text>
      <Text style={[styles.statLabel, { color: theme.textMuted }]}>{label}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  safe: { flex: 1 },
  scroll: { padding: SPACING.lg, gap: SPACING.lg, paddingBottom: SPACING.xxxl },

  pageHeader: { gap: 4 },
  pageTitle: { ...TEXT.h3 },
  pageSub: { ...TEXT.small },

  summaryGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: SPACING.sm },
  summaryCard: {
    width: '47.5%',
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.md,
    gap: SPACING.xs,
    alignItems: 'flex-start',
  },
  summaryIconBg: {
    width: 40,
    height: 40,
    borderRadius: RADIUS.md,
    alignItems: 'center',
    justifyContent: 'center',
  },
  summaryIcon: { fontSize: 20 },
  summaryValue: { fontSize: FONT_SIZE.xxl, fontWeight: '800', marginTop: SPACING.xs },
  summaryLabel: { ...TEXT.small },

  sectionTitle: { ...TEXT.h4 },

  botCard: {
    borderRadius: RADIUS.xl,
    borderWidth: 1,
    padding: SPACING.lg,
    gap: SPACING.md,
  },
  botCardHeader: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm },
  botAvatar: { width: 38, height: 38, borderRadius: RADIUS.full, alignItems: 'center', justifyContent: 'center' },
  botAvatarText: { fontSize: FONT_SIZE.md, fontWeight: '800' },
  botName: { ...TEXT.bodyM, flex: 1 },

  botStats: { flexDirection: 'row', gap: SPACING.sm },
  statChip: { flex: 1, alignItems: 'center', borderRadius: RADIUS.md, paddingVertical: SPACING.sm, gap: 2 },
  statValue: { fontSize: FONT_SIZE.lg, fontWeight: '700' },
  statLabel: { fontSize: FONT_SIZE.xs, textAlign: 'center' },

  barTrack: { height: 8, borderRadius: RADIUS.full, overflow: 'hidden' },
  barFill: { height: '100%', borderRadius: RADIUS.full },
  barLabel: { ...TEXT.caption, marginTop: 4 },
});

const gapStyles = StyleSheet.create({
  section: { borderTopWidth: 1, paddingTop: SPACING.md, gap: SPACING.xs },
  toggle: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  badge: { borderRadius: RADIUS.full, paddingVertical: 3, paddingHorizontal: SPACING.sm },
  badgeText: { fontSize: FONT_SIZE.xs, fontWeight: '700' },
  toggleLabel: { fontSize: FONT_SIZE.xs, fontWeight: '500' },
  queryRow: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: SPACING.xs,
    paddingVertical: SPACING.xs,
    borderBottomWidth: 1,
  },
  queryNum: { fontSize: FONT_SIZE.xs, width: 18, marginTop: 1 },
  queryText: { flex: 1, fontSize: FONT_SIZE.sm, lineHeight: 18 },
  countBadge: { borderRadius: RADIUS.sm, paddingHorizontal: SPACING.xs, paddingVertical: 2 },
  countText: { fontSize: FONT_SIZE.xs, fontWeight: '600' },
});
