import { useCallback, useEffect, useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import api from '../../core/api';
import { useSubscriptionRestriction } from '../../hooks/useSubscriptionRestriction';
import { ScreenLayout } from '../../components/ui/ScreenLayout';
import { Icon } from '../../components/ui/Icon';
import { colors, radii, spacing } from '../../constants/theme';

type Stat = { label: string; value: string | number; icon?: string };

export function DashboardScreen() {
  const { readOnly } = useSubscriptionRestriction();
  const [summary, setSummary] = useState<{
    welcome?: string;
    subtitle?: string;
    role?: string;
    stats?: Stat[];
  }>({});
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    if (readOnly) {
      setSummary({
        welcome: 'Dashboard',
        subtitle: 'Renew your subscription in Settings to restore dashboard access.',
        stats: [],
      });
      setLoading(false);
      return;
    }
    setLoading(true);
    try {
      const { data } = await api.get('/dashboard/summary');
      setSummary(data);
    } catch (e: unknown) {
      const err = e as { subscriptionRequired?: boolean };
      if (err.subscriptionRequired) {
        setSummary({
          welcome: 'Dashboard',
          subtitle: 'Renew your subscription in Settings to restore dashboard access.',
          stats: [],
        });
      } else {
        setSummary({ welcome: 'Dashboard', subtitle: 'Unable to load summary.' });
      }
    } finally {
      setLoading(false);
    }
  }, [readOnly]);

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

  return (
    <ScreenLayout
      title={summary.welcome || 'Dashboard'}
      subtitle={summary.subtitle}
      onRefresh={load}
      refreshing={loading}
    >
      <View style={styles.grid}>
        {(summary.stats || []).map((stat, i) => (
          <View key={i} style={styles.statCard}>
            <Icon name={stat.icon || 'dashboard'} color={colors.primary} />
            <Text style={styles.statValue}>{stat.value}</Text>
            <Text style={styles.statLabel}>{stat.label}</Text>
          </View>
        ))}
      </View>
      {!summary.stats?.length && !loading ? (
        <Text style={styles.muted}>No stats available for your role.</Text>
      ) : null}
    </ScreenLayout>
  );
}

const styles = StyleSheet.create({
  grid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  statCard: {
    width: '47%',
    backgroundColor: colors.surface,
    borderRadius: radii.md,
    padding: spacing.md,
    borderWidth: 1,
    borderColor: colors.border,
    gap: spacing.xs,
  },
  statValue: { fontSize: 22, fontWeight: '700', color: colors.text },
  statLabel: { fontSize: 13, color: colors.textMuted },
  muted: { color: colors.textMuted, textAlign: 'center', marginTop: spacing.lg },
});
