import { useCreateTransaction } 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 { todayIso } from "@/src/utils/date";
import { formatDateDisplay } from "@/src/utils/format";
import { handleNumpadKey, parseAmountStr } from "@/src/utils/numpad";
import { useState } from "react";
import { Ionicons } from "@expo/vector-icons";
import React from "react";
import { useTranslation } from "react-i18next";
import i18n from "@/src/i18n";
import {
  Modal,
  Pressable,
  ScrollView,
  Switch,
  Text,
  TextInput,
  View,
} from "react-native";

type Props = {
  visible: boolean;
  onClose: () => void;
  onRequestAddCategory: (type: "expense" | "income") => void;
  newCategory?: Category | null;
  defaultScope?: "household" | "private" | "child";
  defaultChildId?: string;
};

export function QuickAddModal({
  visible,
  onClose,
  onRequestAddCategory,
  newCategory,
  defaultScope = "household",
  defaultChildId,
}: Props) {
  const { t: tFn } = useTranslation();
  const [type, setType] = useState<"expense" | "income">("expense");
  const [amountStr, setAmountStr] = useState("0");
  const [selectedCategoryId, setSelectedCategoryId] = useState<string | null>(null);
  const [description, setDescription] = useState("");
  const [isFixed, setIsFixed] = useState(false);
  const [selectedDate, setSelectedDate] = useState<string>(todayIso());
  const [showCategoryPicker, setShowCategoryPicker] = useState(false);

  const { data: categories = [] } = useCategories();
  const filteredCategories = categories.filter((c) => c.type === type);
  const selectedCategory = categories.find((c) => c.id === selectedCategoryId) ?? null;

  // Auto-select newly created category when parent passes it in
  React.useEffect(() => {
    if (newCategory) {
      setSelectedCategoryId(newCategory.id);
      setType(newCategory.type);
    }
  }, [newCategory]);

  const { mutate: createTransaction, isPending } = useCreateTransaction();

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

  function handleSave() {
    const amount = parseAmountStr(amountStr);
    if (!amount || amount <= 0) return;
    createTransaction(
      { amount, type, scope: defaultScope, categoryId: selectedCategoryId ?? undefined, description: description.trim() || undefined, date: new Date(selectedDate).toISOString(), isFixed, childId: defaultChildId ?? undefined },
      { onSuccess: () => { resetState(); onClose(); } },
    );
  }

  function resetState() {
    setAmountStr("0");
    setDescription("");
    setSelectedCategoryId(null);
    setType("expense");
    setIsFixed(false);
    setSelectedDate(todayIso());
    setShowCategoryPicker(false);
  }

  function handleClose() { resetState(); onClose(); }

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

        {/* Type Toggle */}
        <View className="flex-row mx-4 mt-4 p-1 bg-gray-100 rounded-xl">
          {(["expense", "income"] as const).map((t) => (
            <Pressable key={t} onPress={() => { setType(t); setSelectedCategoryId(null); setShowCategoryPicker(false); }}
              className={`flex-1 py-2 rounded-lg items-center ${type === t ? "bg-white shadow-sm" : ""}`}>
              <Text className={`font-medium ${type === t ? (t === "expense" ? "text-red-600" : "text-green-600") : "text-gray-500"}`}>
                {t === "expense" ? tFn('transaction.expense') : tFn('transaction.income')}
              </Text>
            </Pressable>
          ))}
        </View>

        {/* Amount */}
        <View className="items-center py-6">
          <Text className="text-5xl font-bold text-gray-900">€ {amountStr}</Text>
        </View>

        {/* Category Select Row */}
        <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 ? (selectedCategory.icon ?? "ellipsis-horizontal-circle-outline") as React.ComponentProps<typeof Ionicons>["name"] : "pricetag-outline"}
              size={14} color={selectedCategory ? "#fff" : "#9ca3af"}
            />
          </View>
          <Text style={{ flex: 1, fontSize: 14, color: selectedCategory ? "#111827" : "#9ca3af" }}>
            {selectedCategory ? selectedCategory.name : tFn('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>
                );
              })}
              <Pressable
                onPress={() => { setShowCategoryPicker(false); onRequestAddCategory(type); }}
                style={{ flexDirection: "row", alignItems: "center", paddingHorizontal: 14, paddingVertical: 10 }}
              >
                <View style={{ width: 32, height: 32, borderRadius: 16, backgroundColor: "#f3f4f6", alignItems: "center", justifyContent: "center", marginRight: 12 }}>
                  <Ionicons name="add" size={16} color="#9ca3af" />
                </View>
                <Text style={{ fontSize: 14, fontWeight: "500", color: "#6b7280" }}>{tFn('transaction.addNewCategory')}</Text>
              </Pressable>
            </ScrollView>
          </View>
        )}

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

        {/* Date Row */}
        <View className="px-4 mb-3 flex-row items-center" style={{ gap: 10 }}>
          <Ionicons name="calendar-outline" size={20} color="#6b7280" />
          <Text className="text-base text-gray-700 flex-1">{formatDateDisplay(selectedDate, i18n.language, tFn('common.today'))}</Text>
        </View>

        {/* Fixkosten Row */}
        <View className="px-4 mb-4 flex-row items-center" style={{ gap: 10 }}>
          <Ionicons name="repeat-outline" size={20} color="#6b7280" />
          <Text className="text-base text-gray-700 flex-1">{tFn('transaction.repeatMonthly')}</Text>
          <Switch value={isFixed} onValueChange={setIsFixed} trackColor={{ false: "#d1d5db", true: "#2563EB" }} thumbColor="#fff" />
        </View>

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