import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Alert,
  FlatList,
  Image,
  InteractionManager,
  KeyboardAvoidingView,
  Modal,
  Pressable,
  StyleSheet,
  TextInput,
  View,
  Platform,
} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';
import * as ImagePicker from 'expo-image-picker';
import { ResizeMode, Video } from 'expo-av';

import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { ThemedButton } from '@/components/themed-button';
import { IconButton } from '@/components/icon-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 { ZoomImageModal } from '@/components/zoom-image-modal';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useFocusEffect, useNavigation } from '@react-navigation/native';
import { useColorScheme } from '@/hooks/use-color-scheme';

type FieldRow = {
  id: number;
  name: string | null;
};

type CropRow = {
  id: number;
  field_id: number | null;
  crop_name: string | null;
};

type HarvestRow = {
  id: number;
  field_id: number | null;
  crop_id: number | null;
  harvested_at: string | null;
  quantity: number | null;
  unit: string | null;
  notes: string | null;
  photo_uri: string | null;
  field_name: string | null;
  crop_name: string | null;
};

export default function HarvestsScreen() {
  const { t } = useTranslation();
  const router = useRouter();
  const navigation = useNavigation();
  const params = useLocalSearchParams<{ from?: string | string[] }>();
  const theme = useColorScheme() ?? 'light';
  const palette = Colors[theme];
  const fromParam = Array.isArray(params.from) ? params.from[0] : params.from;
  const unitPresets = [
    { key: 'kg', value: 'kg' },
    { key: 'g', value: 'g' },
    { key: 'ton', value: 'ton' },
    { key: 'pcs', value: 'pcs' },
  ];
  const [harvests, setHarvests] = useState<HarvestRow[]>([]);
  const [fields, setFields] = useState<FieldRow[]>([]);
  const [crops, setCrops] = useState<CropRow[]>([]);
  const [status, setStatus] = useState(t('harvests.loading'));
  const [newModalOpen, setNewModalOpen] = useState(false);
  const [editModalOpen, setEditModalOpen] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [fieldModalOpen, setFieldModalOpen] = useState(false);
  const [cropModalOpen, setCropModalOpen] = useState(false);
  const [fieldModalTarget, setFieldModalTarget] = useState<'new' | 'edit'>('new');
  const [cropModalTarget, setCropModalTarget] = useState<'new' | 'edit'>('new');

  const [selectedFieldId, setSelectedFieldId] = useState<number | null>(null);
  const [selectedCropId, setSelectedCropId] = useState<number | null>(null);

  useEffect(() => {
    navigation.setOptions({
      headerLeft: () => (
        <Pressable
          onPress={() => {
            if (fromParam === 'logbook') {
              router.replace('/logbook');
              return;
            }
            if (fromParam === 'home') {
              router.replace('/');
              return;
            }
            router.back();
          }}
          hitSlop={10}
          style={{ paddingHorizontal: 8 }}>
          <IconSymbol name="chevron.left" size={20} color={palette.text} />
        </Pressable>
      ),
    });
  }, [fromParam, navigation, palette.text, router]);
  const [harvestDate, setHarvestDate] = useState('');
  const [showHarvestPicker, setShowHarvestPicker] = useState(false);
  const [quantity, setQuantity] = useState('');
  const [unit, setUnit] = useState('kg');
  const [notes, setNotes] = useState('');
  const [photoUri, setPhotoUri] = useState<string | null>(null);
  const [errors, setErrors] = useState<{ field?: string; crop?: string; quantity?: string }>({});
  const [editFieldId, setEditFieldId] = useState<number | null>(null);
  const [editCropId, setEditCropId] = useState<number | null>(null);
  const [editHarvestDate, setEditHarvestDate] = useState('');
  const [showEditHarvestPicker, setShowEditHarvestPicker] = useState(false);
  const [editQuantity, setEditQuantity] = useState('');
  const [editUnit, setEditUnit] = useState('kg');
  const [editNotes, setEditNotes] = useState('');
  const [editPhotoUri, setEditPhotoUri] = useState<string | null>(null);
  const [zoomUri, setZoomUri] = useState<string | null>(null);
  const [pendingZoomUri, setPendingZoomUri] = useState<string | null>(null);
  const [editErrors, setEditErrors] = useState<{ field?: string; crop?: string; quantity?: string }>(
    {}
  );

  const selectedField = useMemo(
    () => fields.find((item) => item.id === selectedFieldId),
    [fields, selectedFieldId]
  );
  const selectedCrop = useMemo(
    () => crops.find((item) => item.id === selectedCropId),
    [crops, selectedCropId]
  );
  const selectedEditField = useMemo(
    () => fields.find((item) => item.id === editFieldId),
    [fields, editFieldId]
  );
  const selectedEditCrop = useMemo(
    () => crops.find((item) => item.id === editCropId),
    [crops, editCropId]
  );

  useEffect(() => {
    let isActive = true;

    async function loadData() {
      try {
        await initCoreTables();
        const db = await dbPromise;
        const fieldRows = await db.getAllAsync<FieldRow>(
          'SELECT id, name FROM fields ORDER BY name ASC;'
        );
        const cropRows = await db.getAllAsync<CropRow>(
          'SELECT id, field_id, crop_name FROM crops ORDER BY id DESC;'
        );
        const harvestRows = await db.getAllAsync<HarvestRow>(
          `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri,
                  f.name as field_name, c.crop_name as crop_name
           FROM harvests h
           LEFT JOIN fields f ON f.id = h.field_id
           LEFT JOIN crops c ON c.id = h.crop_id
           ORDER BY h.harvested_at DESC;`
        );
        if (!isActive) return;
        setFields(fieldRows);
        setCrops(cropRows);
        setHarvests(harvestRows);
        setStatus(harvestRows.length === 0 ? t('harvests.empty') : '');
      } catch (error) {
        if (isActive) setStatus(`Error: ${String(error)}`);
      }
    }

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

  async function fetchHarvestsPage() {
    try {
      const db = await dbPromise;
      const harvestRows = await db.getAllAsync<HarvestRow>(
        `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri,
                f.name as field_name, c.crop_name as crop_name
         FROM harvests h
         LEFT JOIN fields f ON f.id = h.field_id
         LEFT JOIN crops c ON c.id = h.crop_id
         ORDER BY h.harvested_at DESC;`
      );
      setHarvests(harvestRows);
      setStatus(harvestRows.length === 0 ? t('harvests.empty') : '');
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
    }
  }

  useFocusEffect(
    useCallback(() => {
      fetchHarvestsPage();
    }, [t])
  );

  useEffect(() => {
    if (!newModalOpen && !editModalOpen && pendingZoomUri) {
      const uri = pendingZoomUri;
      setPendingZoomUri(null);
      InteractionManager.runAfterInteractions(() => {
        setTimeout(() => setZoomUri(uri), 150);
      });
    }
  }, [newModalOpen, editModalOpen, pendingZoomUri]);

  async function handleSave() {
    const parsedQty = quantity.trim() ? Number(quantity) : null;
    const nextErrors: { field?: string; crop?: string; quantity?: string } = {};
    if (!selectedFieldId) nextErrors.field = t('harvests.fieldRequired');
    if (!selectedCropId) nextErrors.crop = t('harvests.cropRequired');
    if (!parsedQty || !Number.isFinite(parsedQty)) nextErrors.quantity = t('harvests.quantityInvalid');
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) {
      setStatus(nextErrors.field ?? nextErrors.crop ?? nextErrors.quantity ?? t('harvests.fieldRequired'));
      return false;
    }
    try {
      const db = await dbPromise;
      const now = new Date().toISOString();
      await db.runAsync(
        'INSERT INTO harvests (field_id, crop_id, harvested_at, quantity, unit, notes, photo_uri, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?);',
        selectedFieldId,
        selectedCropId,
        harvestDate.trim() || now,
        parsedQty,
        unit.trim() || null,
        notes.trim() || null,
        photoUri,
        now
      );
      setSelectedFieldId(null);
      setSelectedCropId(null);
      setHarvestDate('');
      setQuantity('');
      setUnit('kg');
      setNotes('');
      setPhotoUri(null);
      setErrors({});
      setStatus(t('harvests.saved'));
      const harvestRows = await db.getAllAsync<HarvestRow>(
        `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri,
                f.name as field_name, c.crop_name as crop_name
         FROM harvests h
         LEFT JOIN fields f ON f.id = h.field_id
         LEFT JOIN crops c ON c.id = h.crop_id
         ORDER BY h.harvested_at DESC;`
      );
      setHarvests(harvestRows);
      return true;
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
      return false;
    }
  }

  function startEdit(item: HarvestRow) {
    router.push(`/harvests/${item.id}`);
  }

  function cancelEdit() {
    setEditingId(null);
    setEditFieldId(null);
    setEditCropId(null);
    setEditHarvestDate('');
    setEditQuantity('');
    setEditUnit('kg');
    setEditNotes('');
    setEditPhotoUri(null);
    setEditErrors({});
    setEditModalOpen(false);
  }

  async function handleUpdate() {
    if (!editingId) return;
    const parsedQty = editQuantity.trim() ? Number(editQuantity) : null;
    const nextErrors: { field?: string; crop?: string; quantity?: string } = {};
    if (!editFieldId) nextErrors.field = t('harvests.fieldRequired');
    if (!editCropId) nextErrors.crop = t('harvests.cropRequired');
    if (!parsedQty || !Number.isFinite(parsedQty)) nextErrors.quantity = t('harvests.quantityInvalid');
    setEditErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) {
      setStatus(nextErrors.field ?? nextErrors.crop ?? nextErrors.quantity ?? t('harvests.fieldRequired'));
      return;
    }
    try {
      const db = await dbPromise;
      const now = new Date().toISOString();
      await db.runAsync(
        'UPDATE harvests SET field_id = ?, crop_id = ?, harvested_at = ?, quantity = ?, unit = ?, notes = ?, photo_uri = ? WHERE id = ?;',
        editFieldId,
        editCropId,
        editHarvestDate.trim() || now,
        parsedQty,
        editUnit.trim() || null,
        editNotes.trim() || null,
        editPhotoUri,
        editingId
      );
      setStatus(t('harvests.saved'));
      setEditModalOpen(false);
      setEditingId(null);
      const harvestRows = await db.getAllAsync<HarvestRow>(
        `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri,
                f.name as field_name, c.crop_name as crop_name
         FROM harvests h
         LEFT JOIN fields f ON f.id = h.field_id
         LEFT JOIN crops c ON c.id = h.crop_id
         ORDER BY h.harvested_at DESC;`
      );
      setHarvests(harvestRows);
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
    }
  }

  function confirmDelete(id: number) {
    Alert.alert(t('harvests.deleteTitle'), t('harvests.deleteMessage'), [
      { text: t('harvests.cancel'), style: 'cancel' },
      { text: t('harvests.delete'), style: 'destructive', onPress: () => handleDelete(id) },
    ]);
  }

  async function handleDelete(id: number) {
    try {
      const db = await dbPromise;
      await db.runAsync('DELETE FROM harvests WHERE id = ?;', id);
      const harvestRows = await db.getAllAsync<HarvestRow>(
        `SELECT h.id, h.field_id, h.crop_id, h.harvested_at, h.quantity, h.unit, h.notes, h.photo_uri,
                f.name as field_name, c.crop_name as crop_name
         FROM harvests h
         LEFT JOIN fields f ON f.id = h.field_id
         LEFT JOIN crops c ON c.id = h.crop_id
         ORDER BY h.harvested_at DESC;`
      );
      setHarvests(harvestRows);
      setStatus(harvestRows.length === 0 ? t('harvests.empty') : '');
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
    }
  }

  const inputStyle = [
    styles.input,
    { borderColor: palette.border, backgroundColor: palette.input, color: palette.text },
  ];

  return (
    <>
      <FlatList
        data={harvests}
        keyExtractor={(item) => String(item.id)}
        renderItem={({ item }) => (
          <Pressable onPress={() => startEdit(item)}>
            <ThemedView style={[styles.card, { backgroundColor: palette.card, borderColor: palette.border }]}>
              <View style={styles.cardHeader}>
                <ThemedText type="subtitle">
                  {item.crop_name || t('harvests.untitled')}
                </ThemedText>
                <IconButton
                  name="trash"
                  onPress={() => confirmDelete(item.id)}
                  accessibilityLabel={t('harvests.delete')}
                  variant="danger"
                />
              </View>
            <ThemedText style={styles.meta}>
              {item.field_name || t('harvests.noField')}
            </ThemedText>
            {item.harvested_at ? (
              <ThemedText style={styles.meta}>{formatDate(item.harvested_at)}</ThemedText>
            ) : null}
            {item.quantity !== null ? (
              <ThemedText>
                {item.quantity} {item.unit || t('harvests.unitPlaceholder')}
              </ThemedText>
            ) : null}
            {normalizeMediaUri(item.photo_uri) ? (
              isVideoUri(normalizeMediaUri(item.photo_uri) as string) ? (
                <Video
                  source={{ uri: normalizeMediaUri(item.photo_uri) as string }}
                  style={styles.videoPreview}
                  useNativeControls
                  resizeMode={ResizeMode.CONTAIN}
                  isMuted
                />
              ) : (
                <Pressable onPress={() => setZoomUri(normalizeMediaUri(item.photo_uri) as string)}>
                  <Image
                    source={{ uri: normalizeMediaUri(item.photo_uri) as string }}
                    style={styles.photoPreview}
                    resizeMode="contain"
                  />
                </Pressable>
              )
            ) : null}
            {item.notes ? <ThemedText>{item.notes}</ThemedText> : null}
            </ThemedView>
          </Pressable>
        )}
        ItemSeparatorComponent={() => <View style={styles.separator} />}
        ListHeaderComponent={
          <View>
            <ThemedView style={styles.hero}>
              <Image source={require('@/assets/images/harvestrecord.jpg')} style={styles.heroImage} />
            </ThemedView>
            <ThemedView style={styles.titleContainer}>
              <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
                {t('harvests.title')}
              </ThemedText>
            </ThemedView>
            {status ? (
              <ThemedView style={styles.section}>
                <ThemedText>{status}</ThemedText>
              </ThemedView>
            ) : null}
            <ThemedView style={styles.section}>
              <Pressable style={styles.newButton} onPress={() => router.push('/harvests/new')}>
                <IconSymbol size={18} name="plus.circle.fill" color="#2F7D4F" />
                <ThemedText style={styles.newButtonText}>{t('harvests.new')}</ThemedText>
              </Pressable>
            </ThemedView>
          </View>
        }
        ListFooterComponent={<View style={styles.footer} />}
      />

      <Modal transparent visible={fieldModalOpen} animationType="fade">
        <Pressable style={styles.modalOverlay} onPress={() => setFieldModalOpen(false)}>
          <View style={[styles.modalCard, { backgroundColor: palette.card, borderColor: palette.border }]}>
            <ThemedText type="subtitle">{t('harvests.selectField')}</ThemedText>
            <FlatList
              data={fields}
              keyExtractor={(item) => String(item.id)}
              renderItem={({ item }) => (
                <Pressable
                  onPress={() => {
                    if (fieldModalTarget === 'edit') {
                      setEditFieldId(item.id);
                      setEditCropId(null);
                      setEditErrors((prev) => ({ ...prev, field: undefined }));
                      setEditModalOpen(true);
                    } else {
                      setSelectedFieldId(item.id);
                      setSelectedCropId(null);
                      setErrors((prev) => ({ ...prev, field: undefined }));
                      setNewModalOpen(true);
                    }
                    setFieldModalOpen(false);
                  }}
                  style={styles.modalItem}>
                  <ThemedText>{item.name || t('harvests.untitled')}</ThemedText>
                </Pressable>
              )}
            />
          </View>
        </Pressable>
      </Modal>

      <Modal transparent visible={cropModalOpen} animationType="fade">
        <Pressable style={styles.modalOverlay} onPress={() => setCropModalOpen(false)}>
          <View style={[styles.modalCard, { backgroundColor: palette.card, borderColor: palette.border }]}>
            <ThemedText type="subtitle">{t('harvests.selectCrop')}</ThemedText>
            <FlatList
              data={crops.filter((item) => {
                const targetField = cropModalTarget === 'edit' ? editFieldId : selectedFieldId;
                return !targetField || item.field_id === targetField;
              })}
              keyExtractor={(item) => String(item.id)}
              renderItem={({ item }) => (
                <Pressable
                  onPress={() => {
                    if (cropModalTarget === 'edit') {
                      setEditCropId(item.id);
                      setEditErrors((prev) => ({ ...prev, crop: undefined }));
                      setEditModalOpen(true);
                    } else {
                      setSelectedCropId(item.id);
                      setErrors((prev) => ({ ...prev, crop: undefined }));
                      setNewModalOpen(true);
                    }
                    setCropModalOpen(false);
                  }}
                  style={styles.modalItem}>
                  <ThemedText>{item.crop_name || t('harvests.untitled')}</ThemedText>
                </Pressable>
              )}
              ListEmptyComponent={
                <ThemedText style={styles.meta}>{t('harvests.noCrop')}</ThemedText>
              }
            />
          </View>
        </Pressable>
      </Modal>

      <Modal transparent visible={newModalOpen} animationType="slide">
        <View style={styles.sheetOverlay}>
          <Pressable style={styles.sheetBackdrop} onPress={() => setNewModalOpen(false)} />
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
            style={styles.keyboardAvoid}>
            <View style={[styles.sheet, { backgroundColor: palette.card, borderColor: palette.border }]}>
              <FlatList
                data={[{ key: 'new' }]}
                keyExtractor={(item) => item.key}
                contentContainerStyle={styles.sheetListContent}
                renderItem={() => (
                  <View style={styles.sheetContent}>
                  <ThemedText type="subtitle">{t('harvests.new')}</ThemedText>
                  <ThemedText>
                    {t('harvests.field')}
                    <ThemedText style={styles.requiredMark}> *</ThemedText>
                  </ThemedText>
                  <ThemedButton
                    title={selectedField?.name || t('harvests.selectField')}
                    onPress={() => {
                      setFieldModalTarget('new');
                      setNewModalOpen(false);
                      setFieldModalOpen(true);
                    }}
                    variant="secondary"
                  />
                  {errors.field ? (
                    <ThemedText style={styles.errorText}>{errors.field}</ThemedText>
                  ) : null}
                  <ThemedText>
                    {t('harvests.crop')}
                    <ThemedText style={styles.requiredMark}> *</ThemedText>
                  </ThemedText>
                  <ThemedButton
                    title={selectedCrop?.crop_name || t('harvests.selectCrop')}
                    onPress={() => {
                      setCropModalTarget('new');
                      setNewModalOpen(false);
                      setCropModalOpen(true);
                    }}
                    variant="secondary"
                  />
                  {errors.crop ? (
                    <ThemedText style={styles.errorText}>{errors.crop}</ThemedText>
                  ) : null}
                  <ThemedText>{t('harvests.date')}</ThemedText>
                  <Pressable onPress={() => setShowHarvestPicker(true)} style={styles.dateInput}>
                    <ThemedText style={styles.dateValue}>
                      {harvestDate ? formatDateLabel(harvestDate) : t('harvests.datePlaceholder')}
                    </ThemedText>
                  </Pressable>
                  {showHarvestPicker ? (
                    <>
                      {Platform.OS === 'ios' ? (
                        <View style={styles.pickerRow}>
                          <ThemedButton
                            title={t('crops.today')}
                            onPress={() => {
                              setHarvestDate(toDateOnly(new Date()));
                              setShowHarvestPicker(false);
                            }}
                            variant="secondary"
                          />
                          <ThemedButton
                            title={t('crops.done')}
                            onPress={() => setShowHarvestPicker(false)}
                            variant="secondary"
                          />
                        </View>
                      ) : null}
                      <DateTimePicker
                        value={harvestDate ? new Date(harvestDate) : new Date()}
                        mode="date"
                        display={Platform.OS === 'ios' ? 'inline' : 'calendar'}
                        onChange={(event, date) => {
                          if (date) setHarvestDate(toDateOnly(date));
                          if (Platform.OS !== 'ios') setShowHarvestPicker(false);
                        }}
                      />
                    </>
                  ) : null}
                  <ThemedText>
                    {t('harvests.quantity')}
                    <ThemedText style={styles.requiredMark}> *</ThemedText>
                  </ThemedText>
                  <TextInput
                    value={quantity}
                    onChangeText={(value) => {
                      setQuantity(value);
                      if (errors.quantity) {
                        setErrors((prev) => ({ ...prev, quantity: undefined }));
                      }
                    }}
                    placeholder={t('harvests.quantityPlaceholder')}
                    style={inputStyle}
                    keyboardType="decimal-pad"
                  />
                  {errors.quantity ? (
                    <ThemedText style={styles.errorText}>{errors.quantity}</ThemedText>
                  ) : null}
                  <ThemedText>{t('harvests.unit')}</ThemedText>
                  <View style={styles.unitRow}>
                    {unitPresets.map((preset) => {
                      const label = t(`units.${preset.key}`);
                      const normalized = unit.trim().toLowerCase();
                      const isActive =
                        label.toLowerCase() === normalized ||
                        preset.value.toLowerCase() === normalized;
                      return (
                        <Pressable
                          key={`unit-${preset.key}`}
                          onPress={() => setUnit(label)}
                          style={[styles.unitChip, isActive && styles.unitChipActive]}>
                          <ThemedText style={isActive ? styles.unitTextActive : styles.unitText}>
                            {label}
                          </ThemedText>
                        </Pressable>
                      );
                    })}
                  </View>
                  <TextInput
                    value={unit}
                    onChangeText={setUnit}
                    placeholder={t('harvests.unitPlaceholder')}
                    style={inputStyle}
                  />
                  <ThemedText>{t('harvests.notes')}</ThemedText>
                  <TextInput
                    value={notes}
                    onChangeText={setNotes}
                    placeholder={t('harvests.notesPlaceholder')}
                    style={inputStyle}
                    multiline
                  />
                  <ThemedText>{t('harvests.addMedia')}</ThemedText>
                  {normalizeMediaUri(photoUri) ? (
                    isVideoUri(normalizeMediaUri(photoUri) as string) ? (
                      <Video
                        source={{ uri: normalizeMediaUri(photoUri) as string }}
                        style={styles.videoPreview}
                        useNativeControls
                        resizeMode={ResizeMode.CONTAIN}
                        isMuted
                      />
                    ) : (
                      <Pressable
                        onPress={() => {
                          setPendingZoomUri(normalizeMediaUri(photoUri) as string);
                          setNewModalOpen(false);
                        }}>
                        <Image
                          source={{ uri: normalizeMediaUri(photoUri) as string }}
                          style={styles.photoPreview}
                          resizeMode="contain"
                        />
                      </Pressable>
                    )
                  ) : (
                    <ThemedText style={styles.photoPlaceholder}>
                      {t('harvests.noPhoto')}
                    </ThemedText>
                  )}
                  <View style={styles.photoRow}>
                    <ThemedButton
                      title={t('harvests.pickFromGallery')}
                      onPress={() => handlePickPhoto(setPhotoUri)}
                      variant="secondary"
                    />
                    <ThemedButton
                      title={t('harvests.takeMedia')}
                      onPress={() =>
                        handleTakePhoto(setPhotoUri, (code) =>
                          setStatus(
                            code === 'cameraDenied'
                              ? t('tasks.cameraDenied')
                              : t('tasks.cameraError')
                          )
                        )
                      }
                      variant="secondary"
                    />
                  </View>
                  <View style={styles.modalActions}>
                    <ThemedButton
                      title={t('harvests.cancel')}
                      onPress={() => setNewModalOpen(false)}
                      variant="secondary"
                    />
                    <ThemedButton
                      title={t('harvests.save')}
                      onPress={async () => {
                        const ok = await handleSave();
                        if (ok) setNewModalOpen(false);
                      }}
                    />
                  </View>
                  <View style={styles.sheetFooter} />
                </View>
                )}
              />
            </View>
          </KeyboardAvoidingView>
        </View>
      </Modal>

      <Modal transparent visible={editModalOpen} animationType="slide">
        <View style={styles.sheetOverlay}>
          <Pressable style={styles.sheetBackdrop} onPress={cancelEdit} />
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
            style={styles.keyboardAvoid}>
            <View style={[styles.sheet, { backgroundColor: palette.card, borderColor: palette.border }]}>
              <FlatList
                data={[{ key: 'edit' }]}
                keyExtractor={(item) => item.key}
                contentContainerStyle={styles.sheetListContent}
                renderItem={() => (
                  <View style={styles.sheetContent}>
                  <ThemedText type="subtitle">{t('harvests.edit')}</ThemedText>
                  <ThemedText>
                    {t('harvests.field')}
                    <ThemedText style={styles.requiredMark}> *</ThemedText>
                  </ThemedText>
                  <ThemedButton
                    title={selectedEditField?.name || t('harvests.selectField')}
                    onPress={() => {
                      setFieldModalTarget('edit');
                      setEditModalOpen(false);
                      setFieldModalOpen(true);
                    }}
                    variant="secondary"
                  />
                  {editErrors.field ? (
                    <ThemedText style={styles.errorText}>{editErrors.field}</ThemedText>
                  ) : null}
                  <ThemedText>
                    {t('harvests.crop')}
                    <ThemedText style={styles.requiredMark}> *</ThemedText>
                  </ThemedText>
                  <ThemedButton
                    title={selectedEditCrop?.crop_name || t('harvests.selectCrop')}
                    onPress={() => {
                      setCropModalTarget('edit');
                      setEditModalOpen(false);
                      setCropModalOpen(true);
                    }}
                    variant="secondary"
                  />
                  {editErrors.crop ? (
                    <ThemedText style={styles.errorText}>{editErrors.crop}</ThemedText>
                  ) : null}
                  <ThemedText>{t('harvests.date')}</ThemedText>
                  <Pressable onPress={() => setShowEditHarvestPicker(true)} style={styles.dateInput}>
                    <ThemedText style={styles.dateValue}>
                      {editHarvestDate
                        ? formatDateLabel(editHarvestDate)
                        : t('harvests.datePlaceholder')}
                    </ThemedText>
                  </Pressable>
                  {showEditHarvestPicker ? (
                    <>
                      {Platform.OS === 'ios' ? (
                        <View style={styles.pickerRow}>
                          <ThemedButton
                            title={t('crops.today')}
                            onPress={() => {
                              setEditHarvestDate(toDateOnly(new Date()));
                              setShowEditHarvestPicker(false);
                            }}
                            variant="secondary"
                          />
                          <ThemedButton
                            title={t('crops.done')}
                            onPress={() => setShowEditHarvestPicker(false)}
                            variant="secondary"
                          />
                        </View>
                      ) : null}
                      <DateTimePicker
                        value={editHarvestDate ? new Date(editHarvestDate) : new Date()}
                        mode="date"
                        display={Platform.OS === 'ios' ? 'inline' : 'calendar'}
                        onChange={(event, date) => {
                          if (date) setEditHarvestDate(toDateOnly(date));
                          if (Platform.OS !== 'ios') setShowEditHarvestPicker(false);
                        }}
                      />
                    </>
                  ) : null}
                  <ThemedText>
                    {t('harvests.quantity')}
                    <ThemedText style={styles.requiredMark}> *</ThemedText>
                  </ThemedText>
                  <TextInput
                    value={editQuantity}
                    onChangeText={(value) => {
                      setEditQuantity(value);
                      if (editErrors.quantity) {
                        setEditErrors((prev) => ({ ...prev, quantity: undefined }));
                      }
                    }}
                    placeholder={t('harvests.quantityPlaceholder')}
                    style={inputStyle}
                    keyboardType="decimal-pad"
                  />
                  {editErrors.quantity ? (
                    <ThemedText style={styles.errorText}>{editErrors.quantity}</ThemedText>
                  ) : null}
                  <ThemedText>{t('harvests.unit')}</ThemedText>
                  <View style={styles.unitRow}>
                    {unitPresets.map((preset) => {
                      const label = t(`units.${preset.key}`);
                      const normalized = editUnit.trim().toLowerCase();
                      const isActive =
                        label.toLowerCase() === normalized ||
                        preset.value.toLowerCase() === normalized;
                      return (
                        <Pressable
                          key={`edit-unit-${preset.key}`}
                          onPress={() => setEditUnit(label)}
                          style={[styles.unitChip, isActive && styles.unitChipActive]}>
                          <ThemedText style={isActive ? styles.unitTextActive : styles.unitText}>
                            {label}
                          </ThemedText>
                        </Pressable>
                      );
                    })}
                  </View>
                  <TextInput
                    value={editUnit}
                    onChangeText={setEditUnit}
                    placeholder={t('harvests.unitPlaceholder')}
                    style={inputStyle}
                  />
                  <ThemedText>{t('harvests.notes')}</ThemedText>
                  <TextInput
                    value={editNotes}
                    onChangeText={setEditNotes}
                    placeholder={t('harvests.notesPlaceholder')}
                    style={inputStyle}
                    multiline
                  />
                  <ThemedText>{t('harvests.addMedia')}</ThemedText>
                  {normalizeMediaUri(editPhotoUri) ? (
                    isVideoUri(normalizeMediaUri(editPhotoUri) as string) ? (
                      <Video
                        source={{ uri: normalizeMediaUri(editPhotoUri) as string }}
                        style={styles.videoPreview}
                        useNativeControls
                        resizeMode={ResizeMode.CONTAIN}
                        isMuted
                      />
                    ) : (
                      <Pressable
                        onPress={() => {
                          setPendingZoomUri(normalizeMediaUri(editPhotoUri) as string);
                          setEditModalOpen(false);
                        }}>
                        <Image
                          source={{ uri: normalizeMediaUri(editPhotoUri) as string }}
                          style={styles.photoPreview}
                          resizeMode="contain"
                        />
                      </Pressable>
                    )
                  ) : (
                    <ThemedText style={styles.photoPlaceholder}>
                      {t('harvests.noPhoto')}
                    </ThemedText>
                  )}
                  <View style={styles.photoRow}>
                    <ThemedButton
                      title={t('harvests.pickFromGallery')}
                      onPress={() => handlePickPhoto(setEditPhotoUri)}
                      variant="secondary"
                    />
                    <ThemedButton
                      title={t('harvests.takeMedia')}
                      onPress={() =>
                        handleTakePhoto(setEditPhotoUri, (code) =>
                          setStatus(
                            code === 'cameraDenied'
                              ? t('tasks.cameraDenied')
                              : t('tasks.cameraError')
                          )
                        )
                      }
                      variant="secondary"
                    />
                  </View>
                  <View style={styles.modalActions}>
                    <ThemedButton
                      title={t('harvests.cancel')}
                      onPress={cancelEdit}
                      variant="secondary"
                    />
                    <ThemedButton title={t('harvests.update')} onPress={handleUpdate} />
                  </View>
                  <View style={styles.sheetFooter} />
                </View>
                )}
              />
            </View>
          </KeyboardAvoidingView>
        </View>
      </Modal>
      <ZoomImageModal
        uri={zoomUri}
        visible={Boolean(zoomUri)}
        onClose={() => setZoomUri(null)}
      />
    </>
  );
}

