import { useCreateCategory, type Category } from "@/src/hooks/useCategories";
import { ModalHeader } from "@/src/components/ui/ModalHeader";
import { Ionicons } from "@expo/vector-icons";
import { useState } from "react";
import {
  Modal,
  Pressable,
  ScrollView,
  Text,
  TextInput,
  View,
} from "react-native";
import React from "react";
import { useTranslation } from "react-i18next";

// 30 emoji-like icon names from Ionicons — no external lib needed
const ICON_OPTIONS: Array<{ name: React.ComponentProps<typeof Ionicons>["name"]; label: string }> = [
  { name: "cart-outline", label: "Einkauf" },
  { name: "home-outline", label: "Haus" },
  { name: "car-outline", label: "Auto" },
  { name: "medkit-outline", label: "Gesundheit" },
  { name: "game-controller-outline", label: "Spiel" },
  { name: "happy-outline", label: "Kinder" },
  { name: "airplane-outline", label: "Urlaub" },
  { name: "briefcase-outline", label: "Arbeit" },
  { name: "cash-outline", label: "Geld" },
  { name: "restaurant-outline", label: "Essen" },
  { name: "fitness-outline", label: "Sport" },
  { name: "book-outline", label: "Bildung" },
  { name: "musical-notes-outline", label: "Musik" },
  { name: "phone-portrait-outline", label: "Handy" },
  { name: "wifi-outline", label: "Internet" },
  { name: "shirt-outline", label: "Kleidung" },
  { name: "paw-outline", label: "Tier" },
  { name: "gift-outline", label: "Geschenk" },
  { name: "construct-outline", label: "Reparatur" },
  { name: "cut-outline", label: "Friseur" },
  { name: "bus-outline", label: "Bus" },
  { name: "train-outline", label: "Bahn" },
  { name: "bicycle-outline", label: "Fahrrad" },
  { name: "cafe-outline", label: "Café" },
  { name: "beer-outline", label: "Bar" },
  { name: "tv-outline", label: "TV" },
  { name: "camera-outline", label: "Foto" },
  { name: "flower-outline", label: "Garten" },
  { name: "star-outline", label: "Sonstiges" },
  { name: "ellipsis-horizontal-circle-outline", label: "Allgemein" },
];

const COLORS = [
  "#10b981", "#6366f1", "#f59e0b", "#ef4444", "#8b5cf6",
  "#ec4899", "#0ea5e9", "#6b7280", "#f97316", "#14b8a6",
  "#84cc16", "#a855f7",
];

type Props = {
  visible: boolean;
  onClose: () => void;
  defaultType?: "income" | "expense";
  onCreated?: (cat: Category) => void;
};

