import { Text } from '@/aesthetics/Text';
import { font, spacing, useColors } from '@/aesthetics/styles';
import { useStrings } from '@/common/hooks/useStrings';
import { usePreferences } from '@/profile/preferences';
import { useProfile } from '@/profile/ProfileProvider';
import { useFoodRecommendations } from '@/see-log/recommendation/useFoodRecommendations';
import { useRouter } from 'expo-router';
import { ScrollView, StyleSheet, View } from 'react-native';
import { SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';
import { EmptyState, PendingBanner, Section } from './DashboardUI';
import { DayBarScroll } from './DayBarScroll';
import { FoodLogCard } from './FoodLogCard';
import { FoodRecoCard } from './FoodRecoCard';
import { NutrientBreakdownCard } from './NutrientBreakdownCard';
import { NutritionScoreCard } from './NutritionScoreCard';
import { AddLogCard } from '@/add-log/memo-log-editor/AddLogCard';
import { useFoodLogs } from './useFoodLogs';
import { useFoodReview } from './useFoodReview';

export function DashboardScreen() {
  const c = useColors();
  const strings = useStrings();
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { profile } = useProfile();
  const { enabledCastleFeatures } = usePreferences();
  const { logs: allLogs } = useFoodLogs();

  const {
    selectedDate,
    setSelectedDate,
    displayMode,
    setDisplayMode,
    sortMode,
    setSortMode,
    dayScores,
    loadMoreFutureDays,
    consumed,
    targets,
    logs,
    nutritionScore,
    pendingCount,
  } = useFoodReview(allLogs);

  const {
    ingredients: recommendedIngredients,
    foods: recommendedFoods,
    loading: recommendationsLoading,
    hasGenerated,
    isEligibleForReport,
    canGenerate,
    generate,
  } = useFoodRecommendations(allLogs, selectedDate, profile);

  return (
    <SafeAreaView style={[styles.container, { backgroundColor: c.background }]} edges={['top']}>
      <ScrollView
        style={styles.scroll}
        contentContainerStyle={[styles.scrollContent, { paddingBottom: 120 + insets.bottom }]}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.header}>
          <Text style={[styles.headerTitle, { color: c.text }]}>{strings.common.appName}</Text>
          <Text style={[styles.headerTagline, { color: c.tertiaryText }]}>
            {strings.common.tagline}
          </Text>
        </View>

        <DayBarScroll
          date={selectedDate}
          dayScores={dayScores}
          onSelectDate={setSelectedDate}
          onLoadMore={loadMoreFutureDays}
        />

        <View style={styles.content}>
          <Section title={strings.seeLog.nutritionScore}>
            <NutritionScoreCard score={nutritionScore} />
          </Section>

          <Section title={strings.seeLog.nutrients}>
            <NutrientBreakdownCard
              consumed={consumed}
              targets={targets}
              displayMode={displayMode}
              sortMode={sortMode}
              onChangeDisplayMode={setDisplayMode}
              onChangeSortMode={setSortMode}
            />
          </Section>

          <Section title={strings.seeLog.eatenToday}>
            {pendingCount > 0 && <PendingBanner count={pendingCount} />}
            {logs.length > 0 ? (
              <View style={styles.logsList}>
                {logs.map(log => (
                  <FoodLogCard
                    key={log.id}
                    log={log}
                    onPress={() => router.push(`/see-log/${log.id}`)}
                  />
                ))}
              </View>
            ) : (
              <EmptyState text={strings.seeLog.noFoodLogged} />
            )}
          </Section>

          {isEligibleForReport && (
            <Section title={strings.seeLog.report.title}>
              <FoodRecoCard
                ingredients={recommendedIngredients}
                foods={recommendedFoods}
                loading={recommendationsLoading}
                hasGenerated={hasGenerated}
                canGenerate={canGenerate}
                onGenerate={generate}
              />
            </Section>
          )}

          {enabledCastleFeatures.includes('logAnything') && (
            <Section title={strings.seeLog.userCustomLogs}>
              <AddLogCard />
            </Section>
          )}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scroll: {
    flex: 1,
  },
  scrollContent: {
    paddingBottom: 120,
  },
  header: {
    paddingHorizontal: spacing.xl,
    paddingTop: spacing.xxl,
    paddingBottom: spacing.lg,
  },
  headerTitle: {
    fontSize: font.display,
    letterSpacing: -0.5,
  },
  headerTagline: {
    fontSize: font.xs,
    letterSpacing: 2,
    textTransform: 'uppercase',
    marginTop: spacing.xs,
  },
  content: {
    paddingHorizontal: spacing.xl,
    paddingTop: spacing.xl,
    gap: spacing.section,
  },
  logsList: {
    gap: spacing.lg,
  },
});
