import { Pressable, ScrollView, StyleSheet, View } from 'react-native';
import { useEffect, useState } from 'react';
import { Image } from 'expo-image';

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

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

  useEffect(() => {
    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 (
    <ThemedView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        <ThemedView style={styles.hero}>
          <Image
            source={require('@/assets/images/logbook.jpg')}
            style={styles.heroImage}
            contentFit="cover"
          />
        </ThemedView>
        <ThemedView style={styles.titleContainer}>
          <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
            {t('logbook.title')}
          </ThemedText>
          <ThemedText style={styles.subtitle}>{t('logbook.subtitle')}</ThemedText>
        </ThemedView>

        <View style={styles.grid}>
          <Link href="/logbook/fields" asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="square.grid.2x2.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.fields')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.fields}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.fieldsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href="/logbook/crops" asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="leaf.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.crops')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.crops}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.cropsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href={{ pathname: '/observations', params: { from: 'logbook' } }} asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="eye.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.observations')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.observations}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.observationsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href={{ pathname: '/tasks', params: { from: 'logbook' } }} asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="checklist" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.tasks')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.tasks}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.tasksHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href={{ pathname: '/task-history', params: { from: 'logbook' } }} asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="clock.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.history')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.history}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.historyHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href={{ pathname: '/harvests', params: { from: 'logbook' } }} asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="basket.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.harvests')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.harvests}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.harvestsHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href={{ pathname: '/sales', params: { from: 'logbook' } }} asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="cart.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.sales')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.sales}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.salesHint')}</ThemedText>
            </Pressable>
          </Link>
          <Link href={{ pathname: '/costs', params: { from: 'logbook' } }} asChild>
            <Pressable
              style={[
                styles.card,
                {
                  backgroundColor: palette.card,
                  borderColor: palette.border,
                  ...(theme === 'light' ? styles.cardLightShadow : null),
                },
              ]}>
              <View style={styles.cardHeader}>
                <View style={styles.cardTitleRow}>
                  <View
                    style={[
                      styles.cardIcon,
                      { backgroundColor: palette.surface },
                      theme === 'light' ? styles.cardIconLight : null,
                    ]}>
                    <IconSymbol size={18} color={palette.tint} name="creditcard.fill" />
                  </View>
                  <ThemedText type="subtitle">{t('logbook.costs')}</ThemedText>
                </View>
                <View style={[styles.countBadge, { borderColor: palette.border, backgroundColor: palette.surface }]}>
                  <ThemedText style={styles.countText}>{counts.costs}</ThemedText>
                </View>
              </View>
              <ThemedText style={styles.cardHint}>{t('logbook.costsHint')}</ThemedText>
            </Pressable>
          </Link>
        </View>
      </ScrollView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    paddingBottom: 24,
  },
  hero: {
    backgroundColor: '#E8E6DA',
    aspectRatio: 16 / 9,
    width: '100%',
  },
  heroImage: {
    width: '100%',
    height: '100%',
  },
  titleContainer: {
    gap: 8,
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  subtitle: {
    opacity: 0.7,
  },
  grid: {
    paddingHorizontal: 16,
    gap: 12,
  },
  card: {
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#C6C6C6',
    padding: 16,
    backgroundColor: '#FFFFFF',
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 12,
  },
  cardTitleRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
    flex: 1,
  },
  cardIcon: {
    width: 28,
    height: 28,
    borderRadius: 8,
    backgroundColor: '#E7F3EA',
    alignItems: 'center',
    justifyContent: 'center',
  },
  countBadge: {
    minWidth: 28,
    height: 28,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: '#D9D1C2',
    backgroundColor: '#F6F1E8',
    alignItems: 'center',
    justifyContent: 'center',
    paddingHorizontal: 8,
  },
  countText: {
    fontSize: 12,
    fontWeight: '600',
  },
  cardHint: {
    opacity: 0.7,
    marginTop: 6,
  },
  cardLightShadow: {
    shadowColor: '#1E1A12',
    shadowOpacity: 0.08,
    shadowRadius: 10,
    shadowOffset: { width: 0, height: 6 },
    elevation: 2,
  },
  cardIconLight: {
    borderWidth: 1,
    borderColor: '#E0D7C9',
  },
});
