import { useEffect, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Image,
  KeyboardAvoidingView,
  Modal,
  Pressable,
  Platform,
  ScrollView,
  StyleSheet,
  TextInput,
  View,
} from 'react-native';
import * as ImagePicker from 'expo-image-picker';

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

type FieldRow = {
  id: number;
  name: string | null;
  area_ha: number | null;
  notes: string | null;
  photo_uri: string | null;
  created_at: string | null;
  updated_at: string | null;
};

export default function FieldsScreen() {
  const { t } = useTranslation();
  const theme = useColorScheme() ?? 'light';
  const palette = Colors[theme];
  const pageSize = 12;
  const [fields, setFields] = useState<FieldRow[]>([]);
  const [status, setStatus] = useState(t('fields.loading'));
  const [name, setName] = useState('');
  const [areaHa, setAreaHa] = useState('');
  const [notes, setNotes] = useState('');
  const [photoUri, setPhotoUri] = useState<string | null>(null);
  const [newModalVisible, setNewModalVisible] = useState(false);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editName, setEditName] = useState('');
  const [editAreaHa, setEditAreaHa] = useState('');
  const [editNotes, setEditNotes] = useState('');
  const [editPhotoUri, setEditPhotoUri] = useState<string | null>(null);
  const [newErrors, setNewErrors] = useState<{ name?: string; area?: string }>({});
  const [editErrors, setEditErrors] = useState<{ name?: string; area?: string }>({});
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [loadingMore, setLoadingMore] = useState(false);

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

    async function loadFields() {
      await fetchFieldsPage(1, true, isActive);
    }

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

  async function fetchFieldsPage(pageToLoad: number, replace: boolean, isActive = true) {
    try {
      await initCoreTables();
      const db = await dbPromise;
      const rows = await db.getAllAsync<FieldRow>(
        'SELECT id, name, area_ha, notes, photo_uri, created_at, updated_at FROM fields ORDER BY id DESC LIMIT ? OFFSET ?;',
        pageSize,
        (pageToLoad - 1) * pageSize
      );
      if (!isActive) return;
      setFields((prev) => (replace ? rows : [...prev, ...rows]));
      setHasMore(rows.length === pageSize);
      setPage(pageToLoad);
      if (replace) {
        setStatus(rows.length === 0 ? t('fields.empty') : '');
      }
    } catch (error) {
      if (isActive) setStatus(`Error: ${String(error)}`);
    } finally {
      if (isActive) setLoadingMore(false);
    }
  }

  async function handleLoadMore() {
    if (loadingMore || !hasMore) return;
    setLoadingMore(true);
    const nextPage = page + 1;
    await fetchFieldsPage(nextPage, false);
  }

  async function handleSave() {
    const trimmedName = name.trim();
    const area = areaHa.trim() ? Number(areaHa) : null;
    const nextErrors: { name?: string; area?: string } = {};
    if (!trimmedName) {
      nextErrors.name = t('fields.nameRequired');
    }
    if (areaHa.trim() && !Number.isFinite(area)) {
      nextErrors.area = t('fields.areaInvalid');
    }
    setNewErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) {
      setStatus(nextErrors.name ?? nextErrors.area ?? t('fields.nameRequired'));
      return false;
    }
    try {
      const db = await dbPromise;
      const now = new Date().toISOString();
      if (editingId) {
        await db.runAsync(
          'UPDATE fields SET name = ?, area_ha = ?, notes = ?, photo_uri = ?, updated_at = ? WHERE id = ?;',
          trimmedName,
          area,
          notes.trim() || null,
          photoUri,
          now,
          editingId
        );
        setEditingId(null);
      } else {
        await db.runAsync(
          'INSERT INTO fields (name, area_ha, notes, photo_uri, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?);',
          trimmedName,
          area,
          notes.trim() || null,
          photoUri,
          now,
          now
        );
      }
      setName('');
      setAreaHa('');
      setNotes('');
      setPhotoUri(null);
      setNewErrors({});
      await fetchFieldsPage(1, true);
      setStatus(t('fields.saved'));
      return true;
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
      return false;
    }
  }

  async function handleDelete(id: number) {
    try {
      const db = await dbPromise;
      await db.runAsync('DELETE FROM fields WHERE id = ?;', id);
      await fetchFieldsPage(1, true);
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
    }
  }

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

  function startEdit(field: FieldRow) {
    setEditingId(field.id);
    setEditName(field.name ?? '');
    setEditAreaHa(field.area_ha !== null ? String(field.area_ha) : '');
    setEditNotes(field.notes ?? '');
    setEditPhotoUri(field.photo_uri ?? null);
    setEditErrors({});
    setEditModalVisible(true);
    setStatus('');
  }

  function cancelEdit() {
    setEditingId(null);
    setEditName('');
    setEditAreaHa('');
    setEditNotes('');
    setEditPhotoUri(null);
    setEditErrors({});
    setEditModalVisible(false);
    setStatus('');
  }

  async function handleUpdate() {
    if (!editingId) return;
    const trimmedName = editName.trim();
    const area = editAreaHa.trim() ? Number(editAreaHa) : null;
    const nextErrors: { name?: string; area?: string } = {};
    if (!trimmedName) {
      nextErrors.name = t('fields.nameRequired');
    }
    if (editAreaHa.trim() && !Number.isFinite(area)) {
      nextErrors.area = t('fields.areaInvalid');
    }
    setEditErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) {
      setStatus(nextErrors.name ?? nextErrors.area ?? t('fields.nameRequired'));
      return;
    }
    try {
      const db = await dbPromise;
      const now = new Date().toISOString();
      await db.runAsync(
        'UPDATE fields SET name = ?, area_ha = ?, notes = ?, photo_uri = ?, updated_at = ? WHERE id = ?;',
        trimmedName,
        area,
        editNotes.trim() || null,
        editPhotoUri,
        now,
        editingId
      );
      setEditModalVisible(false);
      setEditingId(null);
      setEditErrors({});
      await fetchFieldsPage(1, true);
      setStatus(t('fields.saved'));
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
    }
  }

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

  return (
    <>
    <FlatList
      data={fields}
      keyExtractor={(item) => String(item.id)}
      extraData={[photoUri, editModalVisible, editPhotoUri, name, areaHa, notes, status]}
      onEndReached={handleLoadMore}
      onEndReachedThreshold={0.4}
      renderItem={({ item }) => (
          <Pressable onPress={() => startEdit(item)}>
          <ThemedView style={[styles.card, { backgroundColor: palette.card, borderColor: palette.border }]}>
            <ThemedText type="subtitle">{item.name || t('fields.unnamed')}</ThemedText>
            {item.area_ha !== null ? (
              <ThemedText style={styles.meta}>
                {t('fields.areaLabel')} {item.area_ha}
              </ThemedText>
            ) : null}
            {item.photo_uri ? (
              <Image
                source={{ uri: item.photo_uri }}
                style={styles.photoPreview}
                resizeMode="cover"
                onError={(error) =>
                  console.log('[Fields] List image error:', item.photo_uri, error.nativeEvent)
                }
                onLoad={() => console.log('[Fields] List image loaded:', item.photo_uri)}
              />
            ) : null}
            {item.notes ? <ThemedText>{item.notes}</ThemedText> : null}
            <View style={styles.buttonRow}>
              <IconButton
                name="trash"
                onPress={() => confirmDelete(item.id)}
                accessibilityLabel={t('fields.delete')}
                variant="danger"
              />
              {item.updated_at ? (
                  <ThemedText style={styles.metaEnd}>{formatDate(item.updated_at)}</ThemedText>
                ) : null}
              </View>
            </ThemedView>
          </Pressable>
        )}
        ItemSeparatorComponent={() => <View style={styles.separator} />}
        ListHeaderComponent={
          <View>
            <ThemedView style={styles.hero}>
              <Image source={require('@/assets/images/fields.jpg')} style={styles.heroImage} />
            </ThemedView>
            <ThemedView style={styles.titleContainer}>
              <ThemedText type="title" style={{ fontFamily: Fonts.rounded }}>
                {t('fields.title')}
              </ThemedText>
            </ThemedView>

            {status ? (
              <ThemedView style={styles.section}>
                <ThemedText>{status}</ThemedText>
              </ThemedView>
            ) : null}

            <ThemedView style={styles.section}>
              <Pressable
                style={styles.newButton}
                onPress={() => {
                  setNewErrors({});
                  setNewModalVisible(true);
                }}>
                <IconSymbol size={18} name="plus.circle.fill" color="#2F7D4F" />
                <ThemedText style={styles.newButtonText}>{t('fields.new')}</ThemedText>
              </Pressable>
            </ThemedView>
          </View>
        }
        ListFooterComponent={
          <View style={styles.footer}>
            {loadingMore ? <ActivityIndicator /> : null}
          </View>
        }
      />
      <Modal
        visible={editModalVisible}
        animationType="slide"
        transparent
        onRequestClose={cancelEdit}>
        <Pressable style={styles.sheetOverlay} onPress={cancelEdit}>
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
            style={styles.keyboardAvoid}>
            <Pressable
              style={[
                styles.sheet,
                { backgroundColor: palette.card, borderColor: palette.border, paddingBottom: 0 },
              ]}
              onPress={() => {}}>
              <ScrollView
                keyboardShouldPersistTaps="handled"
                contentContainerStyle={styles.sheetContent}>
                <ThemedText type="subtitle">{t('fields.edit')}</ThemedText>
            <ThemedText>
              {t('fields.name')}
              <ThemedText style={styles.requiredMark}> *</ThemedText>
            </ThemedText>
            <TextInput
              value={editName}
              onChangeText={(value) => {
                setEditName(value);
                if (editErrors.name) {
                  setEditErrors((prev) => ({ ...prev, name: undefined }));
                }
              }}
              placeholder={t('fields.name')}
              placeholderTextColor={palette.placeholder}
              style={inputStyle}
            />
            {editErrors.name ? <ThemedText style={styles.errorText}>{editErrors.name}</ThemedText> : null}
            <ThemedText>{t('fields.area')}</ThemedText>
            <TextInput
              value={editAreaHa}
              onChangeText={(value) => {
                setEditAreaHa(value);
                if (editErrors.area) {
                  setEditErrors((prev) => ({ ...prev, area: undefined }));
                }
              }}
              placeholder={t('fields.areaPlaceholder')}
              placeholderTextColor={palette.placeholder}
              style={inputStyle}
              keyboardType="decimal-pad"
            />
            {editErrors.area ? <ThemedText style={styles.errorText}>{editErrors.area}</ThemedText> : null}
            <ThemedText>{t('fields.notes')}</ThemedText>
          <TextInput
            value={editNotes}
            onChangeText={setEditNotes}
            placeholder={t('fields.notesPlaceholder')}
            placeholderTextColor={palette.placeholder}
            style={inputStyle}
            multiline
          />
          <ThemedText>{t('fields.photo')}</ThemedText>
          {editPhotoUri ? (
            <Image
              key={editPhotoUri}
              source={{ uri: editPhotoUri }}
              style={styles.photoPreview}
              resizeMode="cover"
              onError={(error) =>
                console.log('[Fields] Edit image error:', editPhotoUri, error.nativeEvent)
              }
              onLoad={() => console.log('[Fields] Edit image loaded:', editPhotoUri)}
            />
          ) : (
            <ThemedText style={styles.photoPlaceholder}>{t('fields.noPhoto')}</ThemedText>
          )}
          <View style={styles.photoRow}>
            <ThemedButton
              title={t('fields.pickPhoto')}
              onPress={() => handlePickPhoto(setEditPhotoUri)}
              variant="secondary"
            />
            <ThemedButton
              title={t('fields.takePhoto')}
              onPress={() =>
                handleTakePhoto(setEditPhotoUri, (code) =>
                  setStatus(
                    code === 'cameraDenied'
                      ? t('tasks.cameraDenied')
                      : t('tasks.cameraError')
                  )
                )
              }
              variant="secondary"
            />
          </View>
          <View style={styles.modalActions}>
            <ThemedButton title={t('fields.cancel')} onPress={cancelEdit} variant="secondary" />
            <ThemedButton title={t('fields.update')} onPress={handleUpdate} />
          </View>
              </ScrollView>
            </Pressable>
          </KeyboardAvoidingView>
        </Pressable>
      </Modal>
      <Modal
        visible={newModalVisible}
        animationType="slide"
        transparent
        onRequestClose={() => setNewModalVisible(false)}>
        <Pressable style={styles.sheetOverlay} onPress={() => setNewModalVisible(false)}>
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : undefined}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 0 : 0}
            style={styles.keyboardAvoid}>
            <Pressable
              style={[
                styles.sheet,
                { backgroundColor: palette.card, borderColor: palette.border, paddingBottom: 0 },
              ]}
              onPress={() => {}}>
              <ScrollView
                keyboardShouldPersistTaps="handled"
                contentContainerStyle={styles.sheetContent}>
                <ThemedText type="subtitle">{t('fields.new')}</ThemedText>
            <ThemedText>
              {t('fields.name')}
              <ThemedText style={styles.requiredMark}> *</ThemedText>
            </ThemedText>
            <TextInput
              value={name}
              onChangeText={(value) => {
                setName(value);
                if (newErrors.name) {
                  setNewErrors((prev) => ({ ...prev, name: undefined }));
                }
              }}
              placeholder={t('fields.name')}
              placeholderTextColor={palette.placeholder}
              style={inputStyle}
            />
            {newErrors.name ? <ThemedText style={styles.errorText}>{newErrors.name}</ThemedText> : null}
            <ThemedText>{t('fields.area')}</ThemedText>
            <TextInput
              value={areaHa}
              onChangeText={(value) => {
                setAreaHa(value);
                if (newErrors.area) {
                  setNewErrors((prev) => ({ ...prev, area: undefined }));
                }
              }}
              placeholder={t('fields.areaPlaceholder')}
              placeholderTextColor={palette.placeholder}
              style={inputStyle}
              keyboardType="decimal-pad"
            />
            {newErrors.area ? <ThemedText style={styles.errorText}>{newErrors.area}</ThemedText> : null}
            <ThemedText>{t('fields.notes')}</ThemedText>
            <TextInput
              value={notes}
              onChangeText={setNotes}
              placeholder={t('fields.notesPlaceholder')}
              placeholderTextColor={palette.placeholder}
              style={inputStyle}
              multiline
            />
            <ThemedText>{t('fields.photo')}</ThemedText>
            {photoUri ? (
              <Image
                key={photoUri}
                source={{ uri: photoUri }}
                style={styles.photoPreview}
                resizeMode="cover"
                onError={(error) =>
                  console.log('[Fields] New image error:', photoUri, error.nativeEvent)
                }
                onLoad={() => console.log('[Fields] New image loaded:', photoUri)}
              />
            ) : (
              <ThemedText style={styles.photoPlaceholder}>{t('fields.noPhoto')}</ThemedText>
            )}
            <View style={styles.photoRow}>
              <ThemedButton
                title={t('fields.pickPhoto')}
                onPress={() => handlePickPhoto(setPhotoUri)}
                variant="secondary"
              />
              <ThemedButton
                title={t('fields.takePhoto')}
                onPress={() =>
                  handleTakePhoto(setPhotoUri, (code) =>
                    setStatus(
                      code === 'cameraDenied'
                        ? t('tasks.cameraDenied')
                        : t('tasks.cameraError')
                    )
                  )
                }
                variant="secondary"
              />
            </View>
            <View style={styles.modalActions}>
              <ThemedButton
                title={t('fields.cancel')}
                onPress={() => setNewModalVisible(false)}
                variant="secondary"
              />
              <ThemedButton
                title={t('fields.save')}
                onPress={async () => {
                  const ok = await handleSave();
                  if (ok) setNewModalVisible(false);
                }}
              />
            </View>
              </ScrollView>
            </Pressable>
          </KeyboardAvoidingView>
        </Pressable>
      </Modal>
    </>
  );
}

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