function formatDate(value: string) {
  try {
    return new Date(value).toLocaleString();
  } catch {
    return value;
  }
}

function formatDateLabel(value: string) {
  try {
    return new Date(value).toISOString().slice(0, 10);
  } catch {
    return value;
  }
}

function toDateOnly(date: Date) {
  return date.toISOString().slice(0, 10);
}

async function handlePickPhoto(setter: (value: string | null) => void) {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: getMediaTypes(),
    quality: 1,
  });
  if (result.canceled) return;
  const asset = result.assets[0];
  setter(asset.uri);
}

async function handleTakePhoto(
  setter: (value: string | null) => void,
  onError?: (msg: string) => void
) {
  try {
    const permission = await ImagePicker.requestCameraPermissionsAsync();
    if (!permission.granted) {
      onError?.('cameraDenied');
      return;
    }
    const result = await ImagePicker.launchCameraAsync({
      mediaTypes: getMediaTypes(),
      quality: 1,
    });
    if (result.canceled) return;
    const asset = result.assets[0];
    setter(asset.uri);
  } catch {
    onError?.('cameraError');
  }
}

function getMediaTypes() {
  const mediaType = (ImagePicker as {
    MediaType?: { Image?: unknown; Images?: unknown; Video?: unknown; Videos?: unknown };
  }).MediaType;
  const imageType = mediaType?.Image ?? mediaType?.Images;
  const videoType = mediaType?.Video ?? mediaType?.Videos;
  if (imageType && videoType) {
    return [imageType, videoType];
  }
  return imageType ?? videoType ?? ['images', 'videos'];
}

