import { useState, useEffect } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { motion, AnimatePresence } from "framer-motion"
import {
  Plus,
  PiggyBank,
  TrendingUp,
  Wallet,
  Target,
  Users,
  X,
  Calendar,
  ArrowUpCircle,
  ArrowDownCircle,
  AlertTriangle,
  CreditCard,
  Edit2,
  Trash2,
  LayoutDashboard,
  FolderOpen,
  Receipt,
  User,
  Settings,
} from "lucide-react"
import { format } from "date-fns"
import { ru } from "date-fns/locale"
import { savingsApi } from "../api/savings"
import Navigation from "../components/Navigation"
import clsx from "clsx"

function formatCurrency(amount) {
  return new Intl.NumberFormat("ru-RU", {
    style: "currency",
    currency: "RUB",
    maximumFractionDigits: 0,
  }).format(amount)
}

// ==================== TAB NAVIGATION ====================
function TabNav({ activeTab, setActiveTab }) {
  const tabs = [
    { id: "dashboard", label: "Обзор", icon: LayoutDashboard },
    { id: "categories", label: "Категории", icon: FolderOpen },
    { id: "transactions", label: "Операции", icon: Receipt },
  ]

  return (
    <div className="flex gap-1 p-1 bg-gray-100 dark:bg-gray-800 rounded-xl mb-6">
      {tabs.map((tab) => (
        <button
          key={tab.id}
          onClick={() => setActiveTab(tab.id)}
          className={clsx(
            "flex-1 flex items-center justify-center gap-2 py-2.5 px-4 rounded-lg font-medium transition-all text-sm",
            activeTab === tab.id
              ? "bg-white dark:bg-gray-700 text-violet-600 dark:text-violet-400 shadow-sm"
              : "text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300"
          )}
        >
          <tab.icon size={18} />
          <span className="hidden sm:inline">{tab.label}</span>
        </button>
      ))}
    </div>
  )
}

