import React, { useState, useCallback } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from '@react-navigation/native';
import { ScreenContainer } from '../../components/layout/ScreenContainer';
import { AnimatedCard } from '../../components/ui/AnimatedCard';
import { useResponsive } from '../../hooks/useResponsive';
import { reportService } from '../../services/reportService';
import { DashboardStats } from '../../types';
import { colors, spacing, radii } from '../../theme';

export default function ReportScreen() {
  const navigation = useNavigation<any>();
  const { contentPadding, cardColumns, gutter, fontSize } = useResponsive();
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);

  const loadStats = async () => {
    try {
      const data = await reportService.dashboard();
      setStats(data);
    } catch (error) {
      console.error('Failed to load report:', error);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  const onRefresh = useCallback(() => {
    setRefreshing(true);
    loadStats();
  }, []);

  React.useEffect(() => {
    loadStats();
  }, []);

  const total = stats?.total_jobs || 1;
  const statusBreakdown = [
    { label: 'Draft', count: stats?.draft_jobs ?? 0, color: colors.gray[500], icon: 'document-outline' as const },
    { label: 'Checked In', count: stats?.checked_in_jobs ?? 0, color: colors.warning[500], icon: 'log-in-outline' as const },
    { label: 'In Progress', count: stats?.in_progress_jobs ?? 0, color: colors.warning[600], icon: 'time-outline' as const },
    { label: 'Completed', count: stats?.completed_jobs ?? 0, color: colors.success[500], icon: 'checkmark-circle-outline' as const },
  ];

  const statCards = [
    { label: 'Total Jobs', value: stats?.total_jobs ?? 0, icon: 'briefcase-outline', color: colors.primary[600] },
    { label: 'Active Users', value: stats?.active_users ?? 0, icon: 'people-outline', color: colors.info[600] },
    { label: 'Location Pings', value: stats?.recent_locations?.length ?? 0, icon: 'navigate-outline', color: colors.success[600] },
  ];

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

  return (
    <ScreenContainer
      title="Reports"
      onBack={() => navigation.goBack()}
      loading={loading}
      refreshing={refreshing}
      onRefresh={onRefresh}
      scroll={true}
      contentPadding={contentPadding}
    >
      <View style={[styles.statsGrid, { gap: gutter, marginBottom: spacing.lg }]}>
        {statCards.map((stat, index) => (
          <AnimatedCard key={stat.label} delay={index * 80} style={[styles.statCard, { width: statCardWidth }]}>
            <View style={[styles.statIcon, { backgroundColor: `${stat.color}15`, width: 40, height: 40, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center', marginBottom: spacing.sm }]}>
              <Ionicons name={stat.icon as any} size={20} color={stat.color} />
            </View>
            <Text style={[styles.statValue, { fontSize: fontSize.stat }]}>{stat.value}</Text>
            <Text style={[styles.statLabel, { fontSize: fontSize.caption, marginTop: spacing.xs }]}>{stat.label}</Text>
          </AnimatedCard>
        ))}
      </View>

      <AnimatedCard delay={300} style={{ marginBottom: spacing.md }}>
        <Text style={[styles.sectionTitle, { fontSize: fontSize.h3, marginBottom: spacing.lg }]}>Status Breakdown</Text>
        {statusBreakdown.map((item) => {
          const percentage = total > 0 ? (item.count / total) * 100 : 0;
          return (
            <View key={item.label} style={[styles.barRow, { marginBottom: spacing.md, gap: spacing.sm }]}>
              <View style={[styles.barLabel, { flexDirection: 'row', alignItems: 'center', gap: spacing.xs, minWidth: 90, flexShrink: 0 }]}>
                <Ionicons name={item.icon} size={16} color={item.color} />
                <Text style={[styles.barLabelText, { fontSize: fontSize.bodySmall }]} numberOfLines={1}>{item.label}</Text>
              </View>
              <View style={[styles.barContainer, { flex: 1, height: 8, backgroundColor: colors.gray[100], borderRadius: radii.full, overflow: 'hidden' }]}>
                <View
                  style={[
                    styles.barFill,
                    { width: `${percentage}%`, backgroundColor: item.color },
                  ]}
                />
              </View>
              <Text style={[styles.barCount, { fontSize: fontSize.body, width: 30, textAlign: 'right' }]}>{item.count}</Text>
            </View>
          );
        })}
      </AnimatedCard>

      <AnimatedCard delay={400}>
        <Text style={[styles.sectionTitle, { fontSize: fontSize.h3, marginBottom: spacing.lg }]}>Quick Actions</Text>
        <View style={[styles.actionsGrid, { flexDirection: 'row', justifyContent: 'space-between' }]}>
          <View style={[styles.actionItem, { alignItems: 'center', gap: spacing.sm }]}>
            <View style={[styles.actionIcon, { backgroundColor: colors.primary[50], width: 48, height: 48, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center' }]}>
              <Ionicons name="briefcase-outline" size={20} color={colors.primary[600]} />
            </View>
            <Text style={[styles.actionLabel, { fontSize: fontSize.caption }]}>Jobs</Text>
          </View>
          <View style={[styles.actionItem, { alignItems: 'center', gap: spacing.sm }]}>
            <View style={[styles.actionIcon, { backgroundColor: colors.info[50], width: 48, height: 48, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center' }]}>
              <Ionicons name="people-outline" size={20} color={colors.info[600]} />
            </View>
            <Text style={[styles.actionLabel, { fontSize: fontSize.caption }]}>Users</Text>
          </View>
          <View style={[styles.actionItem, { alignItems: 'center', gap: spacing.sm }]}>
            <View style={[styles.actionIcon, { backgroundColor: colors.success[50], width: 48, height: 48, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center' }]}>
              <Ionicons name="cube-outline" size={20} color={colors.success[600]} />
            </View>
            <Text style={[styles.actionLabel, { fontSize: fontSize.caption }]}>Materials</Text>
          </View>
          <View style={[styles.actionItem, { alignItems: 'center', gap: spacing.sm }]}>
            <View style={[styles.actionIcon, { backgroundColor: colors.warning[50], width: 48, height: 48, borderRadius: radii.lg, justifyContent: 'center', alignItems: 'center' }]}>
              <Ionicons name="location-outline" size={20} color={colors.warning[600]} />
            </View>
            <Text style={[styles.actionLabel, { fontSize: fontSize.caption }]}>Geofences</Text>
          </View>
        </View>
      </AnimatedCard>
    </ScreenContainer>
  );
}

const styles = StyleSheet.create({
  statsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  statCard: {
    alignItems: 'center',
  },
  statIcon: {},
  statValue: {
    fontWeight: 'bold',
    color: colors.gray[900],
  },
  statLabel: {
    color: colors.gray[500],
  },
  sectionTitle: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  barRow: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  barLabel: {},
  barLabelText: {
    color: colors.gray[700],
  },
  barContainer: {},
  barFill: {
    height: '100%',
    borderRadius: radii.full,
  },
  barCount: {
    fontWeight: '600',
    color: colors.gray[900],
  },
  actionsGrid: {},
  actionItem: {},
  actionIcon: {},
  actionLabel: {
    fontWeight: '500',
    color: colors.gray[600],
  },
});
