import React, { useState, useCallback, useRef, useEffect } from 'react';
import { View, Text, ScrollView, StyleSheet, RefreshControl, TouchableOpacity, StatusBar, Animated } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { useAuth } from '../../hooks/useAuth';
import { useResponsive } from '../../hooks/useResponsive';
import { reportService } from '../../services/reportService';
import { adminService } from '../../services/adminService';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { StatusBadge } from '../../components/common/StatusBadge';
import { SkeletonDashboard } from '../../components/ui/Skeleton';
import { colors, spacing, radii, shadows } from '../../theme';
import { DashboardStats, User } from '../../types';

export default function DashboardScreen() {
  const navigation = useNavigation<any>();
  const insets = useSafeAreaInsets();
  const { user, isAdmin } = useAuth();
  const { contentPadding, fontSize, cardColumns, isPhone } = useResponsive();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const headerFade = useRef(new Animated.Value(0)).current;
  const headerSlide = useRef(new Animated.Value(-10)).current;

  useEffect(() => {
    Animated.parallel([
      Animated.timing(headerFade, { toValue: 1, duration: 400, useNativeDriver: true }),
      Animated.timing(headerSlide, { toValue: 0, duration: 400, useNativeDriver: true }),
    ]).start();
  }, []);

  const loadData = async () => {
    try {
      const [statsData, usersData] = await Promise.all([
        reportService.dashboard().catch(() => null),
        isAdmin ? adminService.users().catch(() => []) : Promise.resolve([]),
      ]);
      setStats(statsData);
      setUsers(usersData);
    } catch {
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  useFocusEffect(useCallback(() => { loadData(); }, []));

  const onRefresh = () => { setRefreshing(true); loadData(); };

  if (loading) return <SkeletonDashboard />;

  const greeting = () => {
    const h = new Date().getHours();
    if (h < 12) return 'Good morning';
    if (h < 17) return 'Good afternoon';
    return 'Good evening';
  };

  const statCards: Array<{ label: string; value: number; icon: keyof typeof Ionicons.glyphMap; color: string; bg: string; route: string }> = [
    { label: 'Total Jobs', value: stats?.total_jobs ?? 0, icon: 'briefcase-outline', color: colors.primary[600], bg: colors.primary[50], route: 'Jobs' },
    ...(isAdmin ? [{ label: 'Users', value: stats?.active_users ?? 0, icon: 'people-outline' as keyof typeof Ionicons.glyphMap, color: colors.info[600], bg: colors.info[50], route: 'Admin' }] : []),
    { label: 'In Progress', value: stats?.in_progress_jobs ?? 0, icon: 'time-outline', color: colors.warning[600], bg: colors.warning[50], route: 'Jobs' },
    { label: 'Completed', value: stats?.completed_jobs ?? 0, icon: 'checkmark-circle-outline', color: colors.success[600], bg: colors.success[50], route: 'Jobs' },
  ];

  const statCardWidth = cardColumns === 1 ? '100%' : cardColumns === 2 ? '47%' : '31%';

  return (
    <ScrollView
      style={styles.container}
      contentContainerStyle={{ paddingBottom: 100 }}
      refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor={colors.primary[500]} />}
      showsVerticalScrollIndicator={false}
    >
      <StatusBar barStyle="dark-content" backgroundColor={colors.white} />

      <View style={[styles.header, { paddingTop: insets.top + spacing.md, paddingHorizontal: contentPadding }]}>
        <Animated.View style={[styles.headerLeft, { opacity: headerFade, transform: [{ translateY: headerSlide }] }]}>
          <Text style={[styles.greeting, { fontSize: fontSize.body }]}>{greeting()},</Text>
          <Text style={[styles.name, { fontSize: fontSize.h1 }]}>{user?.first_name}</Text>
        </Animated.View>
        {isAdmin && (
          <Animated.View style={[styles.adminBadge, { opacity: headerFade }]}>
            <Ionicons name="shield-checkmark" size={12} color={colors.primary[600]} />
            <Text style={styles.adminBadgeText}>Admin</Text>
          </Animated.View>
        )}
      </View>

      <View style={[styles.statsGrid, { paddingHorizontal: contentPadding, marginTop: spacing.lg }]}>
        {statCards.map((stat, index) => (
          <AnimatedCard
            key={stat.label}
            style={[styles.statCard, { width: statCardWidth as any }]}
            onPress={() => {
              if (stat.route === 'Admin') {
                navigation.navigate('Admin', { screen: 'UserList' });
              } else {
                navigation.navigate(stat.route);
              }
            }}
            delay={index * 80}
          >
            <View style={[styles.statIcon, { backgroundColor: stat.bg }]}>
              <Ionicons name={stat.icon} size={20} color={stat.color} />
            </View>
            <Text style={[styles.statValue, { fontSize: fontSize.stat }]}>{stat.value}</Text>
            <Text style={[styles.statLabel, { fontSize: fontSize.bodySmall }]}>{stat.label}</Text>
          </AnimatedCard>
        ))}
      </View>

      {isAdmin && users.length > 0 && (
        <View style={[styles.section, { paddingHorizontal: contentPadding }]}>
          <View style={styles.sectionHeader}>
            <Text style={[styles.sectionTitle, { fontSize: fontSize.body }]}>Team</Text>
            <TouchableOpacity onPress={() => navigation.navigate('Admin', { screen: 'UserList' })}>
              <Text style={[styles.seeAll, { fontSize: fontSize.bodySmall }]}>See All</Text>
            </TouchableOpacity>
          </View>
          <AnimatedCard delay={350}>
            {users.slice(0, 4).map((u, i) => (
              <View key={u.id} style={[styles.userRow, i < Math.min(users.length, 4) - 1 && styles.userBorder]}>
                <View style={[styles.userAvatar, { backgroundColor: colors.primary[100] }]}>
                  <Text style={[styles.userAvatarText, { color: colors.primary[700] }]}>
                    {u.first_name[0]}{u.last_name?.[0] || ''}
                  </Text>
                </View>
                <View style={styles.userInfo}>
                  <Text style={[styles.userName, { fontSize: fontSize.body }]}>{u.first_name} {u.last_name}</Text>
                  <Text style={[styles.userEmail, { fontSize: fontSize.caption }]}>{u.email}</Text>
                </View>
                <StatusBadge status={u.status} size="sm" />
              </View>
            ))}
          </AnimatedCard>
        </View>
      )}

      <View style={[styles.section, { paddingHorizontal: contentPadding }]}>
        <View style={styles.sectionHeader}>
          <Text style={[styles.sectionTitle, { fontSize: fontSize.body }]}>Job Status</Text>
        </View>
        <AnimatedCard delay={450}>
          {[
            { label: 'Draft', value: stats?.draft_jobs ?? 0, color: colors.gray[400] },
            { label: 'In Progress', value: stats?.in_progress_jobs ?? 0, color: colors.primary[500] },
            { label: 'Completed', value: stats?.completed_jobs ?? 0, color: colors.success[500] },
          ].map((item, i) => (
            <View key={item.label} style={[styles.statusRow, i < 2 && styles.userBorder]}>
              <View style={[styles.statusDot, { backgroundColor: item.color }]} />
              <Text style={[styles.statusLabel, { fontSize: fontSize.body }]}>{item.label}</Text>
              <Text style={[styles.statusValue, { fontSize: fontSize.body }]}>{item.value}</Text>
            </View>
          ))}
        </AnimatedCard>
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, backgroundColor: colors.background },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    paddingBottom: spacing.lg,
    backgroundColor: colors.white,
    borderBottomLeftRadius: radii.xl,
    borderBottomRightRadius: radii.xl,
    ...shadows.sm,
  },
  headerLeft: {},
  greeting: { color: colors.gray[500] },
  name: { fontWeight: '700', color: colors.gray[900], letterSpacing: -0.5 },
  adminBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
    backgroundColor: colors.primary[50],
    paddingHorizontal: 10,
    paddingVertical: 5,
    borderRadius: radii.full,
  },
  adminBadgeText: { fontWeight: '600', color: colors.primary[600] },
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: spacing.md,
  },
  statCard: {
    padding: spacing.lg,
  },
  statIcon: {
    width: 38,
    height: 38,
    borderRadius: radii.md,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: spacing.sm,
  },
  statValue: { fontWeight: '700', color: colors.gray[900] },
  statLabel: { color: colors.gray[500], fontWeight: '500' },
  section: { marginTop: spacing.xl },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.md,
  },
  sectionTitle: { fontWeight: '700', color: colors.gray[900] },
  seeAll: { fontWeight: '600', color: colors.primary[600] },
  userRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    gap: spacing.md,
  },
  userBorder: { borderBottomWidth: 1, borderBottomColor: colors.gray[100] },
  userAvatar: {
    width: 38,
    height: 38,
    borderRadius: 19,
    justifyContent: 'center',
    alignItems: 'center',
  },
  userAvatarText: { fontWeight: '700' },
  userInfo: { flex: 1 },
  userName: { fontWeight: '600', color: colors.gray[900] },
  userEmail: { color: colors.gray[500], marginTop: 1 },
  statusRow: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: 12,
    gap: spacing.md,
  },
  statusDot: { width: 8, height: 8, borderRadius: 4 },
  statusLabel: { flex: 1, color: colors.gray[700] },
  statusValue: { fontWeight: '700', color: colors.gray[900] },
});
