import { useCategories, useDeleteCategory, useUpdateCategory, type Category } from "@/src/hooks/useCategories";
import { AddCategoryModal } from "@/src/components/features/categories/AddCategoryModal";
import { ModalHeader } from "@/src/components/ui/ModalHeader";
import { Ionicons } from "@expo/vector-icons";
import { useRouter } from "expo-router";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import {
  ActivityIndicator,
  Alert,
  Modal,
  Pressable,
  ScrollView,
  Text,
  TextInput,
  View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

// ── Edit Modal ─────────────────────────────────────────────────────────────────

function EditCategoryModal({
  category,
  onClose,
}: {
  category: Category | null;
  onClose: () => void;
}) {
  const [name, setName] = useState(category?.name ?? "");
  const { mutate: update, isPending } = useUpdateCategory();
  const { t } = useTranslation();

  function handleSave() {
    if (!category || !name.trim()) return;
    update(
      { id: category.id, name: name.trim() },
      { onSuccess: onClose },
    );
  }

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

        <View className="px-4 mt-6">
          <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"
            value={name}
            onChangeText={setName}
            autoFocus
          />
          {category?.isDefault && (
            <Text className="text-xs text-gray-400 mt-2">
              {t('categories.defaultWarning')}
            </Text>
          )}
        </View>
      </View>
    </Modal>
  );
}

// ── Category Row ───────────────────────────────────────────────────────────────

function CategoryRow({
  category,
  onEdit,
  onDelete,
}: {
  category: Category;
  onEdit: () => void;
  onDelete: () => void;
}) {
  const { t } = useTranslation();
  return (
    <View className="flex-row items-center justify-between py-3 border-b border-gray-100">
      <View className="flex-row items-center gap-3">
        <View
          className="w-9 h-9 rounded-full items-center justify-center"
          style={{ backgroundColor: category.color ?? "#6b7280" }}
        >
          <Ionicons name={category.icon} size={18} color="#fff" />
        </View>
        <Text className="text-base text-gray-800">{category.name}</Text>
        {category.isDefault && (
          <View className="bg-gray-100 rounded px-1.5 py-0.5">
            <Text className="text-xs text-gray-400">{t('categories.default')}</Text>
          </View>
        )}
      </View>
      <View className="flex-row gap-3">
        <Pressable onPress={onEdit} className="p-1 active:opacity-50">
          <Ionicons name="pencil-outline" size={18} color="#6b7280" />
        </Pressable>
        {!category.isDefault && (
          <Pressable onPress={onDelete} className="p-1 active:opacity-50">
            <Ionicons name="trash-outline" size={18} color="#dc2626" />
          </Pressable>
        )}
      </View>
    </View>
  );
}

// ── Main Screen ────────────────────────────────────────────────────────────────

export default function CategoriesScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { t } = useTranslation();
  const { data: categories = [], isLoading } = useCategories();
  const { mutate: deleteCategory } = useDeleteCategory();

  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [showAddModal, setShowAddModal] = useState(false);
  const [addType, setAddType] = useState<"income" | "expense">("expense");

  const expenseCategories = categories.filter((c) => c.type === "expense");
  const incomeCategories = categories.filter((c) => c.type === "income");

  function handleDelete(category: Category) {
    Alert.alert(
      t('categories.deleteTitle'),
      t('categories.deleteMessage', { name: category.name }),
      [
        { text: t('common.cancel'), style: "cancel" },
        {
          text: t('common.delete'),
          style: "destructive",
          onPress: () =>
            deleteCategory(category.id, {
              onError: (err) => {
                Alert.alert(t('common.error'), err.message);
              },
            }),
        },
      ],
    );
  }

  if (isLoading) {
    return (
      <View className="flex-1 bg-white items-center justify-center">
        <ActivityIndicator size="large" color="#2563EB" />
      </View>
    );
  }

  return (
    <View className="flex-1 bg-gray-50" style={{ paddingTop: insets.top }}>
      {/* Header */}
      <View className="flex-row items-center px-4 py-4 bg-white border-b border-gray-100">
        <Pressable onPress={() => router.push("/(app)/settings")} className="mr-3 active:opacity-50">
          <Ionicons name="chevron-back" size={24} color="#374151" />
        </Pressable>
        <Text className="text-lg font-semibold text-gray-900">{t('settings.categories')}</Text>
      </View>

      <ScrollView contentContainerStyle={{ padding: 16 }}>
        {/* Expense Categories */}
        <View className="mb-6 rounded-xl bg-white p-4">
          <View className="flex-row items-center justify-between mb-3">
            <Text className="text-xs font-medium uppercase text-gray-400">{t('categories.expenseSection')}</Text>
          </View>
          {expenseCategories.map((cat) => (
            <CategoryRow
              key={cat.id}
              category={cat}
              onEdit={() => setEditingCategory(cat)}
              onDelete={() => handleDelete(cat)}
            />
          ))}
          <Pressable
            onPress={() => { setAddType("expense"); setShowAddModal(true); }}
            className="mt-3 flex-row items-center gap-2 py-2 active:opacity-50"
          >
            <Ionicons name="add-circle-outline" size={18} color="#2563EB" />
            <Text className="text-sm font-medium text-blue-600">{t('categories.addExpenseCategory')}</Text>
          </Pressable>
        </View>

        {/* Income Categories */}
        <View className="mb-6 rounded-xl bg-white p-4">
          <View className="flex-row items-center justify-between mb-3">
            <Text className="text-xs font-medium uppercase text-gray-400">{t('categories.incomeSection')}</Text>
          </View>
          {incomeCategories.map((cat) => (
            <CategoryRow
              key={cat.id}
              category={cat}
              onEdit={() => setEditingCategory(cat)}
              onDelete={() => handleDelete(cat)}
            />
          ))}
          <Pressable
            onPress={() => { setAddType("income"); setShowAddModal(true); }}
            className="mt-3 flex-row items-center gap-2 py-2 active:opacity-50"
          >
            <Ionicons name="add-circle-outline" size={18} color="#2563EB" />
            <Text className="text-sm font-medium text-blue-600">{t('categories.addIncomeCategory')}</Text>
          </Pressable>
        </View>
      </ScrollView>

      <EditCategoryModal
        key={editingCategory?.id}
        category={editingCategory}
        onClose={() => setEditingCategory(null)}
      />

      <AddCategoryModal
        visible={showAddModal}
        onClose={() => setShowAddModal(false)}
        defaultType={addType}
      />
    </View>
  );
}
