import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  ActivityIndicator,
  Image,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { RootStackParamList } from '../navigation/types';
import { Project, Step } from '../types';
import { getAllProjects, getStepsByProject } from '../lib/db/repositories';
import { Card, PotteryIcon } from '../components';
import { colors, spacing, typography, borderRadius, stepTypeLabels, shadows } from '../lib/theme';
import { useAuth } from '../contexts/AuthContext';

const settingsIcon = require('../../assets/images/settings_icon.png');

const heroImages = [
  require('../../assets/images/hero_pottery.jpg'),
  require('../../assets/images/pottery_bg_1.png'),
  require('../../assets/images/pottery_bg_2.png'),
  require('../../assets/images/pottery_bg_3.png'),
  require('../../assets/images/pottery_bg_4.png'),
  require('../../assets/images/pottery_bg_5.png'), // NEW
  require('../../assets/images/pottery_bg_6.png'), // NEW
  require('../../assets/images/pottery_bg_7.png'), // NEW
];

// Select random image once when module loads (on app start/reload)
const randomHeroImage = heroImages[Math.floor(Math.random() * heroImages.length)];

type NavigationProp = NativeStackNavigationProp<RootStackParamList>;

export const HomeScreen: React.FC = () => {
  const navigation = useNavigation<NavigationProp>();
  const { user } = useAuth();
  const [projects, setProjects] = useState<Project[]>([]);
  const [projectSteps, setProjectSteps] = useState<Record<string, Step[]>>({});
  const [loading, setLoading] = useState(true);

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

  const loadProjects = async () => {
    if (!user) return;

    try {
      const allProjects = await getAllProjects(user.id);
      setProjects(allProjects);

      // Load steps for each project
      const stepsMap: Record<string, Step[]> = {};
      for (const project of allProjects) {
        try {
          const steps = await getStepsByProject(project.id);
          stepsMap[project.id] = steps;
        } catch (error) {
          console.error(`Failed to load steps for project ${project.id}:`, error);
          stepsMap[project.id] = [];
        }
      }
      setProjectSteps(stepsMap);
    } catch (error) {
      console.error('Failed to load projects:', error);
    } finally {
      setLoading(false);
    }
  };

  const getProjectStatus = (project: Project): string => {
    if (project.status === 'done') {
      return 'Completed';
    }

    // Get the most recent step for in-progress projects
    const steps = projectSteps[project.id] || [];
    if (steps.length === 0) {
      return 'In Progress';
    }

    // Sort by updatedAt and get the most recent
    const sortedSteps = [...steps].sort((a, b) =>
      new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    );
    const latestStep = sortedSteps[0];

    // Return the step type label
    return stepTypeLabels[latestStep.type] || 'In Progress';
  };

  // Calculate stats
  const totalProjects = projects.length;
  const inProgressProjects = projects.filter(p => p.status === 'in_progress').length;
  const completedProjects = projects.filter(p => p.status === 'done').length;

  // Get recent projects (last 3)
  const recentProjects = projects
    .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
    .slice(0, 3);

  const handleNewProject = () => {
    navigation.navigate('MainTabs', { screen: 'Projects' });
  };

  const handleBrowseTips = () => {
    navigation.navigate('MainTabs', { screen: 'News' });
  };

  const handleViewAllProjects = () => {
    navigation.navigate('MainTabs', { screen: 'Projects' });
  };

  const handleProjectPress = (projectId: string) => {
    navigation.navigate('ProjectDetail', { projectId });
  };

  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={[]}>
      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContentNoPadding}
        showsVerticalScrollIndicator={false}
      >
        {/* Hero Section with Full-Width Edge-to-Edge Image */}
        <View style={styles.heroSection}>
          {/* Hero Image - edge to edge */}
          <Image source={randomHeroImage} style={styles.heroImage} resizeMode="cover" />
          {/* Content Overlay */}
          <View style={styles.heroOverlay}>
            {/* Top App Bar */}
            <View style={styles.topBar}>
              <View style={styles.greetingContainer}>
                <Text style={styles.greetingText}>Welcome Back,</Text>
                <Text style={styles.nameText}>{user?.name || 'Potter'}</Text>
              </View>
            </View>

            {/* Stats */}
            <View style={styles.statsContainer}>
              <View style={styles.statsRow}>
                <View style={styles.statItem}>
                  <Text style={styles.statNumber}>{totalProjects}</Text>
                  <Text style={styles.statLabel}>Projects</Text>
                </View>
                <View style={styles.statItem}>
                  <Text style={styles.statNumber}>{inProgressProjects}</Text>
                  <Text style={styles.statLabel}>In Progress</Text>
                </View>
              </View>
            </View>
          </View>
        </View>

        {/* Button Group */}
        <View style={styles.buttonGroup}>
          <TouchableOpacity
            style={styles.primaryButton}
            onPress={handleNewProject}
          >
            <Text style={styles.primaryButtonText}>New Pottery Project</Text>
          </TouchableOpacity>
        </View>

        {/* Section Header */}
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>Recent Projects</Text>
          {projects.length > 3 && (
            <TouchableOpacity onPress={handleViewAllProjects}>
              <Text style={styles.viewAllText}>View All</Text>
            </TouchableOpacity>
          )}
        </View>

        {/* List Items */}
        <View style={styles.projectsList}>
          {recentProjects.length === 0 ? (
            <View style={styles.emptyState}>
              <Text style={styles.emptyText}>No projects yet</Text>
              <Text style={styles.emptySubtext}>Start creating your pottery journey!</Text>
              <TouchableOpacity
                style={styles.primaryButton}
                onPress={handleNewProject}
              >
                <Text style={styles.primaryButtonText}>Create First Project</Text>
              </TouchableOpacity>
            </View>
          ) : (
            recentProjects.map((project) => (
              <TouchableOpacity
                key={project.id}
                style={styles.projectItem}
                onPress={() => handleProjectPress(project.id)}
              >
                <View style={styles.projectItemLeft}>
                  {project.coverImageUri ? (
                    <Image
                      source={{ uri: project.coverImageUri }}
                      style={styles.projectThumbnailImage}
                      resizeMode="cover"
                    />
                  ) : (
                    <View style={styles.projectThumbnail}>
                      <Text style={styles.projectEmoji}>🏺</Text>
                    </View>
                  )}
                  <View style={styles.projectInfo}>
                    <Text style={styles.projectName}>{project.title}</Text>
                    <Text style={styles.projectStatus}>
                      {getProjectStatus(project)}
                    </Text>
                  </View>
                </View>
                <View style={styles.projectItemRight}>
                  <Text style={styles.projectDate}>
                    {new Date(project.updatedAt).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                  </Text>
                </View>
              </TouchableOpacity>
            ))
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.background,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: colors.background,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    paddingHorizontal: spacing.lg,
    paddingBottom: 100,
  },
  scrollContentNoPadding: {
    paddingBottom: 100,
  },
  topBar: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    paddingTop: spacing.xl * 3,
    paddingHorizontal: spacing.lg,
    marginBottom: spacing.md,
    gap: spacing.lg,
  },
  greetingContainer: {
    flex: 1,
  },
  greetingText: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.medium,
    color: colors.textSecondary,
    marginBottom: spacing.xs / 2,
  },
  nameText: {
    fontSize: typography.fontSize.xl,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
  },
  settingsButton: {
    padding: spacing.xs,
    marginLeft: spacing.md,
  },
  settingsIconImage: {
    width: 32,
    height: 32,
    opacity: 0.8,
  },
  heroSection: {
    position: 'relative',
    height: 380,
    marginBottom: spacing.xl,
  },
  heroImage: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    opacity: 0.21,
  },
  heroOverlay: {
    flex: 1,
  },
  statsContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: spacing.lg,
  },
  statsRow: {
    flexDirection: 'row',
    gap: spacing.xl * 2,
  },
  statItem: {
    alignItems: 'center',
  },
  statNumber: {
    fontSize: 48,
    fontWeight: typography.fontWeight.bold,
    color: '#8B9A7C', // Sage green from palette
    textShadowColor: 'rgba(0, 0, 0, 0.2)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 3,
  },
  statLabel: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    textTransform: 'uppercase',
    letterSpacing: 0.5,
    textShadowColor: 'rgba(0, 0, 0, 0.1)',
    textShadowOffset: { width: 1, height: 1 },
    textShadowRadius: 2,
    fontWeight: '600',
  },
  buttonGroup: {
    gap: spacing.md,
    marginBottom: spacing.xl,
    paddingHorizontal: spacing.lg,
  },
  primaryButton: {
    backgroundColor: '#8B9A7C', // Sage green from palette
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
    borderRadius: borderRadius.lg,
    alignItems: 'center',
    // Floating effect
    shadowColor: '#000000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.3,
    shadowRadius: 8,
    elevation: 8,
  },
  primaryButtonText: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.bold,
    color: colors.buttonText,
  },
  secondaryButton: {
    backgroundColor: 'transparent',
    paddingVertical: spacing.md,
    paddingHorizontal: spacing.lg,
    borderRadius: borderRadius.lg,
    borderWidth: 2,
    borderColor: colors.accent,
    alignItems: 'center',
  },
  secondaryButtonText: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.semiBold,
    color: colors.accent,
  },
  sectionHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  sectionTitle: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.bold,
    color: colors.text,
  },
  viewAllText: {
    fontSize: typography.fontSize.sm,
    fontWeight: typography.fontWeight.semiBold,
    color: colors.primary,
  },
  projectsList: {
    gap: spacing.md,
    paddingHorizontal: spacing.lg,
  },
  projectItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: colors.card,
    padding: spacing.md,
    borderRadius: borderRadius.lg,
    borderWidth: 2,
    borderColor: colors.border,
    ...shadows.md,
  },
  projectItemLeft: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 1,
  },
  projectThumbnail: {
    width: 50,
    height: 50,
    borderRadius: borderRadius.md,
    backgroundColor: colors.primaryLight,
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: spacing.md,
  },
  projectThumbnailImage: {
    width: 50,
    height: 50,
    borderRadius: borderRadius.md,
    marginRight: spacing.md,
  },
  projectEmoji: {
    fontSize: 24,
  },
  projectInfo: {
    flex: 1,
  },
  projectName: {
    fontSize: typography.fontSize.md,
    fontWeight: typography.fontWeight.semiBold,
    color: colors.text,
    marginBottom: spacing.xs / 2,
  },
  projectStatus: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
  },
  projectItemRight: {
    marginLeft: spacing.md,
  },
  projectDate: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
  },
  emptyState: {
    alignItems: 'center',
    paddingVertical: spacing.xl * 2,
  },
  emptyText: {
    fontSize: typography.fontSize.lg,
    fontWeight: typography.fontWeight.semiBold,
    color: colors.text,
    marginBottom: spacing.xs,
  },
  emptySubtext: {
    fontSize: typography.fontSize.sm,
    color: colors.textSecondary,
    marginBottom: spacing.xl,
  },
});
