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

import { ThemedButton } from '@/components/themed-button';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { ZoomImageModal } from '@/components/zoom-image-modal';
import { Colors } from '@/constants/theme';
import { useColorScheme } from '@/hooks/use-color-scheme';
import { useTranslation } from '@/localization/i18n';
import { dbPromise, initCoreTables } from '@/services/db';

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

type CropMediaRow = {
  uri: string | null;
};

export default function NewCropScreen() {
  const { t } = useTranslation();
  const router = useRouter();
  const theme = useColorScheme() ?? 'light';
  const palette = Colors[theme];

  const [status, setStatus] = useState('');
  const [fields, setFields] = useState<FieldRow[]>([]);
  const [fieldModalOpen, setFieldModalOpen] = useState(false);
  const [selectedFieldId, setSelectedFieldId] = useState<number | null>(null);
  const [cropName, setCropName] = useState('');
  const [variety, setVariety] = useState('');
  const [plantingDate, setPlantingDate] = useState('');
  const [harvestDate, setHarvestDate] = useState('');
  const [showPlantingPicker, setShowPlantingPicker] = useState(false);
  const [showHarvestPicker, setShowHarvestPicker] = useState(false);
  const [mediaUris, setMediaUris] = useState<string[]>([]);
  const [activeUri, setActiveUri] = useState<string | null>(null);
  const [errors, setErrors] = useState<{ field?: string; crop?: string }>({});
  const [zoomUri, setZoomUri] = useState<string | null>(null);
  const [saving, setSaving] = useState(false);

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

    async function loadFields() {
      try {
        await initCoreTables();
        const db = await dbPromise;
        const fieldRows = await db.getAllAsync<FieldRow>('SELECT id, name FROM fields ORDER BY name ASC;');
        if (!isActive) return;
        setFields(fieldRows);
      } catch (error) {
        if (isActive) setStatus(`Error: ${String(error)}`);
      }
    }

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

  const selectedField = useMemo(
    () => fields.find((item) => item.id === selectedFieldId),
    [fields, selectedFieldId]
  );

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

  async function handleSave() {
    const nextErrors: { field?: string; crop?: string } = {};
    if (!selectedFieldId) {
      nextErrors.field = t('crops.fieldRequired');
    }
    if (!cropName.trim()) {
      nextErrors.crop = t('crops.nameRequired');
    }
    setErrors(nextErrors);
    if (Object.keys(nextErrors).length > 0) return;
    try {
      setSaving(true);
      const db = await dbPromise;
      const now = new Date().toISOString();
      const primaryUri = mediaUris[0] ?? normalizeMediaUri(activeUri);
      const result = await db.runAsync(
        'INSERT INTO crops (field_id, crop_name, variety, planting_date, expected_harvest_date, photo_uri) VALUES (?, ?, ?, ?, ?, ?);',
        selectedFieldId,
        cropName.trim(),
        variety.trim() || null,
        plantingDate || null,
        harvestDate || null,
        primaryUri ?? null
      );
      const cropId = Number(result.lastInsertRowId);
      if (cropId) {
        const mediaToInsert = uniqueMediaUris([
          ...mediaUris,
          ...(normalizeMediaUri(activeUri) ? [normalizeMediaUri(activeUri) as string] : []),
        ]);
        for (const uri of mediaToInsert) {
          await db.runAsync(
            'INSERT INTO crop_media (crop_id, uri, media_type, created_at) VALUES (?, ?, ?, ?);',
            cropId,
            uri,
            isVideoUri(uri) ? 'video' : 'image',
            now
          );
        }
      }
      setStatus(t('crops.saved'));
      router.back();
    } catch (error) {
      setStatus(`Error: ${String(error)}`);
    } finally {
      setSaving(false);
    }
  }

  return (
    <ThemedView style={[styles.container, { backgroundColor: palette.background }]}>
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        style={styles.keyboardAvoid}>
        <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
          <ThemedText type="title">{t('crops.new')}</ThemedText>
          {status ? <ThemedText>{status}</ThemedText> : null}

          <ThemedText>{t('crops.field')}</ThemedText>
          <ThemedButton
            title={selectedField?.name || t('crops.selectField')}
            onPress={() => setFieldModalOpen(true)}
            variant="secondary"
          />
          {errors.field ? <ThemedText style={styles.errorText}>{errors.field}</ThemedText> : null}

          <ThemedText>{t('crops.name')}</ThemedText>
          <TextInput
            value={cropName}
            onChangeText={(value) => {
              setCropName(value);
              if (errors.crop) setErrors((prev) => ({ ...prev, crop: undefined }));
            }}
            placeholder={t('crops.namePlaceholder')}
            placeholderTextColor={palette.placeholder}
            style={inputStyle}
          />
          {errors.crop ? <ThemedText style={styles.errorText}>{errors.crop}</ThemedText> : null}

          <ThemedText>{t('crops.variety')}</ThemedText>
          <TextInput
            value={variety}
            onChangeText={setVariety}
            placeholder={t('crops.varietyPlaceholder')}
            placeholderTextColor={palette.placeholder}
            style={inputStyle}
          />

          <ThemedText>{t('crops.planting')}</ThemedText>
          <Pressable onPress={() => setShowPlantingPicker(true)} style={styles.dateInput}>
            <ThemedText style={styles.dateValue}>
              {plantingDate || t('crops.selectDate')}
            </ThemedText>
          </Pressable>
          {showPlantingPicker ? (
            <DateTimePicker
              value={plantingDate ? new Date(plantingDate) : new Date()}
              mode="date"
              onChange={(event, date) => {
                setShowPlantingPicker(false);
                if (date) setPlantingDate(toDateOnly(date));
              }}
            />
          ) : null}

          <ThemedText>{t('crops.harvest')}</ThemedText>
          <Pressable onPress={() => setShowHarvestPicker(true)} style={styles.dateInput}>
            <ThemedText style={styles.dateValue}>
              {harvestDate || t('crops.selectDate')}
            </ThemedText>
          </Pressable>
          {showHarvestPicker ? (
            <DateTimePicker
              value={harvestDate ? new Date(harvestDate) : new Date()}
              mode="date"
              onChange={(event, date) => {
                setShowHarvestPicker(false);
                if (date) setHarvestDate(toDateOnly(date));
              }}
            />
          ) : null}

          <ThemedText>{t('crops.addMedia')}</ThemedText>
          {normalizeMediaUri(activeUri) ? (
            isVideoUri(normalizeMediaUri(activeUri) as string) ? (
              <Video
                source={{ uri: normalizeMediaUri(activeUri) as string }}
                style={styles.mediaPreview}
                useNativeControls
                resizeMode={ResizeMode.CONTAIN}
              />
            ) : (
              <Pressable onPress={() => setZoomUri(normalizeMediaUri(activeUri) as string)}>
                <Image source={{ uri: normalizeMediaUri(activeUri) as string }} style={styles.mediaPreview} resizeMode="contain" />
              </Pressable>
            )
          ) : (
            <ThemedText style={styles.photoPlaceholder}>{t('crops.noPhoto')}</ThemedText>
          )}

          {mediaUris.length > 0 ? (
            <ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.mediaStrip}>
              {mediaUris.map((uri) => (
                <Pressable key={uri} style={styles.mediaChip} onPress={() => setActiveUri(uri)}>
                  {isVideoUri(uri) ? (
                    <View style={styles.videoThumb}>
                      <ThemedText style={styles.videoThumbText}>▶</ThemedText>
                    </View>
                  ) : (
                    <Image source={{ uri }} style={styles.mediaThumb} resizeMode="cover" />
                  )}
                  <Pressable
                    style={styles.mediaRemove}
                    onPress={(event) => {
                      event.stopPropagation();
                      setMediaUris((prev) => {
                        const next = prev.filter((item) => item !== uri);
                        setActiveUri((current) => (current === uri ? next[0] ?? null : current));
                        return next;
                      });
                    }}>
                    <ThemedText style={styles.mediaRemoveText}>×</ThemedText>
                  </Pressable>
                </Pressable>
              ))}
            </ScrollView>
          ) : null}

          <View style={styles.photoRow}>
            <ThemedButton
              title={t('crops.pickFromGallery')}
              onPress={() =>
                handlePickMedia((uris) => {
                  if (uris.length === 0) return;
                  setMediaUris((prev) => uniqueMediaUris([...prev, ...uris]));
                  setActiveUri((prev) => prev ?? uris[0]);
                })
              }
              variant="secondary"
            />
            <ThemedButton
              title={t('crops.takeMedia')}
              onPress={() =>
                handleTakeMedia((uri) => {
                  if (!uri) return;
                  setMediaUris((prev) => uniqueMediaUris([...prev, uri]));
                  setActiveUri((prev) => prev ?? uri);
                })
              }
              variant="secondary"
            />
          </View>

          <View style={styles.actions}>
            <ThemedButton
              title={saving ? t('crops.saving') : t('crops.save')}
              onPress={handleSave}
              disabled={saving}
            />
          </View>
        </ScrollView>
      </KeyboardAvoidingView>

      <Modal transparent visible={fieldModalOpen} animationType="fade">
        <Pressable style={styles.modalBackdrop} onPress={() => setFieldModalOpen(false)}>
          <View style={styles.modalCard}>
            <ThemedText type="subtitle">{t('crops.selectField')}</ThemedText>
            <ScrollView style={styles.modalList}>
              {fields.map((item) => (
                <Pressable
                  key={item.id}
                  style={styles.modalItem}
                  onPress={() => {
                    setSelectedFieldId(item.id);
                    setFieldModalOpen(false);
                  }}>
                  <ThemedText>{item.name || t('crops.untitled')}</ThemedText>
                </Pressable>
              ))}
            </ScrollView>
          </View>
        </Pressable>
      </Modal>

      <ZoomImageModal uri={zoomUri} visible={Boolean(zoomUri)} onClose={() => setZoomUri(null)} />
    </ThemedView>
  );
}

