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

const StorageDashboardScreen: React.FC = () => {
  const { colors, fonts } = useTheme();
  const selectedService = useSelector((s: RootState) => s.integrations.selectedService);

  const mock = useMemo(() => {
    const totalUsageGb = '824/2000'; // GB
    const filesCount = 58240;
    const sharedLinks = 312;
    const activeUsers = 86;
    const monthlyUsage = [620, 640, 660, 700, 760, 824]; // GB
    // Distribution within the active provider (file types)
    const typeDist = [
      { label: 'Images', value: 260, color: '#3AA0FF' },
      { label: 'Videos', value: 140, color: '#6366F1' },
      { label: 'Documents', value: 280, color: '#10B981' },
      { label: 'PDFs', value: 96, color: '#F59E0B' },
      { label: 'Others', value: 48, color: '#EF4444' },
    ];
    const recentActivity = [
      { name: 'Q3_Report.pdf', action: 'Shared', when: '2h ago' },
      { name: 'BrandAssets.zip', action: 'Uploaded', when: '5h ago' },
      { name: 'Sales-2025.xlsx', action: 'Edited', when: '1d ago' },
      { name: 'Engineering-Docs', action: 'Moved', when: '2d ago' },
    ];
    const topFolders = [
      { name: 'Product Design', size: 186 },
      { name: 'Client Deliverables', size: 152 },
      { name: 'Marketing Assets', size: 104 },
      { name: 'Engineering Docs', size: 88 },
    ];
    return { totalUsageGb, filesCount, sharedLinks, activeUsers, monthlyUsage, typeDist, recentActivity, topFolders };
  }, []);
  return (
    <Container>
      <View style={[styles.wrap, { backgroundColor: colors.background }]}> 
        <Text style={[styles.title, { color: colors.text, fontFamily: fonts.bold }]}>File Storage & Document Management</Text>

        {/* KPIs */}
        <View style={styles.kpiGrid}>
          <Kpi label="Total Usage" value={`${mock.totalUsageGb} GB`} color={colors.text} fonts={fonts} accent="#3AA0FF" />
          <Kpi label="Files" value={mock.filesCount.toLocaleString()} color={colors.text} fonts={fonts} accent="#10B981" />
          <Kpi label="Shared Links" value={String(mock.sharedLinks)} color={colors.text} fonts={fonts} accent="#F59E0B" />
          <Kpi label="Active Users" value={String(mock.activeUsers)} color={colors.text} fonts={fonts} accent="#6366F1" />
        </View>

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

        {/* File Types Distribution (scoped to current provider) */}
        <View style={[styles.card, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
          <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>File Types</Text>
          <Stacked segments={mock.typeDist} total={mock.typeDist.reduce((a, b) => a + b.value, 0)} />
          <View style={styles.legendRow}>
            {mock.typeDist.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 }]}>Recent Activity</Text>
            {mock.recentActivity.map(a => (
              <View key={`${a.name}-${a.when}`} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{a.name}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.medium }]}>{a.action} · {a.when}</Text>
              </View>
            ))}
          </View>
          <View style={[styles.card, styles.col, { borderColor: colors.border, backgroundColor: colors.surface }]}> 
            <Text style={[styles.cardTitle, { color: colors.text, fontFamily: fonts.medium }]}>Top Folders</Text>
            {mock.topFolders.map(f => (
              <View key={f.name} style={styles.listRow}>
                <Text style={[styles.listPrimary, { color: colors.text, fontFamily: fonts.regular }]}>{f.name}</Text>
                <Text style={[styles.listSecondary, { color: colors.text, fontFamily: fonts.medium }]}>{f.size} GB</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
    </Container>
  );
};

const styles = StyleSheet.create({
  wrap: { flex: 1, padding: 16 },
  title: { fontSize: 18, marginBottom: 8 },
  kpiGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between' },
  kpiCard: { width: '48%', borderRadius: 12, borderWidth: 1, borderColor: '#E2E8F0', backgroundColor: '#FFFFFF', padding: 12, marginBottom: 12 },
  kpiLabel: { fontSize: 12, opacity: 0.8 },
  kpiValueRow: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 8 },
  card: { borderRadius: 12, borderWidth: 1, padding: 12, marginTop: 12 },
  cardTitle: { fontSize: 16, marginBottom: 8 },
  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 },
});

export default StorageDashboardScreen;

// UI bits
const Kpi: React.FC<{ label: string; value: string; color: string; fonts: any; accent: string }> = ({ label, value, color, fonts, accent }) => {
  return (
    <View style={styles.kpiCard}>
      <Text style={[styles.kpiLabel, { color, fontFamily: fonts.regular }]}>{label}</Text>
      <View style={styles.kpiValueRow}>
        <Text style={{ color, fontSize: 20, fontFamily: fonts.bold }}>{value}</Text>
        <View style={{ width: 10, height: 10, borderRadius: 5, backgroundColor: accent }} />
      </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>
  );
};