async function handlePickPhoto(setter: (value: string | null) => void) {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: getImageMediaTypes(),
    quality: 1,
  });
  if (result.canceled) return;
  const asset = result.assets[0];
  console.log('[Fields] Picked photo:', asset.uri);
  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({ quality: 1 });
    if (result.canceled) return;
    const asset = result.assets[0];
    console.log('[Fields] Captured photo:', asset.uri);
    setter(asset.uri);
  } catch {
    onError?.('cameraError');
  }
}

function getImageMediaTypes() {
  const mediaType = (ImagePicker as { MediaType?: { Image?: unknown; Images?: unknown } })
    .MediaType;
  return mediaType?.Image ?? mediaType?.Images ?? ['images'];
}


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',
  },
  meta: {
    opacity: 0.7,
  },
  input: {
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#B9B9B9',
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
  },
  requiredMark: {
    color: '#C0392B',
    fontWeight: '700',
  },
  errorText: {
    color: '#C0392B',
    fontSize: 12,
  },
  photoPreview: {
    height: 160,
    width: '100%',
    borderRadius: 12,
  },
  buttonRow: {
    alignSelf: 'flex-start',
    flexDirection: 'row',
    gap: 8,
    alignItems: 'center',
    width: '100%',
  },
  metaEnd: {
    marginLeft: 'auto',
    opacity: 0.7,
    fontSize: 12,
  },
  cancelRow: {
    marginTop: 8,
  },
  modalActions: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    gap: 12,
  },
  sheetOverlay: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.3)',
    justifyContent: 'flex-end',
  },
  sheet: {
    borderTopLeftRadius: 16,
    borderTopRightRadius: 16,
    borderWidth: 1,
    borderColor: '#C6C6C6',
    padding: 16,
    backgroundColor: '#FFFFFF',
    gap: 10,
    maxHeight: '85%',
  },
  sheetContent: {
    gap: 10,
    paddingBottom: 80,
  },
  keyboardAvoid: {
    width: '100%',
    flex: 1,
    justifyContent: 'flex-end',
  },
  separator: {
    height: 12,
  },
  footer: {
    height: 24,
  },
  photoRow: {
    flexDirection: 'row',
    gap: 8,
  },
  photoPlaceholder: {
    opacity: 0.6,
  },
});
