import { Image } from 'expo-image';
import { Pressable, StyleSheet, View } from 'react-native';
import { useCallback, useState } from 'react';
import { Link, useFocusEffect } from 'expo-router';

import ParallaxScrollView from '@/components/parallax-scroll-view';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { ThemedButton } from '@/components/themed-button';
import { IconSymbol } from '@/components/ui/icon-symbol';
import { Colors, Fonts } from '@/constants/theme';
import { useTranslation } from '@/localization/i18n';
import { dbPromise, initCoreTables } from '@/services/db';
import { useColorScheme } from '@/hooks/use-color-scheme';


export default function HomeScreen() {
  const { t } = useTranslation();
  const theme = useColorScheme() ?? 'light';
  const palette = Colors[theme];
  const iconColor = palette.tint;
  const [counts, setCounts] = useState({
    fields: 0,
    crops: 0,
    observations: 0,
    tasks: 0,
    history: 0,
    harvests: 0,
    sales: 0,
    costs: 0,
  });

  useFocusEffect(
    useCallback(() => {
      let isActive = true;

      async function loadCounts() {
        try {
          await initCoreTables();
          const db = await dbPromise;
          const fieldCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM fields;'
          );
          const cropCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM crops;'
          );
          const observationCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM observations;'
          );
          const taskCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM daily_tasks WHERE is_active = 1;'
          );
          const historyCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM daily_task_entries;'
          );
          const harvestCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM harvests;'
          );
          const salesCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM sales;'
          );
          const costCount = await db.getFirstAsync<{ count: number }>(
            'SELECT COUNT(*) as count FROM costs;'
          );
          if (!isActive) return;
          setCounts({
            fields: fieldCount?.count ?? 0,
            crops: cropCount?.count ?? 0,
            observations: observationCount?.count ?? 0,
            tasks: taskCount?.count ?? 0,
            history: historyCount?.count ?? 0,
            harvests: harvestCount?.count ?? 0,
            sales: salesCount?.count ?? 0,
            costs: costCount?.count ?? 0,
          });
        } catch {
          if (!isActive) return;
          setCounts((prev) => prev);
        }
      }

      loadCounts();
      return () => {
        isActive = false;
      };
    }, [])
  );

  return (
    <ParallaxScrollView
      headerBackgroundColor={{ light: '#E7E1D6', dark: '#1E241D' }}
      headerImage={
        <Image
          source={require('@/assets/images/home.jpg')}
          style={styles.heroImage}
          contentFit="cover"
        />
      }>
      <ThemedView style={styles.heroCopy}>
        <View
          style={[
            styles.heroBadge,
            { borderColor: palette.border, backgroundColor: palette.surface },
          ]}>
          <IconSymbol name="leaf.fill" size={16} color={iconColor} />
          <ThemedText style={styles.heroBadgeText}>{t('home.badge')}</ThemedText>
        </View>
        <ThemedText type="title" style={styles.heroTitle}>
          {t('home.title')}
        </ThemedText>
        <ThemedText style={styles.heroSubtitle}>
          {t('home.subtitle')}
        </ThemedText>
        <View style={styles.heroActions}>
          <Link href="/logbook" asChild>
            <ThemedButton title={t('home.openLogbook')} />
          </Link>
          <Link href="/tasks" asChild>
            <ThemedButton title={t('home.todayTasks')} variant="secondary" />
          </Link>
        </View>
      </ThemedView>

      <ThemedView style={styles.section}>
        <ThemedText type="subtitle">{t('home.quickActions')}</ThemedText>
        <View style={styles.actionGrid}>
          <Link href="/fields" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="map.fill" size={22} color={iconColor} />
              <View style={styles.actionHeader}>
                <ThemedText style={styles.actionTitle}>{t('home.fields')}</ThemedText>
                <View
                  style={[
                    styles.countBadge,
                    { borderColor: palette.border, backgroundColor: palette.surface },
                  ]}>
                  <ThemedText style={styles.countText}>{counts.fields}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.actionHint}>{t('home.fieldsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/crops" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="leaf.circle.fill" size={22} color={iconColor} />
              <View style={styles.actionHeader}>
                <ThemedText style={styles.actionTitle}>{t('home.crops')}</ThemedText>
                <View
                  style={[
                    styles.countBadge,
                    { borderColor: palette.border, backgroundColor: palette.surface },
                  ]}>
                  <ThemedText style={styles.countText}>{counts.crops}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.actionHint}>{t('home.cropsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/observations" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="eye.fill" size={22} color={iconColor} />
              <View style={styles.actionHeader}>
                <ThemedText style={styles.actionTitle}>{t('home.observations')}</ThemedText>
                <View
                  style={[
                    styles.countBadge,
                    { borderColor: palette.border, backgroundColor: palette.surface },
                  ]}>
                  <ThemedText style={styles.countText}>{counts.observations}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.actionHint}>{t('home.observationsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/onnx" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="sparkles" size={22} color={iconColor} />
              <ThemedText style={styles.actionTitle}>{t('home.onnx')}</ThemedText>
              <ThemedText style={styles.actionHint}>{t('home.onnxHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/harvests" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="tray.full.fill" size={22} color={iconColor} />
              <View style={styles.actionHeader}>
                <ThemedText style={styles.actionTitle}>{t('home.harvests')}</ThemedText>
                <View
                  style={[
                    styles.countBadge,
                    { borderColor: palette.border, backgroundColor: palette.surface },
                  ]}>
                  <ThemedText style={styles.countText}>{counts.harvests}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.actionHint}>{t('home.harvestsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/sales" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="cart.fill" size={22} color={iconColor} />
              <View style={styles.actionHeader}>
                <ThemedText style={styles.actionTitle}>{t('home.sales')}</ThemedText>
                <View
                  style={[
                    styles.countBadge,
                    { borderColor: palette.border, backgroundColor: palette.surface },
                  ]}>
                  <ThemedText style={styles.countText}>{counts.sales}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.actionHint}>{t('home.salesHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/costs" asChild>
            <Pressable
              style={[
                styles.actionCard,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="dollarsign.circle.fill" size={22} color={iconColor} />
              <View style={styles.actionHeader}>
                <ThemedText style={styles.actionTitle}>{t('home.costs')}</ThemedText>
                <View
                  style={[
                    styles.countBadge,
                    { borderColor: palette.border, backgroundColor: palette.surface },
                  ]}>
                  <ThemedText style={styles.countText}>{counts.costs}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.actionHint}>{t('home.costsHint')}</ThemedText>
            </Pressable>
          </Link>
        </View>
      </ThemedView>

      <ThemedView style={styles.section}>
        <ThemedText type="subtitle">{t('home.todayTitle')}</ThemedText>
        <View
          style={[
            styles.highlightCard,
            { borderColor: palette.border, backgroundColor: palette.surface },
          ]}>
          <View style={styles.highlightHeader}>
            <ThemedText style={styles.highlightTitle}>{t('home.todayCardTitle')}</ThemedText>
            <View style={styles.highlightCounts}>
              <View
                style={[
                  styles.countBadge,
                  { borderColor: palette.border, backgroundColor: palette.card },
                ]}>
                <ThemedText style={styles.countText}>
                  {t('home.count.tasks')} {counts.tasks}
                </ThemedText>
              </View>
              <View
                style={[
                  styles.countBadge,
                  { borderColor: palette.border, backgroundColor: palette.card },
                ]}>
                <ThemedText style={styles.countText}>
                  {t('home.count.history')} {counts.history}
                </ThemedText>
              </View>
            </View>
          </View>
          <ThemedText style={styles.highlightBody}>
            {t('home.todayCardBody')}
          </ThemedText>
          <View style={styles.highlightActions}>
            <Link href="/tasks" asChild>
              <ThemedButton title={t('home.openTasks')} />
            </Link>
            <Link href="/task-history" asChild>
              <ThemedButton title={t('home.taskHistory')} variant="secondary" />
            </Link>
          </View>
        </View>
      </ThemedView>

      <ThemedView style={styles.section}>
        <ThemedText type="subtitle">{t('home.learnAnalyze')}</ThemedText>
        <View style={styles.actionGrid}>
          <Link href="/blog" asChild>
            <Pressable
              style={[
                styles.actionCardWide,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="doc.text.image" size={22} color={iconColor} />
              <View style={styles.actionCopy}>
                <ThemedText style={styles.actionTitle}>{t('home.blogs')}</ThemedText>
                <ThemedText style={styles.actionHint}>{t('home.blogsHint')}</ThemedText>
              </View>
            </Pressable>
          </Link>
          <Link href="/setup" asChild>
            <Pressable
              style={[
                styles.actionCardWide,
                { borderColor: palette.border, backgroundColor: palette.card },
                theme === 'light' ? styles.cardLightShadow : null,
              ]}>
              <IconSymbol name="person.crop.circle" size={22} color={iconColor} />
              <View style={styles.actionCopy}>
                <ThemedText style={styles.actionTitle}>{t('home.profile')}</ThemedText>
                <ThemedText style={styles.actionHint}>{t('home.profileHint')}</ThemedText>
              </View>
            </Pressable>
          </Link>
        </View>
      </ThemedView>
    </ParallaxScrollView>
  );
}

const styles = StyleSheet.create({
  heroImage: {
    height: '100%',
    width: '100%',
    position: 'absolute',
  },
  heroCopy: {
    gap: 12,
    paddingHorizontal: 4,
  },
  heroBadge: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
    gap: 6,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 999,
    borderWidth: 1,
    borderColor: '#D2C9B8',
    backgroundColor: '#F6F1E8',
  },
  heroBadgeText: {
    fontSize: 12,
    fontWeight: '600',
  },
  heroTitle: {
    fontFamily: Fonts.rounded,
    fontSize: 28,
  },
  heroSubtitle: {
    opacity: 0.8,
    fontSize: 15,
    lineHeight: 22,
  },
  heroActions: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  section: {
    gap: 12,
  },
  actionGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    columnGap: 20,
    rowGap: 16,
  },
  actionCard: {
    flexBasis: '49%',
    flexGrow: 1,
    gap: 6,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: '#D9D1C2',
    padding: 12,
    backgroundColor: '#FBF8F1',
    alignItems: 'center',
  },
  actionCardWide: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 12,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: '#D9D1C2',
    padding: 12,
    backgroundColor: '#FBF8F1',
    flexBasis: '100%',
  },
  actionCopy: {
    gap: 4,
  },
  actionHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 8,
  },
  actionTitle: {
    fontSize: 16,
    fontWeight: '600',
  },
  actionHint: {
    fontSize: 12,
    opacity: 0.7,
  },
  highlightCard: {
    borderRadius: 16,
    borderWidth: 1,
    borderColor: '#D6CCB9',
    backgroundColor: '#EFE7D6',
    padding: 16,
    gap: 10,
  },
  highlightHeader: {
    gap: 8,
  },
  highlightCounts: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  highlightTitle: {
    fontSize: 18,
    fontWeight: '700',
  },
  highlightBody: {
    fontSize: 14,
    lineHeight: 20,
    opacity: 0.8,
  },
  highlightActions: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  countBadge: {
    minWidth: 28,
    borderRadius: 999,
    borderWidth: 1,
    borderColor: '#D9D1C2',
    backgroundColor: '#F6F1E8',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
  },
  countText: {
    fontSize: 11,
    fontWeight: '600',
  },
  cardLightShadow: {
    shadowColor: '#1E1A12',
    shadowOpacity: 0.08,
    shadowRadius: 10,
    shadowOffset: { width: 0, height: 6 },
    elevation: 2,
  },
});
