import { Image } from 'expo-image';
import { FlatList, Pressable, StyleSheet, View } from 'react-native';
import { useCallback, useMemo, 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,
  });

  const quickActions = useMemo(
    () => [
      {
        key: 'fields',
        title: t('home.fields'),
        hint: t('home.fieldsHint'),
        icon: 'map.fill' as const,
        href: { pathname: '/logbook/fields', params: { from: 'home' } },
      },
      {
        key: 'crops',
        title: t('home.crops'),
        hint: t('home.cropsHint'),
        icon: 'leaf.circle.fill' as const,
        href: { pathname: '/logbook/crops', params: { from: 'home' } },
      },
      {
        key: 'observations',
        title: t('home.observations'),
        hint: t('home.observationsHint'),
        icon: 'eye.fill' as const,
        href: { pathname: '/observations', params: { from: 'home' } },
      },
      {
        key: 'harvests',
        title: t('home.harvests'),
        hint: t('home.harvestsHint'),
        icon: 'tray.full.fill' as const,
        href: { pathname: '/harvests', params: { from: 'home' } },
      },
      {
        key: 'sales',
        title: t('home.sales'),
        hint: t('home.salesHint'),
        icon: 'cart.fill' as const,
        href: { pathname: '/sales', params: { from: 'home' } },
      },
      {
        key: 'costs',
        title: t('home.costs'),
        hint: t('home.costsHint'),
        icon: 'dollarsign.circle.fill' as const,
        href: { pathname: '/costs', params: { from: 'home' } },
      },
      {
        key: 'blogs',
        title: t('home.blogs'),
        hint: t('home.blogsHint'),
        icon: 'doc.text.image' as const,
        href: '/blog',
      },
      {
        key: 'profile',
        title: t('home.profile'),
        hint: t('home.profileHint'),
        icon: 'person.crop.circle' as const,
        href: '/setup',
      },
    ],
    [t]
  );

  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.heroCard}>
        <View style={[styles.badge, { borderColor: palette.border, backgroundColor: palette.card }]}>
          <IconSymbol name="leaf.fill" size={16} color={iconColor} />
          <ThemedText style={styles.badgeText}>{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={{ pathname: '/tasks', params: { from: 'home' } }} asChild>
            <ThemedButton title={t('home.todayTasks')} variant="secondary" />
          </Link>
        </View>
      </ThemedView>

      <ThemedView style={styles.section}>
        <ThemedText type="subtitle">{t('home.quickActions')}</ThemedText>
        <FlatList
          data={quickActions}
          keyExtractor={(item) => item.key}
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={styles.actionRow}
          renderItem={({ item }) => (
            <Link href={item.href} asChild>
              <Pressable
                style={[
                  styles.actionCard,
                  { borderColor: palette.border, backgroundColor: palette.card },
                  theme === 'light' ? styles.cardShadow : null,
                ]}>
                <View style={styles.actionIconWrap}>
                <IconSymbol name={item.icon} size={26} color={iconColor} />
                </View>
                <ThemedText style={styles.actionTitle}>{item.title}</ThemedText>
                <ThemedText style={styles.actionHint}>{item.hint}</ThemedText>
              </Pressable>
            </Link>
          )}
        />
      </ThemedView>

      <ThemedView style={styles.section}>
        <ThemedText type="subtitle">{t('home.todayTitle')}</ThemedText>
        <View style={[styles.card, { borderColor: palette.border, backgroundColor: palette.surface }]}>
          <ThemedText style={styles.cardTitle}>{t('home.todayCardTitle')}</ThemedText>
          <View style={styles.countRow}>
            <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>
          <ThemedText style={styles.cardBody}>{t('home.todayCardBody')}</ThemedText>
          <View style={styles.cardActions}>
            <Link href={{ pathname: '/tasks', params: { from: 'home' } }} asChild>
              <ThemedButton title={t('home.openTasks')} />
            </Link>
            <Link href={{ pathname: '/task-history', params: { from: 'home' } }} asChild>
              <ThemedButton title={t('home.taskHistory')} variant="secondary" />
            </Link>
          </View>
        </View>
      </ThemedView>

    </ParallaxScrollView>
  );
}

const styles = StyleSheet.create({
  heroImage: {
    height: '100%',
    width: '100%',
    position: 'absolute',
  },
  heroCard: {
    gap: 12,
    paddingHorizontal: 4,
  },
  badge: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
    gap: 6,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 999,
    borderWidth: 1,
  },
  badgeText: {
    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,
  },
  actionRow: {
    gap: 18,
    paddingRight: 4,
  },
  actionCard: {
    width: 180,
    minWidth: 180,
    maxWidth: 180,
    borderRadius: 14,
    borderWidth: 1,
    padding: 14,
    gap: 10,
    alignItems: 'center',
  },
  actionIconWrap: {
    width: '100%',
    alignItems: 'center',
    justifyContent: 'center',
  },
  actionTitle: {
    fontSize: 16,
    fontWeight: '600',
    textAlign: 'center',
    width: '100%',
  },
  actionHint: {
    fontSize: 12,
    opacity: 0.7,
    textAlign: 'center',
    width: '100%',
  },
  card: {
    borderRadius: 16,
    borderWidth: 1,
    padding: 16,
    gap: 10,
  },
  cardTitle: {
    fontSize: 18,
    fontWeight: '700',
  },
  cardBody: {
    fontSize: 14,
    lineHeight: 20,
    opacity: 0.8,
  },
  countRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  countBadge: {
    borderRadius: 999,
    borderWidth: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 8,
    paddingVertical: 4,
  },
  countText: {
    fontSize: 11,
    fontWeight: '600',
  },
  cardActions: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 12,
  },
  cardShadow: {
    shadowColor: '#1E1A12',
    shadowOpacity: 0.08,
    shadowRadius: 10,
    shadowOffset: { width: 0, height: 6 },
    elevation: 2,
  },
});
