import { useState, useEffect } from "react"
import { financeApi } from "../../api/finance"

const quickTemplates = [
  { description: "Продукты", categoryName: "Еда", amount: 2000 },
  { description: "Такси", categoryName: "Транспорт", amount: 400 },
  { description: "Кофе", categoryName: "Еда", amount: 350 },
  { description: "Обед", categoryName: "Еда", amount: 600 },
  { description: "Метро", categoryName: "Транспорт", amount: 57 },
]

export default function AddTransactionModal({ onClose, onSaved }) {
  const [type, setType] = useState("expense")
  const [categories, setCategories] = useState([])
  const [categoryId, setCategoryId] = useState(null)
  const [amount, setAmount] = useState("")
  const [description, setDescription] = useState("")
  const [date, setDate] = useState(new Date().toISOString().slice(0, 10))
  const [saving, setSaving] = useState(false)

  useEffect(() => {
    financeApi.listCategories().then(setCategories).catch(console.error)
  }, [])

  const cats = categories.filter((c) => c.type === type)

  const applyTemplate = (t) => {
    setDescription(t.description)
    setAmount(String(t.amount))
    const found = categories.find(
      (c) => c.name === t.categoryName && c.type === "expense"
    )
    if (found) setCategoryId(found.id)
  }

  const handleSubmit = async () => {
    if (!amount || !categoryId) return
    setSaving(true)
    try {
      await financeApi.createTransaction({
        type,
        category_id: categoryId,
        amount: parseFloat(amount),
        description,
        date,
      })
      onSaved()
    } catch (e) {
      console.error(e)
      alert("Ошибка при сохранении")
    } finally {
      setSaving(false)
    }
  }

  return (
    <div
      className="fixed inset-0 bg-black/50 flex items-end justify-center z-50"
      onClick={onClose}
    >
      <div
        className="bg-white dark:bg-gray-900 rounded-t-3xl w-full max-w-lg flex flex-col"
        style={{ maxHeight: "85vh" }}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header - fixed */}
        <div className="px-6 pt-4 pb-2 flex-shrink-0">
          <div className="w-12 h-1 bg-gray-300 dark:bg-gray-700 rounded-full mx-auto mb-4" />
          <h2 className="text-lg font-display font-bold text-gray-900 dark:text-white">
            Новая запись
          </h2>
        </div>

        {/* Scrollable content */}
        <div className="flex-1 overflow-y-auto px-6 pb-4" style={{ WebkitOverflowScrolling: "touch" }}>
          <div className="space-y-5 pt-2">
            {/* Type toggle */}
            <div className="flex bg-gray-100 dark:bg-gray-800 rounded-xl p-1">
              {[
                ["expense", "Расход"],
                ["income", "Доход"],
              ].map(([k, l]) => (
                <button
                  key={k}
                  onClick={() => {
                    setType(k)
                    setCategoryId(null)
                  }}
                  className={`flex-1 py-2.5 rounded-lg text-sm font-semibold transition ${
                    type === k
                      ? k === "expense"
                        ? "bg-red-500 text-white"
                        : "bg-green-500 text-white"
                      : "text-gray-500"
                  }`}
                >
                  {l}
                </button>
              ))}
            </div>

            {/* Quick templates */}
            {type === "expense" && (
              <div>
                <p className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase mb-2">
                  Быстрые шаблоны
                </p>
                <div className="flex flex-wrap gap-2">
                  {quickTemplates.map((t, i) => (
                    <button
                      key={i}
                      onClick={() => applyTemplate(t)}
                      className="px-3 py-1.5 rounded-lg bg-gray-100 dark:bg-gray-800 text-sm text-gray-700 dark:text-gray-300 hover:bg-primary-100 dark:hover:bg-primary-900 transition"
                    >
                      {t.description}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* Amount */}
            <div>
              <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase block mb-1">
                Сумма
              </label>
              <div className="relative">
                <input
                  type="number"
                  inputMode="decimal"
                  value={amount}
                  onChange={(e) => setAmount(e.target.value)}
                  className="w-full px-4 py-3 rounded-xl bg-gray-100 dark:bg-gray-800 text-2xl font-bold text-gray-900 dark:text-white outline-none"
                  placeholder="0"
                />
                <span className="absolute right-4 top-1/2 -translate-y-1/2 text-lg text-gray-400">
                  ₽
                </span>
              </div>
            </div>

            {/* Description */}
            <div>
              <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase block mb-1">
                Описание
              </label>
              <input
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                className="w-full px-4 py-3 rounded-xl bg-gray-100 dark:bg-gray-800 text-sm text-gray-900 dark:text-white outline-none"
                placeholder="Что купили?"
              />
            </div>

            {/* Category */}
            <div>
              <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase block mb-1">
                Категория
              </label>
              <div className="grid grid-cols-2 gap-2">
                {cats.map((c) => (
                  <button
                    key={c.id}
                    onClick={() => setCategoryId(c.id)}
                    className={`px-3 py-2.5 rounded-xl text-sm text-left font-medium transition ${
                      categoryId === c.id
                        ? "bg-primary-500 text-white ring-2 ring-primary-300"
                        : "bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300"
                    }`}
                  >
                    {c.emoji} {c.name}
                  </button>
                ))}
              </div>
            </div>

            {/* Date */}
            <div>
              <label className="text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase block mb-1">
                Дата
              </label>
              <input
                type="date"
                value={date}
                onChange={(e) => setDate(e.target.value)}
                className="w-full px-4 py-3 rounded-xl bg-gray-100 dark:bg-gray-800 text-sm text-gray-900 dark:text-white outline-none"
              />
            </div>
          </div>
        </div>

        {/* Sticky submit button */}
        <div className="px-6 py-4 border-t border-gray-100 dark:border-gray-800 flex-shrink-0 bg-white dark:bg-gray-900">
          <button
            onClick={handleSubmit}
            disabled={saving || !amount || !categoryId}
            className="w-full py-3.5 bg-primary-500 hover:bg-primary-600 disabled:opacity-50 text-white rounded-xl font-semibold text-base transition shadow-lg"
          >
            {saving
              ? "Сохраняю..."
              : `Добавить ${type === "expense" ? "расход" : "доход"}`}
          </button>
        </div>
      </div>
    </div>
  )
}
