import React, { useMemo } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Container } from '@/shared/components/ui';
import { useTheme } from '@/shared/styles/useTheme';

const CollabDashboardScreen: React.FC = () => {
  const { colors, fonts } = useTheme();

  const mock = useMemo(() => {
    const messagesToday = 4820;
    const activeChannels = 38;
    const mentions = 126;
    const calls = 24;
    const messageTrend = [540, 620, 580, 640, 710, 680];
    const heatmap = [
      [1, 2, 3, 2, 4, 1, 0],
      [0, 1, 2, 3, 2, 1, 2],
      [2, 3, 4, 5, 4, 3, 2],
      [1, 2, 3, 3, 2, 2, 1],
      [0, 1, 2, 1, 2, 3, 4],
    ]; // rows=weeks, cols=days
    const channelDist = [
      { label: 'General', value: 28, color: '#3AA0FF' },
      { label: 'Projects', value: 22, color: '#10B981' },
      { label: 'Support', value: 18, color: '#F59E0B' },
      { label: 'Social', value: 8, color: '#6366F1' },
      { label: 'Other', value: 6, color: '#EF4444' },
    ];
    const activeList = [
      { name: '#proj-alpha', unread: 18 },
      { name: '#support', unread: 12 },
      { name: '#marketing', unread: 9 },
      { name: '#random', unread: 4 },
    ];
    const mentionsList = [
      { user: 'Aarti', when: '2h', ctx: 'Please review the draft' },
      { user: 'Rahul', when: '5h', ctx: 'Meeting moved to 3 PM' },
      { user: 'Meera', when: '1d', ctx: 'Approved the change' },
    ];
    return { messagesToday, activeChannels, mentions, calls, messageTrend, heatmap, channelDist, activeList, mentionsList };
  }, []);
  return (
    <Container>
      <View style={[styles.wrap, { backgroundColor: colors.background }]}> 
        <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>Communication & Collaboration</Text>

        {/* KPI Pills */}
        <View style={styles.kpiRow}>
          <Pill label="Messages Today" value={mock.messagesToday.toLocaleString()} color={colors.text} fonts={fonts} bg="#E6F2FF" dot="#3AA0FF" />
          <Pill label="Active Channels" value={String(mock.activeChannels)} color={colors.text} fonts={fonts} bg="#E9FAF2" dot="#10B981" />
        </View>
        <View style={styles.kpiRow}>
          <Pill label="Mentions" value={String(mock.mentions)} color={colors.text} fonts={fonts} bg="#FFF4E6" dot="#F59E0B" />
          <Pill label="Calls" value={String(mock.calls)} color={colors.text} fonts={fonts} bg="#ECEBFF" dot="#6366F1" />
        </View>

        {/* Activity Heatmap */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Weekly Activity Heatmap</Text>
          <Heatmap data={mock.heatmap} baseColor="#3AA0FF" />
          <Text style={{ fontSize: 12, marginTop: 6, color: colors.text, fontFamily: fonts.regular }}>Rows represent weeks, columns represent days (Mon-Sun)</Text>
        </View>

        {/* Message Volume */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Message Volume</Text>
          <Bars data={mock.messageTrend} max={Math.max(...mock.messageTrend)} color="#3AA0FF" />
        </View>

        {/* Channel Distribution */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Channel Distribution</Text>
          <Stacked segments={mock.channelDist} total={mock.channelDist.reduce((a, b) => a + b.value, 0)} />
          <View style={styles.legendRow}>
            {mock.channelDist.map(s => (
              <View key={s.label} style={styles.legendItem}>
                <View style={[styles.legendDot, { backgroundColor: s.color }]} />
                <Text style={{ color: colors.text, fontFamily: fonts.regular }}>{s.label}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Lists */}
        <View style={styles.row}> 
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Active Channels</Text>
            {mock.activeList.map(c => (
              <View key={c.name} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{c.name}</Text>
                <Badge text={String(c.unread)} fonts={fonts} />
              </View>
            ))}
          </View>
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Recent Mentions</Text>
            {mock.mentionsList.map(m => (
              <View key={`${m.user}-${m.when}`} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{m.user}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.regular }]}>{m.ctx} · {m.when}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
    </Container>
  );
};

const styles = StyleSheet.create({
  wrap: { flex: 1, padding: 16 },
  title: { fontSize: 18, marginBottom: 8 },
  kpiRow: { flexDirection: 'row', justifyContent: 'space-between' },
  pill: { flex: 1, marginRight: 12, borderRadius: 12, paddingVertical: 12, paddingHorizontal: 14 },
  pillLast: { marginRight: 0 },
  pillTop: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' },
  dot: { width: 8, height: 8, borderRadius: 4 },
  pillLabel: { fontSize: 12, opacity: 0.8 },
  pillValue: { fontSize: 18, marginTop: 6 },
  card: { borderRadius: 12, borderWidth: 1, padding: 12, marginTop: 12 },
  cardTitle: { fontSize: 16, marginBottom: 8 },
  heatRow: { flexDirection: 'row', marginBottom: 6 },
  heatCell: { width: 14, height: 14, borderRadius: 3, marginRight: 6 },
  bars: { flexDirection: 'row', alignItems: 'flex-end' },
  bar: { flex: 1, marginRight: 6, borderTopLeftRadius: 4, borderTopRightRadius: 4 },
  legendRow: { flexDirection: 'row', flexWrap: 'wrap', marginTop: 8 },
  legendItem: { flexDirection: 'row', alignItems: 'center', marginRight: 12, marginTop: 6 },
  legendDot: { width: 8, height: 8, borderRadius: 4, marginRight: 6 },
  row: {  marginTop: 12 },
  col: { flex: 1, marginRight: 8 },
  listRow: { flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 10, borderBottomWidth: StyleSheet.hairlineWidth, borderColor: '#E5E7EB' },
  listPrimary: { fontSize: 14, flex: 1, paddingRight: 8 },
  listSecondary: { fontSize: 12 },
  badge: { backgroundColor: '#E6F2FF', borderRadius: 10, paddingHorizontal: 8, paddingVertical: 2 },
});

export default CollabDashboardScreen;

// UI pieces (no external deps)
const Pill: React.FC<{ label: string; value: string; color: string; fonts: any; bg: string; dot: string }> = ({ label, value, color, fonts, bg, dot }) => {
  return (
    <View style={[styles.pill, { backgroundColor: bg }]}> 
      <View style={styles.pillTop}>
        <Text style={[styles.pillLabel, { color, fontFamily: fonts.regular }]}>{label}</Text>
        <View style={[styles.dot, { backgroundColor: dot }]} />
      </View>
      <Text style={[styles.pillValue, { color, fontFamily: fonts.bold }]}>{value}</Text>
    </View>
  );
};

const Heatmap: React.FC<{ data: number[][]; baseColor: string }> = ({ data, baseColor }) => {
  const max = Math.max(1, ...data.flat());
  const tint = (val: number) => {
    const alpha = 0.2 + (val / max) * 0.8; // 0.2 - 1
    return `${baseColor}${Math.round(alpha * 255).toString(16).padStart(2, '0')}`; // add alpha to hex
  };
  return (
    <View>
      {data.map((row, i) => (
        <View key={i} style={styles.heatRow}>
          {row.map((v, j) => (
            <View key={j} style={[styles.heatCell, { backgroundColor: tint(v) }]} />
          ))}
        </View>
      ))}
    </View>
  );
};

const Bars: React.FC<{ data: number[]; max: number; color: string }> = ({ data, max, color }) => {
  return (
    <View style={styles.bars}>
      {data.map((v, i) => (
        <View key={i} style={[styles.bar, { height: Math.max(6, (v / Math.max(1, max)) * 64), backgroundColor: color }]} />
      ))}
    </View>
  );
};

const Stacked: React.FC<{ segments: { label: string; value: number; color: string }[]; total: number }> = ({ segments, total }) => {
  return (
    <View style={{ height: 12, borderRadius: 8, backgroundColor: '#E5E7EB', overflow: 'hidden', flexDirection: 'row', marginTop: 8 }}>
      {segments.map(s => (
        <View key={s.label} style={{ width: `${(s.value / Math.max(1, total)) * 100}%`, backgroundColor: s.color }} />
      ))}
    </View>
  );
};

const Badge: React.FC<{ text: string; fonts: any }> = ({ text, fonts }) => (
  <View style={styles.badge}>
    <Text style={{ fontSize: 12, fontFamily: fonts.medium }}>{text}</Text>
  </View>
);


