import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  FlatList,
  TouchableOpacity,
  ActivityIndicator,
  RefreshControl,
  Image,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { useFocusEffect } from '@react-navigation/native';
import { useAuth } from '@/contexts/AuthContext';
import { useBeneficiary } from '@/contexts/BeneficiaryContext';
import { api } from '@/services/api';
import {
  AppColors,
  BorderRadius,
  FontSizes,
  FontWeights,
  Spacing,
  Shadows,
  AvatarSizes,
} from '@/constants/theme';
import type { Beneficiary } from '@/types';

// Beneficiary card with equipment status support
interface BeneficiaryCardProps {
  beneficiary: Beneficiary;
  onPress: () => void;
  onActivate?: () => void;
}

// Equipment status config
const equipmentStatusConfig = {
  ordered: {
    icon: 'cube-outline' as const,
    label: 'Kit ordered',
    sublabel: 'Preparing to ship',
    color: AppColors.info,
    bgColor: AppColors.infoLight,
  },
  shipped: {
    icon: 'car-outline' as const,
    label: 'In transit',
    sublabel: 'Track your package',
    color: AppColors.warning,
    bgColor: AppColors.warningLight,
  },
  delivered: {
    icon: 'checkmark-circle-outline' as const,
    label: 'Delivered',
    sublabel: 'Ready to activate',
    color: AppColors.success,
    bgColor: AppColors.successLight,
  },
};

function BeneficiaryCard({ beneficiary, onPress, onActivate }: BeneficiaryCardProps) {
  const equipmentStatus = beneficiary.equipmentStatus;
  const isAwaitingEquipment = equipmentStatus && ['ordered', 'shipped', 'delivered'].includes(equipmentStatus);
  const statusConfig = equipmentStatus ? equipmentStatusConfig[equipmentStatus as keyof typeof equipmentStatusConfig] : null;

  // Check if subscription is missing or expired (only for active equipment)
  const hasNoSubscription = !isAwaitingEquipment && (
    !beneficiary.subscription || beneficiary.subscription.status !== 'active'
  );

  // Handle press - if delivered, go to activate
  const handlePress = () => {
    if (equipmentStatus === 'delivered' && onActivate) {
      onActivate();
    } else {
      onPress();
    }
  };

  return (
    <TouchableOpacity
      style={[styles.card, hasNoSubscription && styles.cardNoSubscription]}
      onPress={handlePress}
      activeOpacity={0.7}
    >
      {/* Avatar */}
      <View style={styles.avatarWrapper}>
        {beneficiary.avatar ? (
          <Image source={{ uri: beneficiary.avatar }} style={styles.avatarImage} />
        ) : (
          <View style={[styles.avatar, hasNoSubscription && styles.avatarNoSubscription]}>
            <Text style={[styles.avatarText, hasNoSubscription && styles.avatarTextNoSubscription]}>
              {beneficiary.name.charAt(0).toUpperCase()}
            </Text>
          </View>
        )}
      </View>

      {/* Name and Status */}
      <View style={styles.info}>
        <Text style={styles.name} numberOfLines={1}>{beneficiary.name}</Text>
        {/* Equipment status badge */}
        {isAwaitingEquipment && statusConfig && (
          <View style={[styles.statusBadge, { backgroundColor: statusConfig.bgColor }]}>
            <Ionicons name={statusConfig.icon} size={14} color={statusConfig.color} />
            <Text style={[styles.statusText, { color: statusConfig.color }]}>
              {statusConfig.label}
            </Text>
          </View>
        )}
        {/* No subscription warning */}
        {hasNoSubscription && (
          <View style={styles.noSubscriptionBadge}>
            <Ionicons name="alert-circle" size={14} color={AppColors.error} />
            <Text style={styles.noSubscriptionText}>No subscription</Text>
          </View>
        )}
      </View>

      {/* Action button or Arrow */}
      {equipmentStatus === 'delivered' ? (
        <TouchableOpacity
          style={styles.activateButton}
          onPress={onActivate}
          activeOpacity={0.8}
        >
          <Text style={styles.activateButtonText}>Activate</Text>
        </TouchableOpacity>
      ) : (
        <View style={styles.arrowContainer}>
          <Ionicons name="chevron-forward" size={20} color={AppColors.textMuted} />
        </View>
      )}
    </TouchableOpacity>
  );
}

