import { useQuery } from '@tanstack/react-query';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { useEffect, useState } from 'react';
import { ActivityIndicator, Pressable, RefreshControl, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { ScreenHeader } from '../../src/components/ScreenHeader';
import { api } from '../../src/lib/api';
import { getCustomer } from '../../src/lib/session';
import { syncWalletState } from '../../src/lib/walletSync';

function money(value: number) {
  return `₦${Number(value || 0).toLocaleString()}`;
}

function titleFor(item: any) {
  if (item.source === 'purchase') return 'Solar';
  if (item.source === 'airtime') return 'Airtime';
  if (item.source === 'data') return 'Data';
  if (item.source === 'funding') return 'Funding';
  if (item.source === 'withdrawal') return 'Withdrawal';
  return String(item.source ?? 'Transaction');
}

function iconFor(item: any) {
  if (item.source === 'purchase') return { name: 'solar-power', color: '#16A34A', bg: '#ECFDF3' };
  if (item.source === 'airtime') return { name: 'cellphone', color: '#7C3AED', bg: '#F3E8FF' };
  if (item.source === 'data') return { name: 'wifi', color: '#2563EB', bg: '#DBEAFE' };
  if (item.source === 'funding') return { name: 'wallet', color: '#D97706', bg: '#FEF3C7' };
  if (item.source === 'withdrawal') return { name: 'cash-minus', color: '#0891B2', bg: '#CFFAFE' };
  return { name: 'receipt-text', color: '#475569', bg: '#E2E8F0' };
}

export default function DashboardScreen() {
  const [bootComplete, setBootComplete] = useState(false);
  const customerQuery = useQuery({
    queryKey: ['customer'],
    queryFn: getCustomer,
  });

  const dashboardQuery = useQuery({
    queryKey: ['dashboard', customerQuery.data?.id],
    enabled: !!customerQuery.data?.id,
    refetchOnMount: 'always',
    refetchOnWindowFocus: true,
    refetchInterval: 30000,
    queryFn: async () => {
      const customer = customerQuery.data;
      const [summary, notifications, transactions] = await Promise.all([
        api.get('/dashboard/summary', { params: { customer_id: customer?.id } }),
        api.get('/notifications/index', { params: { customer_id: customer?.id } }),
        api.get('/transactions/index', { params: { customer_id: customer?.id } }),
      ]);

      return {
        summary: summary.data?.data,
        notifications: notifications.data?.data,
        transactions: transactions.data?.data?.transactions ?? [],
      };
    },
  });

  useEffect(() => {
    if (!customerQuery.isLoading && !customerQuery.data) {
      router.replace('/auth/login');
    }
  }, [customerQuery.data, customerQuery.isLoading]);

  useEffect(() => {
    const timer = setTimeout(() => setBootComplete(true), 4000);
    return () => clearTimeout(timer);
  }, []);

  const isLoading = !bootComplete && (customerQuery.isLoading || (dashboardQuery.isLoading && !dashboardQuery.data));
  const isRefreshing = dashboardQuery.isFetching && !!dashboardQuery.data;
  const customer = dashboardQuery.data?.summary?.customer ?? customerQuery.data;
  const summary = dashboardQuery.data?.summary?.summary ?? {};
  const summaryRecent = dashboardQuery.data?.summary?.recent ?? [];
  const recent = summaryRecent.length > 0 ? summaryRecent : (dashboardQuery.data?.transactions?.slice(0, 5) ?? []);
  const unreadCount = dashboardQuery.data?.notifications?.unread_count ?? dashboardQuery.data?.summary?.unread_count ?? 0;

  if (isLoading) {
    return (
      <View style={styles.loading}>
        <ActivityIndicator size="large" color="#16A34A" />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.safeArea} edges={['top']}>
      <ScrollView
        style={styles.container}
        contentContainerStyle={styles.content}
        refreshControl={
          <RefreshControl refreshing={dashboardQuery.isFetching} onRefresh={() => syncWalletState().then(() => dashboardQuery.refetch())} tintColor="#16A34A" />
        }
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.topBar}>
          <View style={{ flex: 1 }}>
            <Text style={styles.greeting}>Hello, {customer?.full_name?.split(' ')[0] ?? 'Customer'}</Text>
            <Text style={styles.subtitle}>Welcome back to PPay</Text>
          </View>
          <Pressable style={styles.bellButton} onPress={() => router.push('/(app)/notifications')}>
            <MaterialCommunityIcons name="bell-outline" size={22} color="#0F5132" />
            {unreadCount > 0 ? <View style={styles.badge}><Text style={styles.badgeText}>{unreadCount > 9 ? '9+' : unreadCount}</Text></View> : null}
          </Pressable>
        </View>
        {isRefreshing ? <Text style={styles.refreshingText}>Refreshing in the background...</Text> : null}

        <LinearGradient colors={['#16A34A', '#22C55E', '#15803D']} style={styles.walletCard}>
          <Text style={styles.walletLabel}>Wallet Balance</Text>
          <Text style={styles.walletAmount}>{money(customer?.wallet_balance ?? 0)}</Text>
          <Text style={styles.walletHint}>Available for solar, airtime, data and more</Text>
          {!customerQuery.data && !dashboardQuery.data ? <Text style={styles.walletHint}>Loading account data...</Text> : null}
          <View style={styles.walletActions}>
            <Pressable style={styles.primaryAction} onPress={() => router.push('/(app)/fund-wallet')}>
              <Text style={styles.primaryActionText}>Fund Wallet</Text>
            </Pressable>
            <Pressable style={styles.secondaryAction} onPress={() => router.push('/(app)/transactions')}>
              <Text style={styles.secondaryActionText}>History</Text>
            </Pressable>
          </View>
        </LinearGradient>

        <View style={styles.statsGrid}>
          <StatCard label="Total Purchase" value={money(summary.total_purchases ?? 0)} />
          <StatCard label="Total Funded" value={money(summary.total_funded ?? 0)} />
          <StatCard label="VTU Purchases" value={money((summary.total_airtime ?? 0) + (summary.total_data ?? 0))} />
          <StatCard label="Unread Alerts" value={String(unreadCount)} />
        </View>

        <SectionTitle title="Quick Actions" />
        <View style={styles.actionsGrid}>
          <ActionTile icon="solar-power" iconBg="#ECFDF3" iconColor="#16A34A" label="Solar PIN" onPress={() => router.push('/(app)/solar')} />
          <ActionTile icon="cellphone" iconBg="#F3E8FF" iconColor="#7C3AED" label="Airtime" onPress={() => router.push('/(app)/airtime')} />
          <ActionTile icon="wifi" iconBg="#DBEAFE" iconColor="#2563EB" label="Data" onPress={() => router.push('/(app)/data')} />
          <ActionTile icon="cash-minus" iconBg="#CFFAFE" iconColor="#0891B2" label="Withdrawal" onPress={() => router.push('/(app)/withdrawal')} />
          <ActionTile icon="list-status" iconBg="#EDE9FE" iconColor="#6D28D9" label="Transactions" onPress={() => router.push('/(app)/transactions')} />
          <ActionTile icon="account-circle-outline" iconBg="#FCE7F3" iconColor="#DB2777" label="Profile" onPress={() => router.push('/(app)/profile')} />
        </View>

        <SectionTitle title="Recent Activity" actionText="View All" onAction={() => router.push('/(app)/transactions')} />
        {recent.length === 0 ? (
          <View style={styles.emptyCard}>
            <Text style={styles.emptyText}>No transactions yet</Text>
          </View>
        ) : (
          recent.map((item: any, index: number) => {
            const icon = iconFor(item);
            return (
              <View key={`${item.source}-${item.reference ?? index}-${item.created_at}`} style={styles.txCard}>
                <View style={[styles.txIcon, { backgroundColor: icon.bg }]}>
                  <MaterialCommunityIcons name={icon.name as any} size={22} color={icon.color} />
                </View>
                <View style={styles.txBody}>
                  <View style={styles.txRow}>
                    <Text style={styles.txTitle}>{titleFor(item)}</Text>
                    <Text style={styles.txDate}>{String(item.created_at).replace('T', ' ').slice(0, 16)}</Text>
                  </View>
                  <Text style={styles.txDetails} numberOfLines={1}>{item.details}</Text>
                  <Text style={styles.txAmount}>{money(item.total_amount)}</Text>
                </View>
              </View>
            );
          })
        )}

        <View style={styles.spacer} />
      </ScrollView>
    </SafeAreaView>
  );
}