function isVideoUri(uri: string) {
  return /\.(mp4|mov|m4v|webm|avi|mkv)(\?.*)?$/i.test(uri);
}

function normalizeMediaUri(uri?: string | null) {
  if (typeof uri !== 'string') return null;
  const trimmed = uri.trim();
  return trimmed ? trimmed : null;
}

const styles = StyleSheet.create({
  hero: {
    backgroundColor: '#E8E6DA',
    aspectRatio: 16 / 9,
    width: '100%',
  },
  heroImage: {
    width: '100%',
    height: '100%',
  },
  titleContainer: {
    gap: 8,
    paddingHorizontal: 16,
    paddingVertical: 12,
  },
  section: {
    gap: 8,
    marginBottom: 16,
    paddingHorizontal: 16,
  },
  newButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#B9B9B9',
    paddingHorizontal: 12,
    paddingVertical: 10,
    alignSelf: 'flex-start',
  },
  newButtonText: {
    fontSize: 15,
    fontWeight: '600',
  },
  card: {
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#C6C6C6',
    padding: 12,
    marginHorizontal: 16,
    gap: 6,
    backgroundColor: '#FFFFFF',
  },
  cardHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: 8,
  },
  meta: {
    opacity: 0.7,
  },
  separator: {
    height: 12,
  },
  footer: {
    height: 24,
  },
  modalOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.3)',
    justifyContent: 'center',
    padding: 16,
  },
  modalCard: {
    borderRadius: 12,
    borderWidth: 1,
    borderColor: '#C6C6C6',
    padding: 16,
    backgroundColor: '#FFFFFF',
    gap: 8,
    maxHeight: '70%',
  },
  modalItem: {
    paddingVertical: 8,
  },
  input: {
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#B9B9B9',
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
  },
  dateInput: {
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#B9B9B9',
    paddingHorizontal: 12,
    paddingVertical: 10,
  },
  dateValue: {
    fontSize: 15,
    opacity: 0.9,
  },
  pickerRow: {
    flexDirection: 'row',
    gap: 8,
  },
  modalActions: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 12,
  },
  sheetOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.3)',
    justifyContent: 'flex-end',
  },
  sheetBackdrop: {
    ...StyleSheet.absoluteFillObject,
  },
  sheet: {
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    borderWidth: 1,
    borderColor: '#C6C6C6',
    padding: 16,
    backgroundColor: '#FFFFFF',
    gap: 10,
    maxHeight: '85%',
  },
  sheetContent: {
    gap: 10,
  },
  sheetListContent: {
    paddingBottom: 80,
  },
  sheetFooter: {
    height: 24,
  },
  keyboardAvoid: {
    width: '100%',
    flex: 1,
    justifyContent: 'flex-end',
  },
  photoRow: {
    flexDirection: 'row',
    gap: 12,
  },
  photoPreview: {
    width: '100%',
    height: 200,
    borderRadius: 12,
  },
  videoPreview: {
    width: '100%',
    height: 200,
    borderRadius: 12,
    backgroundColor: '#1C1C1C',
  },
  photoPlaceholder: {
    opacity: 0.6,
  },
  unitRow: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: 8,
  },
  unitChip: {
    borderRadius: 999,
    borderWidth: 1,
    borderColor: '#C6C6C6',
    paddingHorizontal: 10,
    paddingVertical: 4,
  },
  unitChipActive: {
    borderColor: '#2F7D4F',
    backgroundColor: '#E7F3EA',
  },
  unitText: {
    fontSize: 12,
  },
  unitTextActive: {
    fontSize: 12,
    color: '#2F7D4F',
    fontWeight: '600',
  },
  requiredMark: {
    color: '#C0392B',
    fontWeight: '700',
  },
  errorText: {
    color: '#C0392B',
    fontSize: 12,
  },
});
