import { useUpdateTransaction } from "@/src/hooks/useTransactions";
import { useCategories, type Category } from "@/src/hooks/useCategories";
import { ModalHeader } from "@/src/components/ui/ModalHeader";
import { Numpad } from "@/src/components/ui/Numpad";
import { formatDateDisplay } from "@/src/utils/format";
import { handleNumpadKey, parseAmountStr } from "@/src/utils/numpad";
import { Ionicons } from "@expo/vector-icons";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import i18n from "@/src/i18n";
import {
  Modal,
  Pressable,
  ScrollView,
  Text,
  TextInput,
  View,
} from "react-native";
import type { TransactionWithCategory } from "@/src/hooks/useTransactions";

type Props = {
  transaction: TransactionWithCategory;
  onClose: () => void;
};

function amountToDisplay(amount: string): string {
  return parseFloat(amount).toFixed(2).replace(".", ",");
}

export function EditTransactionModal({ transaction, onClose }: Props) {
  const { t } = useTranslation();
  const [amountStr, setAmountStr] = useState(amountToDisplay(transaction.amount));
  const [description, setDescription] = useState(transaction.description ?? "");
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(
    null, // will be set via category lookup
  );
  const [showCategoryPicker, setShowCategoryPicker] = useState(false);

  const { data: categories = [] } = useCategories();
  const { mutate: updateTransaction, isPending } = useUpdateTransaction();

  // Resolve initial category from transaction's categoryName
  const [resolvedInitial, setResolvedInitial] = useState(false);
  React.useEffect(() => {
    if (!resolvedInitial && categories.length > 0) {
      const match = categories.find((c) => c.name === transaction.categoryName);
      setSelectedCategoryId(match?.id ?? null);
      setResolvedInitial(true);
    }
  }, [categories, resolvedInitial, transaction.categoryName]);

  const filteredCategories = categories.filter((c) => c.type === transaction.type);
  const selectedCategory = categories.find((c) => c.id === selectedCategoryId) ?? null;

  function handleNumpad(key: string) {
    setAmountStr((prev) => handleNumpadKey(prev, key));
  }

  function handleSave() {
    const amount = parseAmountStr(amountStr);
    if (!amount || amount <= 0) return;
    updateTransaction(
      {
        id: transaction.id,
        amount,
        description: description.trim() || undefined,
        categoryId: selectedCategoryId ?? undefined,
      },
      { onSuccess: onClose },
    );
  }

  const canSave = parseAmountStr(amountStr) > 0;

  return (
    <Modal
      visible
      animationType="slide"
      presentationStyle="pageSheet"
      onRequestClose={onClose}
    >
      <View className="flex-1 bg-white">
        {/* Header */}
        <ModalHeader
          title={t('transaction.editTitle')}
          onClose={onClose}
          closeLabel={t('common.cancel')}
          onSave={handleSave}
          saveLabel={t('common.save')}
          saveDisabled={!canSave}
          saveLoading={isPending}
        />

        {/* isFixed warning */}
        {transaction.isFixed && (
          <View className="mx-4 mt-3 px-3 py-2 bg-amber-50 rounded-xl flex-row items-start gap-2">
            <Text className="text-sm">⚠️</Text>
            <Text className="text-xs text-amber-700 flex-1">
              Das ist eine Fixkostenbuchung. Änderungen gelten nur für diesen Monat. Um den Betrag dauerhaft zu ändern, gehe zu Einstellungen → Fixkosten.
            </Text>
          </View>
        )}

        {/* Amount */}
        <View className="items-center py-6">
          <Text
            className="text-5xl font-bold"
            style={{ color: transaction.type === "income" ? "#16a34a" : "#111827" }}
          >
            € {amountStr}
          </Text>
          <Text className="text-sm text-gray-400 mt-1">
            {transaction.type === "income" ? t('transaction.income') : t('transaction.expense')}
          </Text>
        </View>

        {/* Category Select */}
        <Pressable
          onPress={() => setShowCategoryPicker((v) => !v)}
          style={{
            flexDirection: "row", alignItems: "center",
            marginHorizontal: 16, marginBottom: 4,
            paddingHorizontal: 14, paddingVertical: 11,
            backgroundColor: "#f3f4f6", borderRadius: 12,
            borderWidth: selectedCategory ? 1.5 : 0,
            borderColor: selectedCategory ? (selectedCategory.color ?? "#6b7280") : "transparent",
          }}
        >
          <View style={{ width: 28, height: 28, borderRadius: 14, backgroundColor: selectedCategory ? (selectedCategory.color ?? "#6b7280") : "#e5e7eb", alignItems: "center", justifyContent: "center", marginRight: 10 }}>
            <Ionicons
              name={(selectedCategory?.icon ?? "pricetag-outline") as React.ComponentProps<typeof Ionicons>["name"]}
              size={14}
              color={selectedCategory ? "#fff" : "#9ca3af"}
            />
          </View>
          <Text style={{ flex: 1, fontSize: 14, color: selectedCategory ? "#111827" : "#9ca3af" }}>
            {selectedCategory ? selectedCategory.name : t('transaction.selectCategory')}
          </Text>
          {selectedCategory ? (
            <Pressable onPress={(e) => { e.stopPropagation(); setSelectedCategoryId(null); }} hitSlop={8}>
              <Ionicons name="close-circle" size={18} color="#9ca3af" />
            </Pressable>
          ) : (
            <Ionicons name={showCategoryPicker ? "chevron-up" : "chevron-down"} size={16} color="#9ca3af" />
          )}
        </Pressable>

        {/* Inline Category Picker */}
        {showCategoryPicker && (
          <View style={{ marginHorizontal: 16, marginBottom: 4, borderWidth: 1, borderColor: "#e5e7eb", borderRadius: 12, backgroundColor: "#fff", maxHeight: 220 }}>
            <ScrollView bounces={false} keyboardShouldPersistTaps="handled">
              {filteredCategories.map((cat) => {
                const active = cat.id === selectedCategoryId;
                const color = cat.color ?? "#6b7280";
                return (
                  <Pressable
                    key={cat.id}
                    onPress={() => { setSelectedCategoryId(active ? null : cat.id); setShowCategoryPicker(false); }}
                    style={{ flexDirection: "row", alignItems: "center", paddingHorizontal: 14, paddingVertical: 10, backgroundColor: active ? `${color}12` : "#fff", borderBottomWidth: 1, borderBottomColor: "#f3f4f6" }}
                  >
                    <View style={{ width: 32, height: 32, borderRadius: 16, backgroundColor: color, alignItems: "center", justifyContent: "center", marginRight: 12 }}>
                      <Ionicons name={(cat.icon ?? "ellipsis-horizontal-circle-outline") as React.ComponentProps<typeof Ionicons>["name"]} size={16} color="#fff" />
                    </View>
                    <Text style={{ flex: 1, fontSize: 14, fontWeight: "500", color: active ? color : "#111827" }}>{cat.name}</Text>
                    {active && <Ionicons name="checkmark-circle" size={18} color={color} />}
                  </Pressable>
                );
              })}
            </ScrollView>
          </View>
        )}

        {/* Description */}
        <View className="px-4 mt-2 mb-3">
          <TextInput
            className="bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-base text-gray-900"
            placeholder={t('transaction.descriptionOptional')}
            value={description}
            onChangeText={setDescription}
          />
        </View>

        {/* Date (readonly display) */}
        <View className="px-4 mb-4 flex-row items-center" style={{ gap: 10 }}>
          <Ionicons name="calendar-outline" size={20} color="#6b7280" />
          <Text className="text-base text-gray-500">{formatDateDisplay(transaction.date, i18n.language, t('common.today'))}</Text>
        </View>

        {/* Numpad */}
        <Numpad onKeyPress={handleNumpad} />
      </View>
    </Modal>
  );
}