function SectionTitle({ title, actionText, onAction }: { title: string; actionText?: string; onAction?: () => void }) {
  return (
    <View style={styles.sectionHeader}>
      <Text style={styles.sectionTitle}>{title}</Text>
      {actionText && onAction ? (
        <Pressable onPress={onAction}>
          <Text style={styles.sectionAction}>{actionText}</Text>
        </Pressable>
      ) : null}
    </View>
  );
}

function StatCard({ label, value }: { label: string; value: string }) {
  return (
    <View style={styles.statCard}>
      <Text style={styles.statLabel}>{label}</Text>
      <Text style={styles.statValue}>{value}</Text>
    </View>
  );
}

function ActionTile({
  icon,
  iconBg,
  iconColor,
  label,
  onPress,
}: {
  icon: any;
  iconBg: string;
  iconColor: string;
  label: string;
  onPress: () => void;
}) {
  return (
    <Pressable style={styles.actionTile} onPress={onPress}>
      <View style={[styles.actionIcon, { backgroundColor: iconBg }]}>
        <MaterialCommunityIcons name={icon} size={22} color={iconColor} />
      </View>
      <Text style={styles.actionText}>{label}</Text>
    </Pressable>
  );
}

const styles = StyleSheet.create({
  safeArea: { flex: 1, backgroundColor: '#F4FAF7' },
  container: { flex: 1, backgroundColor: '#F4FAF7' },
  content: { paddingHorizontal: 20, paddingTop: 12, paddingBottom: 40 },
  loading: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#F4FAF7' },
  topBar: { flexDirection: 'row', alignItems: 'center', gap: 12, marginBottom: 16 },
  greeting: { color: '#062117', fontSize: 24, fontWeight: '900' },
  subtitle: { color: '#587267', marginTop: 2 },
  bellButton: { width: 46, height: 46, borderRadius: 16, backgroundColor: '#FFFFFF', alignItems: 'center', justifyContent: 'center' },
  badge: { position: 'absolute', top: 6, right: 6, minWidth: 18, height: 18, borderRadius: 9, backgroundColor: '#EF4444', alignItems: 'center', justifyContent: 'center', paddingHorizontal: 4 },
  badgeText: { color: '#FFFFFF', fontSize: 10, fontWeight: '800' },
  refreshingText: { color: '#587267', fontSize: 12, fontWeight: '700', marginBottom: 8 },
  walletCard: { borderRadius: 28, padding: 22, marginBottom: 18 },
  walletLabel: { color: '#E7FBEF', opacity: 0.9, fontSize: 14, fontWeight: '700' },
  walletAmount: { color: '#FFFFFF', fontSize: 38, fontWeight: '900', marginTop: 8 },
  walletHint: { color: '#ECFDF5', marginTop: 6, opacity: 0.9 },
  walletHintSmall: { color: '#ECFDF5', marginTop: 8, opacity: 0.85, fontSize: 12, fontWeight: '700' },
  walletActions: { flexDirection: 'row', gap: 10, marginTop: 18 },
  primaryAction: { backgroundColor: '#FFFFFF', paddingVertical: 12, paddingHorizontal: 16, borderRadius: 16 },
  primaryActionText: { color: '#0F5132', fontWeight: '800' },
  secondaryAction: { borderWidth: 1, borderColor: 'rgba(255,255,255,0.35)', paddingVertical: 12, paddingHorizontal: 16, borderRadius: 16 },
  secondaryActionText: { color: '#FFFFFF', fontWeight: '800' },
  statsGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: 12 },
  statCard: { width: '48%', backgroundColor: '#FFFFFF', borderRadius: 20, padding: 16, borderWidth: 1, borderColor: '#D8E7DF' },
  statLabel: { color: '#64748B', fontSize: 12, fontWeight: '700' },
  statValue: { color: '#062117', fontSize: 18, fontWeight: '900', marginTop: 8 },
  sectionHeader: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginTop: 22, marginBottom: 10 },
  sectionTitle: { color: '#062117', fontSize: 18, fontWeight: '900' },
  sectionAction: { color: '#16A34A', fontWeight: '800' },
  actionsGrid: { flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between', rowGap: 12, columnGap: 12 },
  actionTile: {
    flexBasis: '48%',
    flexGrow: 1,
    minWidth: 150,
    backgroundColor: '#FFFFFF',
    borderRadius: 18,
    paddingVertical: 16,
    paddingHorizontal: 12,
    alignItems: 'center',
    borderWidth: 1,
    borderColor: '#E3EFE8',
  },
  actionIcon: { width: 42, height: 42, borderRadius: 15, alignItems: 'center', justifyContent: 'center', marginBottom: 10 },
  actionText: { color: '#0F5132', fontSize: 12, fontWeight: '800', textAlign: 'center' },
  emptyCard: { backgroundColor: '#FFFFFF', borderRadius: 20, padding: 20, borderWidth: 1, borderColor: '#D8E7DF' },
  emptyText: { color: '#64748B' },
  txCard: { flexDirection: 'row', gap: 12, backgroundColor: '#FFFFFF', borderRadius: 20, padding: 14, marginBottom: 12, borderWidth: 1, borderColor: '#E3EFE8' },
  txIcon: { width: 44, height: 44, borderRadius: 16, alignItems: 'center', justifyContent: 'center' },
  txBody: { flex: 1 },
  txRow: { flexDirection: 'row', justifyContent: 'space-between', gap: 10 },
  txTitle: { color: '#062117', fontWeight: '900', flexShrink: 1 },
  txDate: { color: '#64748B', fontSize: 12 },
  txDetails: { color: '#475569', marginTop: 4 },
  txAmount: { color: '#0F5132', fontWeight: '900', marginTop: 8 },
  spacer: { height: 12 },
});