async function handlePickMedia(onAdd: (uris: string[]) => void) {
  const result = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: getMediaTypes(),
    quality: 1,
    allowsMultipleSelection: true,
    selectionLimit: 0,
  });
  if (result.canceled) return;
  const uris = (result.assets ?? []).map((asset) => asset.uri).filter(Boolean) as string[];
  if (uris.length === 0) return;
  onAdd(uris);
}

async function handleTakeMedia(onAdd: (uri: string | null) => void) {
  const permission = await ImagePicker.requestCameraPermissionsAsync();
  if (!permission.granted) {
    return;
  }
  const result = await ImagePicker.launchCameraAsync({
    mediaTypes: getMediaTypes(),
    quality: 1,
  });
  if (result.canceled) return;
  const asset = result.assets[0];
  onAdd(asset.uri);
}

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;
}

function uniqueMediaUris(uris: string[]) {
  const seen = new Set<string>();
  const result: string[] = [];
  for (const uri of uris) {
    if (!uri || seen.has(uri)) continue;
    seen.add(uri);
    result.push(uri);
  }
  return result;
}

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  keyboardAvoid: {
    flex: 1,
  },
  content: {
    padding: 16,
    gap: 10,
    paddingBottom: 40,
  },
  input: {
    borderRadius: 10,
    borderWidth: 1,
    paddingHorizontal: 12,
    paddingVertical: 10,
    fontSize: 15,
  },
  errorText: {
    color: '#C0392B',
    fontSize: 12,
  },
  dateInput: {
    borderRadius: 10,
    borderWidth: 1,
    borderColor: '#B9B9B9',
    paddingHorizontal: 12,
    paddingVertical: 10,
  },
  dateValue: {
    opacity: 0.7,
  },
  mediaPreview: {
    width: '100%',
    height: 220,
    borderRadius: 12,
    backgroundColor: '#1C1C1C',
  },
  photoRow: {
    flexDirection: 'row',
    gap: 8,
  },
  actions: {
    marginTop: 12,
    gap: 10,
  },
  photoPlaceholder: {
    opacity: 0.6,
  },
  mediaStrip: {
    marginTop: 6,
  },
  mediaChip: {
    width: 72,
    height: 72,
    borderRadius: 10,
    marginRight: 8,
    overflow: 'hidden',
    backgroundColor: '#E6E1D4',
    alignItems: 'center',
    justifyContent: 'center',
  },
  mediaThumb: {
    width: '100%',
    height: '100%',
  },
  videoThumb: {
    width: '100%',
    height: '100%',
    backgroundColor: '#1C1C1C',
    alignItems: 'center',
    justifyContent: 'center',
  },
  videoThumbText: {
    color: '#FFFFFF',
    fontSize: 18,
    fontWeight: '700',
  },
  mediaRemove: {
    position: 'absolute',
    top: 4,
    right: 4,
    width: 18,
    height: 18,
    borderRadius: 9,
    backgroundColor: 'rgba(0,0,0,0.6)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  mediaRemoveText: {
    color: '#FFFFFF',
    fontSize: 12,
    lineHeight: 14,
    fontWeight: '700',
  },
  modalBackdrop: {
    flex: 1,
    backgroundColor: 'rgba(0,0,0,0.4)',
    justifyContent: 'center',
    padding: 24,
  },
  modalCard: {
    borderRadius: 14,
    backgroundColor: '#FFFFFF',
    padding: 16,
    gap: 10,
    maxHeight: '80%',
  },
  modalList: {
    maxHeight: 300,
  },
  modalItem: {
    paddingVertical: 10,
  },
});