export default function HomeScreen() {
  const { user } = useAuth();
  const { currentBeneficiary, setCurrentBeneficiary, localBeneficiaries } = useBeneficiary();
  const [isLoading, setIsLoading] = useState(true);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [beneficiaries, setBeneficiaries] = useState<Beneficiary[]>([]);
  const [error, setError] = useState<string | null>(null);


  // Load beneficiaries when screen is focused (after editing profile, etc.)
  useFocusEffect(
    useCallback(() => {
      loadBeneficiaries();
    }, [localBeneficiaries])
  );

  const loadBeneficiaries = async () => {
    setIsLoading(true);
    setError(null);
    try {
      const onboardingCompleted = await api.isOnboardingCompleted();
      const response = await api.getAllBeneficiaries();

      let allBeneficiaries: Beneficiary[] = [];

      if (response.ok && response.data) {
        allBeneficiaries = [...response.data];
      }

      allBeneficiaries = [...allBeneficiaries, ...localBeneficiaries];
      setBeneficiaries(allBeneficiaries);

      if (!currentBeneficiary && allBeneficiaries.length > 0) {
        setCurrentBeneficiary(allBeneficiaries[0]);
      }

      if (allBeneficiaries.length === 0 && !onboardingCompleted) {
        router.replace({
          pathname: '/(auth)/add-loved-one',
          params: { email: user?.email || '' },
        });
        return;
      }
    } catch (err) {
      console.error('Failed to load beneficiaries:', err);
      if (localBeneficiaries.length > 0) {
        setBeneficiaries(localBeneficiaries);
      } else {
        setError('Failed to load beneficiaries');
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleRefresh = async () => {
    setIsRefreshing(true);
    await loadBeneficiaries();
    setIsRefreshing(false);
  };

  const handleBeneficiaryPress = (beneficiary: Beneficiary) => {
    setCurrentBeneficiary(beneficiary);
    // If equipment is not active yet, show status page instead of dashboard
    if (beneficiary.equipmentStatus && ['ordered', 'shipped'].includes(beneficiary.equipmentStatus)) {
      router.push(`/(tabs)/beneficiaries/${beneficiary.id}`);
    } else {
      router.push(`/(tabs)/beneficiaries/${beneficiary.id}/dashboard`);
    }
  };

  const handleActivate = (beneficiary: Beneficiary) => {
    setCurrentBeneficiary(beneficiary);
    router.push({
      pathname: '/(auth)/activate',
      params: { lovedOneName: beneficiary.name, beneficiaryId: beneficiary.id.toString() },
    });
  };

  const getDisplayName = () => {
    if (user?.user_name) return user.user_name;
    if (user?.email) return user.email.split('@')[0];
    return 'User';
  };

  const displayName = getDisplayName();
  const greeting = new Date().getHours() < 12 ? 'Good morning' : new Date().getHours() < 18 ? 'Good afternoon' : 'Good evening';

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container} edges={['top']}>
        <View style={styles.header}>
          <View>
            <Text style={styles.greeting}>{greeting},</Text>
            <Text style={styles.displayName}>{displayName}</Text>
          </View>
        </View>
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={AppColors.primary} />
          <Text style={styles.loadingText}>Loading...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container} edges={['top']}>
      {/* Header */}
      <View style={styles.header}>
        <View style={styles.headerContent}>
          <View>
            <Text style={styles.greeting}>{greeting},</Text>
            <Text style={styles.displayName}>{displayName}</Text>
          </View>
          <TouchableOpacity style={styles.headerAction} onPress={handleRefresh}>
            <Ionicons name="refresh" size={22} color={AppColors.primary} />
          </TouchableOpacity>
        </View>
      </View>


      {/* Section Title */}
      {beneficiaries.length > 0 && (
        <View style={styles.sectionHeader}>
          <Text style={styles.sectionTitle}>My Loved Ones</Text>
          <Text style={styles.sectionCount}>{beneficiaries.length}</Text>
        </View>
      )}

      {/* Content */}
      {beneficiaries.length === 0 ? (
        <View style={styles.emptyContainer}>
          <View style={styles.emptyIconContainer}>
            <Ionicons name="people-outline" size={48} color={AppColors.primary} />
          </View>
          <Text style={styles.emptyTitle}>No loved ones yet</Text>
          <Text style={styles.emptyText}>
            Add a loved one to start monitoring their wellbeing and stay connected.
          </Text>
          <TouchableOpacity
            style={styles.addButtonLarge}
            onPress={() => router.push('/(tabs)/beneficiaries/add')}
          >
            <Ionicons name="add" size={22} color={AppColors.white} />
            <Text style={styles.addButtonText}>Add Loved One</Text>
          </TouchableOpacity>
        </View>
      ) : (
        <>
          <FlatList
            data={beneficiaries}
            keyExtractor={(item) => item.id.toString()}
            renderItem={({ item }) => (
              <BeneficiaryCard
                beneficiary={item}
                onPress={() => handleBeneficiaryPress(item)}
                onActivate={() => handleActivate(item)}
              />
            )}
            contentContainerStyle={styles.listContent}
            showsVerticalScrollIndicator={false}
            refreshControl={
              <RefreshControl
                refreshing={isRefreshing}
                onRefresh={handleRefresh}
                colors={[AppColors.primary]}
                tintColor={AppColors.primary}
              />
            }
          />
          {/* Floating Add Button */}
          <TouchableOpacity
            style={styles.fab}
            onPress={() => router.push('/(tabs)/beneficiaries/add')}
            activeOpacity={0.9}
          >
            <Ionicons name="add" size={28} color={AppColors.white} />
          </TouchableOpacity>
        </>
      )}
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.background,
  },
  header: {
    paddingHorizontal: Spacing.lg,
    paddingTop: Spacing.md,
    paddingBottom: Spacing.lg,
    backgroundColor: AppColors.background,
  },
  headerContent: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  greeting: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    fontWeight: FontWeights.medium,
  },
  displayName: {
    fontSize: FontSizes['2xl'],
    fontWeight: FontWeights.bold,
    color: AppColors.textPrimary,
    marginTop: 2,
  },
  headerAction: {
    width: 44,
    height: 44,
    borderRadius: BorderRadius.lg,
    backgroundColor: AppColors.primaryLighter,
    justifyContent: 'center',
    alignItems: 'center',
  },
  sectionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: Spacing.lg,
    marginBottom: Spacing.md,
  },
  sectionTitle: {
    fontSize: FontSizes.lg,
    fontWeight: FontWeights.semibold,
    color: AppColors.textPrimary,
  },
  sectionCount: {
    fontSize: FontSizes.sm,
    fontWeight: FontWeights.semibold,
    color: AppColors.primary,
    backgroundColor: AppColors.primaryLighter,
    paddingHorizontal: Spacing.sm,
    paddingVertical: 2,
    borderRadius: BorderRadius.full,
    marginLeft: Spacing.sm,
    overflow: 'hidden',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: Spacing.md,
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: Spacing.xl,
  },
  emptyIconContainer: {
    width: 96,
    height: 96,
    borderRadius: BorderRadius['2xl'],
    backgroundColor: AppColors.primaryLighter,
    justifyContent: 'center',
    alignItems: 'center',
    marginBottom: Spacing.lg,
  },
  emptyTitle: {
    fontSize: FontSizes.xl,
    fontWeight: FontWeights.bold,
    color: AppColors.textPrimary,
    marginBottom: Spacing.sm,
  },
  emptyText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
    lineHeight: 24,
    marginBottom: Spacing.xl,
  },
  addButtonLarge: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: AppColors.primary,
    paddingVertical: Spacing.md,
    paddingHorizontal: Spacing.xl,
    borderRadius: BorderRadius.lg,
    gap: Spacing.sm,
    ...Shadows.primary,
  },
  addButtonText: {
    fontSize: FontSizes.base,
    fontWeight: FontWeights.semibold,
    color: AppColors.white,
  },
  listContent: {
    paddingHorizontal: Spacing.lg,
    paddingBottom: 100,
  },
  // Card styles
  card: {
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.xl,
    marginBottom: Spacing.md,
    padding: Spacing.md,
    flexDirection: 'row',
    alignItems: 'center',
    borderWidth: 2,
    borderColor: 'transparent',
    ...Shadows.sm,
  },
  cardNoSubscription: {
    borderColor: AppColors.error,
    backgroundColor: AppColors.errorLight,
  },
  avatarWrapper: {
    position: 'relative',
  },
  avatar: {
    width: AvatarSizes.md,
    height: AvatarSizes.md,
    borderRadius: AvatarSizes.md / 2,
    backgroundColor: AppColors.primaryLighter,
    justifyContent: 'center',
    alignItems: 'center',
  },
  avatarImage: {
    width: AvatarSizes.md,
    height: AvatarSizes.md,
    borderRadius: AvatarSizes.md / 2,
  },
  avatarText: {
    fontSize: FontSizes.xl,
    fontWeight: FontWeights.bold,
    color: AppColors.primary,
  },
  avatarNoSubscription: {
    backgroundColor: AppColors.errorLight,
  },
  avatarTextNoSubscription: {
    color: AppColors.error,
  },
  info: {
    flex: 1,
    marginLeft: Spacing.md,
    marginRight: Spacing.sm,
  },
  name: {
    fontSize: FontSizes.lg,
    fontWeight: FontWeights.semibold,
    color: AppColors.textPrimary,
  },
  noSubscriptionBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 4,
    gap: 4,
  },
  noSubscriptionText: {
    fontSize: FontSizes.xs,
    fontWeight: FontWeights.medium,
    color: AppColors.error,
  },
  statusBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: Spacing.sm,
    paddingVertical: 4,
    borderRadius: BorderRadius.md,
    marginTop: 4,
    alignSelf: 'flex-start',
    gap: 4,
  },
  statusText: {
    fontSize: FontSizes.xs,
    fontWeight: FontWeights.medium,
  },
  activateButton: {
    backgroundColor: AppColors.primary,
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    borderRadius: BorderRadius.md,
  },
  activateButtonText: {
    color: AppColors.white,
    fontSize: FontSizes.sm,
    fontWeight: FontWeights.semibold,
  },
  arrowContainer: {
    width: 32,
    height: 32,
    borderRadius: BorderRadius.md,
    backgroundColor: AppColors.surfaceSecondary,
    justifyContent: 'center',
    alignItems: 'center',
  },
  // Floating Action Button
  fab: {
    position: 'absolute',
    bottom: Spacing.xl,
    right: Spacing.lg,
    width: 60,
    height: 60,
    borderRadius: 30,
    backgroundColor: AppColors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    ...Shadows.lg,
  },
});