export function AddCategoryModal({ visible, onClose, defaultType = "expense", onCreated }: Props) {
  const [name, setName] = useState("");
  const [selectedIcon, setSelectedIcon] = useState<React.ComponentProps<typeof Ionicons>["name"]>("star-outline");
  const [selectedColor, setSelectedColor] = useState(COLORS[0]!);
  const [type, setType] = useState<"income" | "expense">(defaultType);
  const [iconPickerOpen, setIconPickerOpen] = useState(false);

  const { mutate: create, isPending } = useCreateCategory();
  const { t } = useTranslation();

  function handleSave() {
    const trimmed = name.trim();
    if (!trimmed) return;
    create(
      { name: trimmed, icon: selectedIcon, color: selectedColor, type },
      {
        onSuccess: (cat) => {
          onCreated?.(cat);
          resetAndClose();
        },
      },
    );
  }

  function resetAndClose() {
    setName("");
    setSelectedIcon("star-outline");
    setSelectedColor(COLORS[0]!);
    setType(defaultType);
    onClose();
  }

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

        <ScrollView contentContainerStyle={{ padding: 16 }}>
          {/* Type Toggle */}
          <View className="flex-row p-1 bg-gray-100 rounded-xl mb-5">
            <Pressable
              onPress={() => setType("expense")}
              className={`flex-1 py-2 rounded-lg items-center ${type === "expense" ? "bg-white shadow-sm" : ""}`}
            >
              <Text className={`font-medium ${type === "expense" ? "text-red-600" : "text-gray-500"}`}>
                {t('categories.expenseType')}
              </Text>
            </Pressable>
            <Pressable
              onPress={() => setType("income")}
              className={`flex-1 py-2 rounded-lg items-center ${type === "income" ? "bg-white shadow-sm" : ""}`}
            >
              <Text className={`font-medium ${type === "income" ? "text-green-600" : "text-gray-500"}`}>
                {t('categories.incomeType')}
              </Text>
            </Pressable>
          </View>

          {/* Name */}
          <Text className="text-sm font-medium text-gray-700 mb-2">{t('categories.nameLabel')}</Text>
          <TextInput
            className="bg-gray-50 border border-gray-200 rounded-xl px-4 py-3 text-base text-gray-900 mb-5"
            placeholder={t('categories.namePlaceholder')}
            value={name}
            onChangeText={setName}
            autoFocus
          />

          {/* Preview */}
          <View className="flex-row items-center gap-3 mb-5 p-3 bg-gray-50 rounded-xl">
            <View
              className="w-10 h-10 rounded-full items-center justify-center"
              style={{ backgroundColor: selectedColor }}
            >
              <Ionicons name={selectedIcon} size={20} color="#fff" />
            </View>
            <Text className="text-base font-medium text-gray-800">
              {name.trim() || t('common.preview')}
            </Text>
          </View>

          {/* Color Picker */}
          <Text className="text-sm font-medium text-gray-700 mb-3">{t('categories.colorLabel')}</Text>
          <View className="flex-row flex-wrap gap-2 mb-5">
            {COLORS.map((c) => (
              <Pressable
                key={c}
                onPress={() => setSelectedColor(c)}
                style={{
                  width: 36,
                  height: 36,
                  borderRadius: 18,
                  backgroundColor: c,
                  alignItems: "center",
                  justifyContent: "center",
                  borderWidth: selectedColor === c ? 3 : 0,
                  borderColor: "#fff",
                  shadowColor: selectedColor === c ? c : "transparent",
                  shadowOpacity: selectedColor === c ? 0.6 : 0,
                  shadowRadius: 4,
                  elevation: selectedColor === c ? 4 : 0,
                }}
              >
                {selectedColor === c && <Ionicons name="checkmark" size={16} color="#fff" />}
              </Pressable>
            ))}
          </View>

          {/* Icon Picker — select row */}
          <Text className="text-sm font-medium text-gray-700 mb-2">{t('categories.iconLabel')}</Text>
          <Pressable
            onPress={() => setIconPickerOpen((v) => !v)}
            style={{
              flexDirection: "row",
              alignItems: "center",
              backgroundColor: "#f3f4f6",
              borderRadius: 12,
              paddingHorizontal: 14,
              paddingVertical: 12,
              marginBottom: iconPickerOpen ? 8 : 0,
            }}
          >
            <View
              style={{
                width: 32,
                height: 32,
                borderRadius: 16,
                backgroundColor: selectedColor,
                alignItems: "center",
                justifyContent: "center",
                marginRight: 10,
              }}
            >
              <Ionicons name={selectedIcon} size={17} color="#fff" />
            </View>
            <Text style={{ flex: 1, fontSize: 14, color: "#374151" }}>
              {ICON_OPTIONS.find((o) => o.name === selectedIcon)?.label ?? t('categories.selectIcon')}
            </Text>
            <Ionicons
              name={iconPickerOpen ? "chevron-up" : "chevron-down"}
              size={16}
              color="#9ca3af"
            />
          </Pressable>

          {/* Dropdown grid */}
          {iconPickerOpen && (
            <View
              style={{
                backgroundColor: "#fff",
                borderWidth: 1,
                borderColor: "#e5e7eb",
                borderRadius: 12,
                padding: 8,
                flexDirection: "row",
                flexWrap: "wrap",
                gap: 4,
                marginBottom: 8,
              }}
            >
              {ICON_OPTIONS.map((opt) => {
                const active = selectedIcon === opt.name;
                return (
                  <Pressable
                    key={opt.name}
                    onPress={() => {
                      setSelectedIcon(opt.name);
                      setIconPickerOpen(false);
                    }}
                    style={{
                      width: 44,
                      height: 44,
                      borderRadius: 10,
                      alignItems: "center",
                      justifyContent: "center",
                      backgroundColor: active ? selectedColor : "#f3f4f6",
                    }}
                  >
                    <Ionicons name={opt.name} size={20} color={active ? "#fff" : "#6b7280"} />
                  </Pressable>
                );
              })}
            </View>
          )}
        </ScrollView>
      </View>
    </Modal>
  );
}