// ==================== DASHBOARD TAB ====================
function DashboardTab({ categories, stats }) {
  const totalBalance = stats?.total_balance || 0
  const monthlyPaymentDetails = stats?.monthly_payment_details || []
  const overdues = stats?.overdues || []
  const activeCategories = categories.filter((c) => !c.is_closed)

  return (
    <div className="space-y-6">
      {/* 1. Total Balance Card */}
      <div className="card p-5 bg-gradient-to-br from-violet-500 to-purple-600 text-white">
        <div className="text-sm opacity-80 mb-1">Общий баланс</div>
        <div className="text-3xl font-bold">{formatCurrency(totalBalance)}</div>
        <div className="mt-3 flex gap-4 text-sm opacity-80">
          <span>📥 Пополнения: {formatCurrency(stats?.total_deposits || 0)}</span>
          <span>📤 Снятия: {formatCurrency(stats?.total_withdrawals || 0)}</span>
        </div>
      </div>

      {/* 2. Active Categories Count */}
      <div className="grid grid-cols-2 gap-3">
        <div className="card p-4 text-center">
          <div className="text-2xl font-bold text-gray-900 dark:text-white">
            {activeCategories.length}
          </div>
          <div className="text-sm text-gray-500 dark:text-gray-400">
            Активных категорий
          </div>
        </div>
        <div className="card p-4 text-center">
          <div className="text-2xl font-bold text-emerald-600 dark:text-emerald-400">
            {categories.filter((c) => c.is_deposit && !c.is_closed).length}
          </div>
          <div className="text-sm text-gray-500 dark:text-gray-400">Депозитов</div>
        </div>
      </div>

      {/* 3. Category Progress */}
      <div className="card p-4">
        <h3 className="font-semibold text-gray-900 dark:text-white mb-3">
          Прогресс по категориям
        </h3>
        <div className="space-y-3">
          {activeCategories.length === 0 ? (
            <p className="text-gray-500 dark:text-gray-400">Нет активных категорий</p>
          ) : (
            activeCategories.slice(0, 6).map((cat) => (
              <div key={cat.id} className="flex items-center gap-3">
                <div
                  className={clsx(
                    "w-8 h-8 rounded-lg flex items-center justify-center text-white",
                    cat.is_deposit
                      ? "bg-amber-500"
                      : cat.is_credit
                      ? "bg-orange-500"
                      : cat.is_recurring
                      ? "bg-emerald-500"
                      : "bg-violet-500"
                  )}
                >
                  {cat.is_deposit ? (
                    <TrendingUp size={16} />
                  ) : cat.is_credit ? (
                    <CreditCard size={16} />
                  ) : cat.is_recurring ? (
                    <Target size={16} />
                  ) : (
                    <PiggyBank size={16} />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-medium text-gray-900 dark:text-white truncate flex items-center gap-1">
                    {cat.name}
                    {cat.is_multi && (
                      <span className="text-xs text-blue-500">(общая)</span>
                    )}
                  </div>
                </div>
                <div className="text-sm font-semibold text-gray-900 dark:text-white">
                  {formatCurrency(cat.current_amount)}
                </div>
              </div>
            ))
          )}
        </div>
      </div>

      {/* 4. Monthly Payments Block */}
      {monthlyPaymentDetails.length > 0 && (
        <div className="card p-4">
          <h3 className="font-semibold text-gray-900 dark:text-white mb-3 flex items-center gap-2">
            <Calendar className="w-5 h-5 text-blue-500" />
            Ежемесячные платежи
            <span className="ml-auto text-lg text-blue-600 dark:text-blue-400 font-bold">
              {formatCurrency(stats?.monthly_payments || 0)}
            </span>
          </h3>
          <div className="space-y-3">
            {monthlyPaymentDetails.map((detail) => (
              <div
                key={detail.category_id}
                className="flex items-center justify-between py-2 border-b border-gray-100 dark:border-gray-800 last:border-0"
              >
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">
                    {detail.category_name}
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    К оплате до {detail.day} числа
                  </div>
                </div>
                <div className="text-right">
                  <div className="font-semibold text-blue-600 dark:text-blue-400">
                    {formatCurrency(detail.amount)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 5. Overdues Block */}
      {overdues.length > 0 && (
        <div className="card p-4 border-2 border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900/20">
          <h3 className="font-semibold text-red-600 dark:text-red-400 mb-3 flex items-center gap-2">
            <AlertTriangle className="w-5 h-5" />
            Просрочки ({overdues.length})
          </h3>
          <div className="space-y-3">
            {overdues.map((overdue) => (
              <div
                key={`${overdue.category_id}-${overdue.month || overdue.days_overdue}`}
                className="flex items-center justify-between py-2 border-b border-red-200 dark:border-red-800 last:border-0"
              >
                <div>
                  <div className="font-medium text-gray-900 dark:text-white flex items-center gap-2">
                    {overdue.category_name}
                    {overdue.month && (
                      <span className="text-xs font-normal text-red-400 bg-red-100 dark:bg-red-900/40 px-1.5 py-0.5 rounded">
                        {overdue.month}
                      </span>
                    )}
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400">
                    Просрочено {overdue.days_overdue} дн. · до {overdue.due_day} числа
                  </div>
                </div>
                <div className="text-right">
                  <div className="font-semibold text-red-600 dark:text-red-400">
                    {formatCurrency(overdue.amount)}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  )
}

// ==================== CATEGORIES TAB ====================
function CategoriesTab({ categories, onEdit, onDelete, onManagePlans }) {
  const [activeSubTab, setActiveSubTab] = useState("active")

  const filteredCategories = categories.filter((c) =>
    activeSubTab === "active" ? !c.is_closed : c.is_closed
  )

  const getTypeInfo = (category) => {
    if (category.is_deposit)
      return { icon: TrendingUp, label: "Депозит", color: "from-amber-500 to-orange-500" }
    if (category.is_credit)
      return { icon: CreditCard, label: "Кредит", color: "from-orange-500 to-red-500" }
    if (category.is_account)
      return { icon: Wallet, label: "Счёт", color: "from-blue-500 to-indigo-500" }
    if (category.is_recurring)
      return { icon: Target, label: "Регулярные", color: "from-emerald-500 to-teal-500" }
    return { icon: PiggyBank, label: "Накопление", color: "from-violet-500 to-purple-500" }
  }

  return (
    <div className="space-y-4">
      {/* Sub-tabs */}
      <div className="flex gap-2">
        <button
          onClick={() => setActiveSubTab("active")}
          className={clsx(
            "px-4 py-2 rounded-lg text-sm font-medium transition",
            activeSubTab === "active"
              ? "bg-violet-100 dark:bg-violet-900/30 text-violet-600 dark:text-violet-400"
              : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
          )}
        >
          📂 Активные ({categories.filter((c) => !c.is_closed).length})
        </button>
        <button
          onClick={() => setActiveSubTab("closed")}
          className={clsx(
            "px-4 py-2 rounded-lg text-sm font-medium transition",
            activeSubTab === "closed"
              ? "bg-violet-100 dark:bg-violet-900/30 text-violet-600 dark:text-violet-400"
              : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
          )}
        >
          🗃️ Закрытые ({categories.filter((c) => c.is_closed).length})
        </button>
      </div>

      {/* Categories List */}
      {filteredCategories.length === 0 ? (
        <div className="card p-8 text-center">
          <PiggyBank className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
          <p className="text-gray-500 dark:text-gray-400">
            {activeSubTab === "active" ? "Нет активных категорий" : "Нет закрытых категорий"}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {filteredCategories.map((category) => {
            const typeInfo = getTypeInfo(category)
            const Icon = typeInfo.icon

            return (
              <motion.div
                key={category.id}
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="card p-4"
              >
                <div className="flex items-start gap-4">
                  <div
                    className={clsx(
                      "w-12 h-12 rounded-xl bg-gradient-to-br flex items-center justify-center text-white",
                      typeInfo.color
                    )}
                  >
                    <Icon className="w-6 h-6" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 mb-1">
                      <h3 className="font-semibold text-gray-900 dark:text-white truncate">
                        {category.name}
                      </h3>
                      {category.is_multi && (
                        <span className="flex items-center gap-1 text-xs text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/30 px-2 py-0.5 rounded-full">
                          <Users size={12} />
                        </span>
                      )}
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 mb-2">
                      {typeInfo.label}
                    </div>
                    <div className="text-xl font-bold text-gray-900 dark:text-white">
                      {formatCurrency(category.current_amount)}
                    </div>

                    {/* Deposit info */}
                    {category.is_deposit && category.interest_rate > 0 && (
                      <div className="mt-2 text-xs text-amber-600 dark:text-amber-400">
                        📈 {category.interest_rate}% годовых
                        {category.deposit_term > 0 && ` · ${category.deposit_term} мес.`}
                      </div>
                    )}
                  </div>

                  {/* Actions */}
                  {!category.is_closed && (
                    <div className="flex gap-1">
                      {category.is_recurring && (
                        <button
                          onClick={() => onManagePlans(category)}
                          className="p-2 text-gray-400 hover:text-emerald-500 hover:bg-emerald-50 dark:hover:bg-emerald-900/20 rounded-lg transition"
                          title="Управление планами"
                        >
                          <Settings size={18} />
                        </button>
                      )}
                      <button
                        onClick={() => onEdit(category)}
                        className="p-2 text-gray-400 hover:text-violet-500 hover:bg-violet-50 dark:hover:bg-violet-900/20 rounded-lg transition"
                      >
                        <Edit2 size={18} />
                      </button>
                      <button
                        onClick={() => onDelete(category)}
                        className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition"
                      >
                        <Trash2 size={18} />
                      </button>
                    </div>
                  )}
                </div>
              </motion.div>
            )
          })}
        </div>
      )}
    </div>
  )
}

// ==================== TRANSACTIONS TAB ====================
function TransactionsTab({ transactions, categories, onAddTransaction, onEditTransaction, onDeleteTransaction }) {
  const [filter, setFilter] = useState("")

  const filteredTransactions = filter
    ? transactions.filter((t) => t.category_id === parseInt(filter))
    : transactions

  // Debug: log to check for duplicates
  useEffect(() => {
    console.log("[Savings] Transactions loaded:", transactions.length, transactions)
  }, [transactions])

  return (
    <div className="space-y-4">
      {/* Filter */}
      <div className="flex gap-3">
        <select
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
          className="input flex-1"
        >
          <option value="">Все категории</option>
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
        <button onClick={onAddTransaction} className="btn btn-primary">
          <Plus size={18} />
        </button>
      </div>

      {/* Transactions List */}
      <div className="card divide-y divide-gray-100 dark:divide-gray-800">
        {filteredTransactions.length === 0 ? (
          <div className="p-8 text-center">
            <Receipt className="w-12 h-12 mx-auto mb-3 text-gray-300 dark:text-gray-600" />
            <p className="text-gray-500 dark:text-gray-400">Нет операций</p>
          </div>
        ) : (
          filteredTransactions.slice(0, 50).map((tx) => {
            const isDeposit = tx.type === "deposit"
            return (
              <div key={tx.id} className="flex items-center gap-4 p-4 group">
                <div
                  className={clsx(
                    "w-10 h-10 rounded-xl flex items-center justify-center",
                    isDeposit
                      ? "bg-emerald-100 dark:bg-emerald-900/30"
                      : "bg-rose-100 dark:bg-rose-900/30"
                  )}
                >
                  {isDeposit ? (
                    <ArrowDownCircle className="w-5 h-5 text-emerald-600 dark:text-emerald-400" />
                  ) : (
                    <ArrowUpCircle className="w-5 h-5 text-rose-600 dark:text-rose-400" />
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <div className="font-medium text-gray-900 dark:text-white truncate">
                    {tx.category_name || "Транзакция"}
                  </div>
                  <div className="text-xs text-gray-500 dark:text-gray-400 flex flex-wrap items-center gap-x-2">
                    <span className="flex items-center gap-1">
                      <Calendar size={10} />
                      {format(new Date(tx.date), "d MMM yyyy", { locale: ru })}
                    </span>
                    {tx.user_name && (
                      <span className="flex items-center gap-1">
                        <User size={10} />
                        {tx.user_name}
                      </span>
                    )}
                    {tx.description && (
                      <span className="truncate max-w-[150px]">· {tx.description}</span>
                    )}
                  </div>
                </div>
                <div
                  className={clsx(
                    "font-semibold",
                    isDeposit
                      ? "text-emerald-600 dark:text-emerald-400"
                      : "text-rose-600 dark:text-rose-400"
                  )}
                >
                  {isDeposit ? "+" : "-"}
                  {formatCurrency(tx.amount)}
                </div>
                {/* Edit/Delete buttons */}
                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  <button
                    onClick={() => onEditTransaction(tx)}
                    className="p-1.5 text-gray-400 hover:text-violet-500 hover:bg-violet-50 dark:hover:bg-violet-900/20 rounded-lg transition"
                  >
                    <Edit2 size={14} />
                  </button>
                  <button
                    onClick={() => onDeleteTransaction(tx)}
                    className="p-1.5 text-gray-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition"
                  >
                    <Trash2 size={14} />
                  </button>
                </div>
              </div>
            )
          })
        )}
      </div>
    </div>
  )
}

// ==================== MODALS ====================

// Transaction Modal (Create/Edit)
function TransactionModal({ isOpen, onClose, categories, onSubmit, transaction }) {
  const [form, setForm] = useState({
    category_id: "",
    amount: "",
    type: "deposit",
    description: "",
    date: format(new Date(), "yyyy-MM-dd"),
  })

  useEffect(() => {
    if (transaction) {
      setForm({
        category_id: transaction.category_id?.toString() || "",
        amount: transaction.amount?.toString() || "",
        type: transaction.type || "deposit",
        description: transaction.description || "",
        date: transaction.date ? format(new Date(transaction.date), "yyyy-MM-dd") : format(new Date(), "yyyy-MM-dd"),
      })
    } else {
      setForm({
        category_id: "",
        amount: "",
        type: "deposit",
        description: "",
        date: format(new Date(), "yyyy-MM-dd"),
      })
    }
  }, [transaction, isOpen])

  const handleSubmit = (e) => {
    e.preventDefault()
    onSubmit({
      ...form,
      category_id: parseInt(form.category_id),
      amount: parseFloat(form.amount),
    }, transaction?.id)
    onClose()
  }

  if (!isOpen) return null

  return (
    <div
      className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-4 bg-black/50"
      onClick={onClose}
    >
      <motion.div
        initial={{ opacity: 0, y: 100 }}
        animate={{ opacity: 1, y: 0 }}
        exit={{ opacity: 0, y: 100 }}
        className="w-full max-w-lg bg-white dark:bg-gray-900 rounded-2xl p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {transaction ? "Редактировать операцию" : "Новая операция"}
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
            <X size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Категория</label>
            <select
              value={form.category_id}
              onChange={(e) => setForm({ ...form, category_id: e.target.value })}
              className="input w-full"
              required
              disabled={!!transaction}
            >
              <option value="">Выберите категорию</option>
              {categories.filter((c) => !c.is_closed).map((c) => (
                <option key={c.id} value={c.id}>{c.name}</option>
              ))}
            </select>
          </div>

          <div className="flex gap-2">
            <button
              type="button"
              onClick={() => setForm({ ...form, type: "deposit" })}
              className={clsx(
                "flex-1 py-3 rounded-xl flex items-center justify-center gap-2 font-medium transition",
                form.type === "deposit"
                  ? "bg-emerald-500 text-white"
                  : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
              )}
            >
              <ArrowDownCircle size={20} /> Пополнение
            </button>
            <button
              type="button"
              onClick={() => setForm({ ...form, type: "withdrawal" })}
              className={clsx(
                "flex-1 py-3 rounded-xl flex items-center justify-center gap-2 font-medium transition",
                form.type === "withdrawal"
                  ? "bg-rose-500 text-white"
                  : "bg-gray-100 dark:bg-gray-800 text-gray-600 dark:text-gray-400"
              )}
            >
              <ArrowUpCircle size={20} /> Снятие
            </button>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Сумма</label>
            <input
              type="number"
              value={form.amount}
              onChange={(e) => setForm({ ...form, amount: e.target.value })}
              className="input w-full"
              placeholder="0"
              min="0.01"
              step="0.01"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Дата</label>
            <input
              type="date"
              value={form.date}
              onChange={(e) => setForm({ ...form, date: e.target.value })}
              className="input w-full"
              required
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Описание (опционально)</label>
            <input
              type="text"
              value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
              className="input w-full"
              placeholder="Комментарий"
            />
          </div>

          <button type="submit" className="btn btn-primary w-full">
            {transaction ? "Сохранить" : "Добавить операцию"}
          </button>
        </form>
      </motion.div>
    </div>
  )
}

// Delete Transaction Confirmation Modal
function DeleteTransactionModal({ isOpen, onClose, transaction, onConfirm }) {
  if (!isOpen || !transaction) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="w-full max-w-sm bg-white dark:bg-gray-900 rounded-2xl p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="text-center">
          <div className="w-16 h-16 mx-auto mb-4 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center">
            <AlertTriangle className="w-8 h-8 text-red-500" />
          </div>
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-2">Удалить операцию?</h3>
          <p className="text-gray-500 dark:text-gray-400 mb-6">
            Операция на сумму {formatCurrency(transaction.amount)} будет удалена безвозвратно.
          </p>
          <div className="flex gap-3">
            <button onClick={onClose} className="btn flex-1">Отмена</button>
            <button
              onClick={() => { onConfirm(transaction.id); onClose() }}
              className="btn bg-red-500 hover:bg-red-600 text-white flex-1"
            >
              Удалить
            </button>
          </div>
        </div>
      </motion.div>
    </div>
  )
}

// Category Edit Modal
function CategoryEditModal({ isOpen, onClose, category, onSubmit }) {
  const [form, setForm] = useState({
    name: "",
    description: "",
    is_deposit: false,
    is_credit: false,
    is_account: false,
    is_recurring: false,
    is_multi: false,
    initial_capital: "",
    deposit_amount: "",
    interest_rate: "",
    deposit_start_date: "",
    deposit_term: "",
    credit_amount: "",
    credit_term: "",
    credit_rate: "",
    credit_start_date: "",
    recurring_amount: "",
    recurring_day: "",
    recurring_start_date: "",
  })

  useEffect(() => {
    if (category) {
      setForm({
        name: category.name || "",
        description: category.description || "",
        is_deposit: category.is_deposit || false,
        is_credit: category.is_credit || false,
        is_account: category.is_account || false,
        is_recurring: category.is_recurring || false,
        is_multi: category.is_multi || false,
        initial_capital: category.initial_capital?.toString() || "",
        deposit_amount: category.deposit_amount?.toString() || "",
        interest_rate: category.interest_rate?.toString() || "",
        deposit_start_date: category.deposit_start_date?.split("T")[0] || "",
        deposit_term: category.deposit_term?.toString() || "",
        credit_amount: category.credit_amount?.toString() || "",
        credit_term: category.credit_term?.toString() || "",
        credit_rate: category.credit_rate?.toString() || "",
        credit_start_date: category.credit_start_date?.split("T")[0] || "",
        recurring_amount: category.recurring_amount?.toString() || "",
        recurring_day: category.recurring_day?.toString() || "",
        recurring_start_date: category.recurring_start_date?.split("T")[0] || "",
      })
    } else {
      setForm({
        name: "", description: "", is_deposit: false, is_credit: false, is_account: false,
        is_recurring: false, is_multi: false, initial_capital: "", deposit_amount: "",
        interest_rate: "", deposit_start_date: "", deposit_term: "", credit_amount: "",
        credit_term: "", credit_rate: "", credit_start_date: "", recurring_amount: "",
        recurring_day: "", recurring_start_date: "",
      })
    }
  }, [category, isOpen])

  const handleSubmit = (e) => {
    e.preventDefault()
    const data = {
      name: form.name,
      description: form.description,
      is_deposit: form.is_deposit,
      is_credit: form.is_credit,
      is_account: form.is_account,
      is_recurring: form.is_recurring,
      is_multi: form.is_multi,
    }

    if (form.initial_capital) data.initial_capital = parseFloat(form.initial_capital)

    if (form.is_deposit) {
      if (form.deposit_amount) data.deposit_amount = parseFloat(form.deposit_amount)
      if (form.interest_rate) data.interest_rate = parseFloat(form.interest_rate)
      if (form.deposit_start_date) data.deposit_start_date = form.deposit_start_date
      if (form.deposit_term) data.deposit_term = parseInt(form.deposit_term)
    }

    if (form.is_credit) {
      if (form.credit_amount) data.credit_amount = parseFloat(form.credit_amount)
      if (form.credit_term) data.credit_term = parseInt(form.credit_term)
      if (form.credit_rate) data.credit_rate = parseFloat(form.credit_rate)
      if (form.credit_start_date) data.credit_start_date = form.credit_start_date
    }

    if (form.is_recurring) {
      if (form.recurring_amount) data.recurring_amount = parseFloat(form.recurring_amount)
      if (form.recurring_day) data.recurring_day = parseInt(form.recurring_day)
      if (form.recurring_start_date) data.recurring_start_date = form.recurring_start_date
    }

    onSubmit(category?.id, data)
    onClose()
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 overflow-y-auto" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        exit={{ opacity: 0, scale: 0.95 }}
        className="w-full max-w-lg bg-white dark:bg-gray-900 rounded-2xl p-6 my-8"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            {category ? "Редактировать категорию" : "Новая категория"}
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
            <X size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4 max-h-[70vh] overflow-y-auto">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Название</label>
            <input type="text" value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} className="input w-full" required />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Описание</label>
            <textarea value={form.description} onChange={(e) => setForm({ ...form, description: e.target.value })} className="input w-full" rows={2} />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Начальный капитал</label>
            <input type="number" value={form.initial_capital} onChange={(e) => setForm({ ...form, initial_capital: e.target.value })} className="input w-full" step="1000" />
          </div>

          {/* Type toggles */}
          <div className="space-y-3">
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" checked={form.is_deposit} onChange={(e) => setForm({ ...form, is_deposit: e.target.checked, is_credit: false })} className="w-5 h-5 rounded border-gray-300" />
              <span className="text-gray-700 dark:text-gray-300">💰 Депозит</span>
            </label>
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" checked={form.is_credit} onChange={(e) => setForm({ ...form, is_credit: e.target.checked, is_deposit: false })} className="w-5 h-5 rounded border-gray-300" />
              <span className="text-gray-700 dark:text-gray-300">💳 Кредит/Рассрочка</span>
            </label>
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" checked={form.is_recurring} onChange={(e) => setForm({ ...form, is_recurring: e.target.checked })} className="w-5 h-5 rounded border-gray-300" />
              <span className="text-gray-700 dark:text-gray-300">🔄 Повторяющаяся категория</span>
            </label>
            <label className="flex items-center gap-3 cursor-pointer">
              <input type="checkbox" checked={form.is_multi} onChange={(e) => setForm({ ...form, is_multi: e.target.checked })} className="w-5 h-5 rounded border-gray-300" />
              <span className="text-gray-700 dark:text-gray-300">👥 Несколько участников</span>
            </label>
          </div>

          {/* Deposit fields */}
          {form.is_deposit && (
            <div className="p-4 bg-amber-50 dark:bg-amber-900/20 rounded-xl space-y-3">
              <h4 className="font-medium text-amber-800 dark:text-amber-300">Параметры депозита</h4>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Сумма депозита</label>
                  <input type="number" value={form.deposit_amount} onChange={(e) => setForm({ ...form, deposit_amount: e.target.value })} className="input w-full text-sm" step="1000" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Ставка %</label>
                  <input type="number" value={form.interest_rate} onChange={(e) => setForm({ ...form, interest_rate: e.target.value })} className="input w-full text-sm" step="0.1" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Срок (мес)</label>
                  <input type="number" value={form.deposit_term} onChange={(e) => setForm({ ...form, deposit_term: e.target.value })} className="input w-full text-sm" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Дата начала</label>
                  <input type="date" value={form.deposit_start_date} onChange={(e) => setForm({ ...form, deposit_start_date: e.target.value })} className="input w-full text-sm" />
                </div>
              </div>
            </div>
          )}

          {/* Credit fields */}
          {form.is_credit && (
            <div className="p-4 bg-orange-50 dark:bg-orange-900/20 rounded-xl space-y-3">
              <h4 className="font-medium text-orange-800 dark:text-orange-300">Параметры кредита</h4>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Сумма кредита</label>
                  <input type="number" value={form.credit_amount} onChange={(e) => setForm({ ...form, credit_amount: e.target.value })} className="input w-full text-sm" step="1000" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Ставка %</label>
                  <input type="number" value={form.credit_rate} onChange={(e) => setForm({ ...form, credit_rate: e.target.value })} className="input w-full text-sm" step="0.1" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Срок (мес)</label>
                  <input type="number" value={form.credit_term} onChange={(e) => setForm({ ...form, credit_term: e.target.value })} className="input w-full text-sm" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Дата начала</label>
                  <input type="date" value={form.credit_start_date} onChange={(e) => setForm({ ...form, credit_start_date: e.target.value })} className="input w-full text-sm" />
                </div>
              </div>
            </div>
          )}

          {/* Recurring fields */}
          {form.is_recurring && (
            <div className="p-4 bg-emerald-50 dark:bg-emerald-900/20 rounded-xl space-y-3">
              <h4 className="font-medium text-emerald-800 dark:text-emerald-300">Параметры повторения</h4>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Сумма/месяц</label>
                  <input type="number" value={form.recurring_amount} onChange={(e) => setForm({ ...form, recurring_amount: e.target.value })} className="input w-full text-sm" step="1000" />
                </div>
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">День месяца</label>
                  <input type="number" value={form.recurring_day} onChange={(e) => setForm({ ...form, recurring_day: e.target.value })} className="input w-full text-sm" min="1" max="28" />
                </div>
                <div className="col-span-2">
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Дата начала</label>
                  <input type="date" value={form.recurring_start_date} onChange={(e) => setForm({ ...form, recurring_start_date: e.target.value })} className="input w-full text-sm" />
                </div>
              </div>
            </div>
          )}

          <button type="submit" className="btn btn-primary w-full">
            {category ? "Сохранить изменения" : "Создать категорию"}
          </button>
        </form>
      </motion.div>
    </div>
  )
}

// Delete Confirmation Modal
function DeleteModal({ isOpen, onClose, category, onConfirm }) {
  if (!isOpen || !category) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="w-full max-w-sm bg-white dark:bg-gray-900 rounded-2xl p-6"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="text-center">
          <div className="w-16 h-16 mx-auto mb-4 bg-red-100 dark:bg-red-900/30 rounded-full flex items-center justify-center">
            <AlertTriangle className="w-8 h-8 text-red-500" />
          </div>
          <h3 className="text-lg font-bold text-gray-900 dark:text-white mb-2">Удалить категорию?</h3>
          <p className="text-gray-500 dark:text-gray-400 mb-6">
            Категория «{category.name}» и все связанные транзакции будут удалены безвозвратно.
          </p>
          <div className="flex gap-3">
            <button onClick={onClose} className="btn flex-1">Отмена</button>
            <button
              onClick={() => { onConfirm(category.id); onClose() }}
              className="btn bg-red-500 hover:bg-red-600 text-white flex-1"
            >
              Удалить
            </button>
          </div>
        </div>
      </motion.div>
    </div>
  )
}

// Recurring Plans Management Modal
function RecurringPlansModal({ isOpen, onClose, category, queryClient }) {
  const [showAddForm, setShowAddForm] = useState(false)
  const [editingPlan, setEditingPlan] = useState(null)
  const [planForm, setPlanForm] = useState({ effective: "", amount: "", day: "1", user_id: "" })

  const { data: plans = [], isLoading } = useQuery({
    queryKey: ["recurring-plans", category?.id],
    queryFn: () => savingsApi.getRecurringPlans(category.id),
    enabled: !!category?.id && isOpen,
  })

  const { data: members = [] } = useQuery({
    queryKey: ["category-members", category?.id],
    queryFn: () => savingsApi.getMembers(category.id),
    enabled: !!category?.id && category?.is_multi && isOpen,
  })

  const createPlanMutation = useMutation({
    mutationFn: (data) => savingsApi.createRecurringPlan(category.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["recurring-plans", category.id] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
      setShowAddForm(false)
      setPlanForm({ effective: "", amount: "", day: "1", user_id: "" })
    },
  })

  const updatePlanMutation = useMutation({
    mutationFn: ({ id, data }) => savingsApi.updateRecurringPlan(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["recurring-plans", category.id] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
      setEditingPlan(null)
    },
  })

  const deletePlanMutation = useMutation({
    mutationFn: (id) => savingsApi.deleteRecurringPlan(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["recurring-plans", category.id] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const handleSubmit = (e) => {
    e.preventDefault()
    const data = {
      effective: planForm.effective,
      amount: parseFloat(planForm.amount),
      day: parseInt(planForm.day) || 1,
    }
    if (planForm.user_id) {
      data.user_id = parseInt(planForm.user_id)
    }

    if (editingPlan) {
      updatePlanMutation.mutate({ id: editingPlan.id, data })
    } else {
      createPlanMutation.mutate(data)
    }
  }

  const startEdit = (plan) => {
    setEditingPlan(plan)
    setPlanForm({
      effective: plan.effective?.split("T")[0] || "",
      amount: plan.amount?.toString() || "",
      day: plan.day?.toString() || "1",
      user_id: plan.user_id?.toString() || "",
    })
    setShowAddForm(true)
  }

  if (!isOpen || !category) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 overflow-y-auto" onClick={onClose}>
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="w-full max-w-lg bg-white dark:bg-gray-900 rounded-2xl p-6 my-8"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white">
            Планы: {category.name}
          </h2>
          <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
            <X size={20} />
          </button>
        </div>

        {/* Plans List */}
        <div className="space-y-3 mb-4 max-h-[300px] overflow-y-auto">
          {isLoading ? (
            <p className="text-center text-gray-500">Загрузка...</p>
          ) : plans.length === 0 ? (
            <p className="text-center text-gray-500 py-4">Нет планов</p>
          ) : (
            plans.map((plan) => (
              <div key={plan.id} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                <div>
                  <div className="font-medium text-gray-900 dark:text-white">
                    {formatCurrency(plan.amount)} / мес
                  </div>
                  <div className="text-xs text-gray-500">
                    С {format(new Date(plan.effective), "d MMM yyyy", { locale: ru })} · {plan.day} числа
                    {plan.user_id && members.length > 0 && (
                      <span className="ml-1">
                        · {members.find(m => m.user_id === plan.user_id)?.user_name || `ID: ${plan.user_id}`}
                      </span>
                    )}
                  </div>
                </div>
                <div className="flex gap-1">
                  <button onClick={() => startEdit(plan)} className="p-1.5 text-gray-400 hover:text-violet-500 rounded">
                    <Edit2 size={16} />
                  </button>
                  <button onClick={() => deletePlanMutation.mutate(plan.id)} className="p-1.5 text-gray-400 hover:text-red-500 rounded">
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Add/Edit Form */}
        {showAddForm ? (
          <form onSubmit={handleSubmit} className="space-y-3 p-4 bg-emerald-50 dark:bg-emerald-900/20 rounded-xl">
            <h4 className="font-medium text-emerald-800 dark:text-emerald-300">
              {editingPlan ? "Редактировать план" : "Добавить план"}
            </h4>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Дата начала</label>
                <input
                  type="date"
                  value={planForm.effective}
                  onChange={(e) => setPlanForm({ ...planForm, effective: e.target.value })}
                  className="input w-full text-sm"
                  required
                />
              </div>
              <div>
                <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Сумма</label>
                <input
                  type="number"
                  value={planForm.amount}
                  onChange={(e) => setPlanForm({ ...planForm, amount: e.target.value })}
                  className="input w-full text-sm"
                  step="100"
                  required
                />
              </div>
              <div>
                <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">День месяца</label>
                <input
                  type="number"
                  value={planForm.day}
                  onChange={(e) => setPlanForm({ ...planForm, day: e.target.value })}
                  className="input w-full text-sm"
                  min="1"
                  max="28"
                />
              </div>
              {category.is_multi && members.length > 0 && (
                <div>
                  <label className="block text-xs text-gray-600 dark:text-gray-400 mb-1">Участник</label>
                  <select
                    value={planForm.user_id}
                    onChange={(e) => setPlanForm({ ...planForm, user_id: e.target.value })}
                    className="input w-full text-sm"
                  >
                    <option value="">Общий план</option>
                    {members.map((m) => (
                      <option key={m.user_id} value={m.user_id}>{m.user_name}</option>
                    ))}
                  </select>
                </div>
              )}
            </div>
            <div className="flex gap-2">
              <button type="submit" className="btn btn-primary flex-1">
                {editingPlan ? "Сохранить" : "Добавить"}
              </button>
              <button
                type="button"
                onClick={() => { setShowAddForm(false); setEditingPlan(null); setPlanForm({ effective: "", amount: "", day: "1", user_id: "" }) }}
                className="btn flex-1"
              >
                Отмена
              </button>
            </div>
          </form>
        ) : (
          <button
            onClick={() => setShowAddForm(true)}
            className="btn btn-primary w-full flex items-center justify-center gap-2"
          >
            <Plus size={18} /> Добавить план
          </button>
        )}
      </motion.div>
    </div>
  )
}

// ==================== MAIN COMPONENT ====================
export default function Savings() {
  const [activeTab, setActiveTab] = useState("dashboard")
  const [showTransactionModal, setShowTransactionModal] = useState(false)
  const [showCategoryModal, setShowCategoryModal] = useState(false)
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [showDeleteTransactionModal, setShowDeleteTransactionModal] = useState(false)
  const [showPlansModal, setShowPlansModal] = useState(false)
  const [selectedCategory, setSelectedCategory] = useState(null)
  const [categoryToDelete, setCategoryToDelete] = useState(null)
  const [selectedTransaction, setSelectedTransaction] = useState(null)
  const [transactionToDelete, setTransactionToDelete] = useState(null)
  const [categoryForPlans, setCategoryForPlans] = useState(null)
  const queryClient = useQueryClient()

  const { data: categories = [], isLoading } = useQuery({
    queryKey: ["savings-categories"],
    queryFn: savingsApi.listCategories,
  })

  const { data: transactions = [] } = useQuery({
    queryKey: ["savings-transactions"],
    queryFn: () => savingsApi.listTransactions(null, 100),
  })

  const { data: stats } = useQuery({
    queryKey: ["savings-stats"],
    queryFn: savingsApi.getStats,
  })

  const createTransactionMutation = useMutation({
    mutationFn: savingsApi.createTransaction,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["savings-categories"] })
      queryClient.invalidateQueries({ queryKey: ["savings-transactions"] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const updateTransactionMutation = useMutation({
    mutationFn: ({ id, data }) => savingsApi.updateTransaction(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["savings-categories"] })
      queryClient.invalidateQueries({ queryKey: ["savings-transactions"] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const deleteTransactionMutation = useMutation({
    mutationFn: savingsApi.deleteTransaction,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["savings-categories"] })
      queryClient.invalidateQueries({ queryKey: ["savings-transactions"] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const createCategoryMutation = useMutation({
    mutationFn: savingsApi.createCategory,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["savings-categories"] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const updateCategoryMutation = useMutation({
    mutationFn: ({ id, data }) => savingsApi.updateCategory(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["savings-categories"] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const deleteCategoryMutation = useMutation({
    mutationFn: savingsApi.deleteCategory,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["savings-categories"] })
      queryClient.invalidateQueries({ queryKey: ["savings-stats"] })
    },
  })

  const handleEditCategory = (category) => {
    setSelectedCategory(category)
    setShowCategoryModal(true)
  }

  const handleDeleteCategory = (category) => {
    setCategoryToDelete(category)
    setShowDeleteModal(true)
  }

  const handleManagePlans = (category) => {
    setCategoryForPlans(category)
    setShowPlansModal(true)
  }

  const handleSaveCategory = (id, data) => {
    if (id) {
      updateCategoryMutation.mutate({ id, data })
    } else {
      createCategoryMutation.mutate(data)
    }
  }

  const handleEditTransaction = (transaction) => {
    setSelectedTransaction(transaction)
    setShowTransactionModal(true)
  }

  const handleDeleteTransaction = (transaction) => {
    setTransactionToDelete(transaction)
    setShowDeleteTransactionModal(true)
  }

  const handleSaveTransaction = (data, id) => {
    if (id) {
      updateTransactionMutation.mutate({ id, data })
    } else {
      createTransactionMutation.mutate(data)
    }
  }

  return (
    <div className="min-h-screen bg-surface-50 dark:bg-gray-950 gradient-mesh pb-24 transition-colors duration-300">
      <header className="bg-white/70 dark:bg-gray-900/70 backdrop-blur-xl border-b border-gray-100/50 dark:border-gray-800 sticky top-0 z-10">
        <div className="max-w-lg mx-auto px-4 py-4">
          <div className="flex items-center justify-between mb-4">
            <div>
              <h1 className="text-xl font-display font-bold text-gray-900 dark:text-white">Накопления</h1>
              <p className="text-sm text-gray-500 dark:text-gray-400">
                {categories.filter((c) => !c.is_closed).length} категорий
              </p>
            </div>
            <div className="flex gap-2">
              {activeTab === "categories" && (
                <button
                  onClick={() => { setSelectedCategory(null); setShowCategoryModal(true) }}
                  className="btn btn-primary flex items-center gap-2"
                >
                  <Plus size={18} />
                  <span className="hidden sm:inline">Категория</span>
                </button>
              )}
              {activeTab !== "categories" && (
                <button
                  onClick={() => { setSelectedTransaction(null); setShowTransactionModal(true) }}
                  className="btn btn-primary flex items-center gap-2"
                >
                  <Plus size={18} />
                  <span className="hidden sm:inline">Операция</span>
                </button>
              )}
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-lg mx-auto px-4 py-6">
        <TabNav activeTab={activeTab} setActiveTab={setActiveTab} />

        {isLoading ? (
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <div key={i} className="card p-5 animate-pulse">
                <div className="flex items-center gap-4">
                  <div className="w-12 h-12 rounded-xl bg-gray-200 dark:bg-gray-700" />
                  <div className="flex-1">
                    <div className="h-5 bg-gray-200 dark:bg-gray-700 rounded-lg w-1/2 mb-2" />
                    <div className="h-4 bg-gray-200 dark:bg-gray-700 rounded-lg w-1/3" />
                  </div>
                </div>
              </div>
            ))}
          </div>
        ) : (
          <>
            {activeTab === "dashboard" && <DashboardTab categories={categories} stats={stats} />}
            {activeTab === "categories" && (
              <CategoriesTab
                categories={categories}
                onEdit={handleEditCategory}
                onDelete={handleDeleteCategory}
                onManagePlans={handleManagePlans}
              />
            )}
            {activeTab === "transactions" && (
              <TransactionsTab
                transactions={transactions}
                categories={categories}
                onAddTransaction={() => { setSelectedTransaction(null); setShowTransactionModal(true) }}
                onEditTransaction={handleEditTransaction}
                onDeleteTransaction={handleDeleteTransaction}
              />
            )}
          </>
        )}
      </main>

      <Navigation />

      <AnimatePresence>
        {showTransactionModal && (
          <TransactionModal
            isOpen={showTransactionModal}
            onClose={() => { setShowTransactionModal(false); setSelectedTransaction(null) }}
            categories={categories}
            onSubmit={handleSaveTransaction}
            transaction={selectedTransaction}
          />
        )}
        {showDeleteTransactionModal && (
          <DeleteTransactionModal
            isOpen={showDeleteTransactionModal}
            onClose={() => { setShowDeleteTransactionModal(false); setTransactionToDelete(null) }}
            transaction={transactionToDelete}
            onConfirm={(id) => deleteTransactionMutation.mutate(id)}
          />
        )}
        {showCategoryModal && (
          <CategoryEditModal
            isOpen={showCategoryModal}
            onClose={() => { setShowCategoryModal(false); setSelectedCategory(null) }}
            category={selectedCategory}
            onSubmit={handleSaveCategory}
          />
        )}
        {showDeleteModal && (
          <DeleteModal
            isOpen={showDeleteModal}
            onClose={() => { setShowDeleteModal(false); setCategoryToDelete(null) }}
            category={categoryToDelete}
            onConfirm={(id) => deleteCategoryMutation.mutate(id)}
          />
        )}
        {showPlansModal && (
          <RecurringPlansModal
            isOpen={showPlansModal}
            onClose={() => { setShowPlansModal(false); setCategoryForPlans(null) }}
            category={categoryForPlans}
            queryClient={queryClient}
          />
        )}
      </AnimatePresence>
    </div>
  )
}
