import { useEffect, useMemo, useState } from "react";
import { useNavigate } from "react-router-dom";
import { createExpense, deleteExpense, listExpenses } from "./expensesApi";
import type { Expense } from "./expensesApi";
import { clearToken } from "../../lib/auth";

function formatMoneyCents(amountCents: number, currency: string) {
  const amount = amountCents / 100;
  return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(amount);
}

export function ExpensesPage() {
  const navigate = useNavigate();
  const [items, setItems] = useState<Expense[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  const [title, setTitle] = useState("");
  const [amount, setAmount] = useState("12.50");
  const [currency, setCurrency] = useState("CHF");
  const [category, setCategory] = useState("Food");
  const [expenseDate, setExpenseDate] = useState(() => new Date().toISOString().slice(0, 10));
  const [note, setNote] = useState("");

  const totalCents = useMemo(() => items.reduce((s, e) => s + e.amountCents, 0), [items]);

  async function refresh() {
    setError("");
    setLoading(true);
    try {
      const page = await listExpenses({ page: 0, size: 50 });
      setItems(page.content ?? []);
    } catch (e: any) {
      if (e.message === "Unauthorized") {
        navigate("/login");
        return;
      }
      setError(e.message ?? "Failed to load expenses");
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    refresh();
  }, []);

  async function onAdd(e: React.FormEvent) {
    e.preventDefault();
    setError("");

    const normalizedTitle = title.trim();
    if (!normalizedTitle) {
      setError("Please enter a title.");
      return;
    }

    const normalized = amount.replace(",", ".").trim();
    const parsed = Number(normalized);

    if (!Number.isFinite(parsed) || parsed <= 0) {
      setError("Please enter a valid amount > 0.");
      return;
    }

    const amountCents = Math.round(parsed * 100);

    try {
      await createExpense({
        title: normalizedTitle,
        amountCents,
        currency,
        category,
        expenseDate,
        note: note.trim() ? note.trim() : null,
      });
      setTitle("");
      setNote("");
      await refresh();
    } catch (e: any) {
      if (e.message === "Unauthorized") {
        navigate("/login");
        return;
      }
      setError(e.message ?? "Failed to create expense");
    }
  }

  async function onDelete(id: number) {
    setError("");
    try {
      await deleteExpense(id);
      setItems((prev) => prev.filter((x) => x.id !== id));
    } catch (e: any) {
      if (e.message === "Unauthorized") {
        navigate("/login");
        return;
      }
      setError(e.message ?? "Failed to delete expense");
    }
  }

  function onLogout() {
    clearToken();
    navigate("/login", { replace: true });
  }

  return (
    <div className="relative min-h-screen overflow-hidden bg-[radial-gradient(circle_at_top_right,#fce7f3_0%,#fbcfe8_28%,#ddd6fe_58%,#bfdbfe_100%)] px-4 py-8 text-rose-950 sm:px-6">
      <div className="pointer-events-none absolute -left-24 top-12 h-72 w-72 rounded-full bg-pink-300/40 blur-3xl" />
      <div className="pointer-events-none absolute -right-24 bottom-8 h-80 w-80 rounded-full bg-violet-300/35 blur-3xl" />

      <div className="relative mx-auto w-full max-w-5xl rounded-3xl border border-rose-200/70 bg-white/50 p-6 shadow-[0_24px_80px_-28px_rgba(219,39,119,0.55)] backdrop-blur-xl sm:p-8">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h1 className="text-3xl font-black tracking-tight text-rose-700">Expenses</h1>
            <p className="mt-1 text-sm text-rose-700/80">Track your spend with sparkle and clarity.</p>
          </div>
          <button
            type="button"
            onClick={onLogout}
            className="rounded-xl border border-rose-200 bg-rose-100 px-4 py-2 font-semibold text-rose-700 transition hover:bg-rose-200"
          >
            Logout
          </button>
        </div>

        {error && (
          <div className="mt-4 rounded-xl border border-rose-300 bg-rose-100 p-3 text-sm text-rose-700">
            {error}
          </div>
        )}

        <form onSubmit={onAdd} className="mt-6 grid gap-3 rounded-2xl border border-rose-200 bg-rose-50/70 p-4 sm:p-5">
          <input
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Title"
            className="w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-pink-300 focus:ring-2 focus:ring-pink-200"
          />

          <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
            <input
              value={amount}
              onChange={(e) => setAmount(e.target.value)}
              placeholder="Amount"
              className="w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-fuchsia-300 focus:ring-2 focus:ring-fuchsia-200"
            />
            <input
              value={currency}
              onChange={(e) => setCurrency(e.target.value.toUpperCase())}
              placeholder="CHF"
              className="w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-fuchsia-300 focus:ring-2 focus:ring-fuchsia-200"
            />
            <input
              value={category}
              onChange={(e) => setCategory(e.target.value)}
              placeholder="Category"
              className="w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-violet-300 focus:ring-2 focus:ring-violet-200"
            />
            <input
              type="date"
              value={expenseDate}
              onChange={(e) => setExpenseDate(e.target.value)}
              className="w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 outline-none transition focus:border-violet-300 focus:ring-2 focus:ring-violet-200"
            />
          </div>

          <input
            value={note}
            onChange={(e) => setNote(e.target.value)}
            placeholder="Note (optional)"
            className="w-full rounded-xl border border-rose-200 bg-white/80 px-3 py-2 text-rose-900 placeholder:text-rose-400 outline-none transition focus:border-pink-300 focus:ring-2 focus:ring-pink-200"
          />

          <button
            type="submit"
            className="w-full rounded-xl bg-linear-to-r from-rose-300 via-pink-300 to-violet-300 px-4 py-2 font-bold text-rose-900 shadow-lg shadow-rose-300/70 transition hover:scale-[1.01] hover:brightness-105 sm:w-auto"
          >
            Add expense
          </button>
        </form>

        <div className="mt-6 rounded-2xl border border-rose-200 bg-white/60 p-4">
          <div className="text-sm font-semibold text-rose-700/80">Total</div>
          <div className="mt-1 text-2xl font-black text-rose-700">
            {formatMoneyCents(totalCents, currency)}
          </div>
        </div>

        <div className="mt-6 rounded-2xl border border-rose-200 bg-white/60 p-4">
          {loading ? (
            <div className="text-rose-700/80">Loading...</div>
          ) : items.length === 0 ? (
            <div className="text-rose-700/80">No expenses yet.</div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full min-w-[700px] border-collapse text-sm">
                <thead>
                  <tr className="text-left text-rose-700/80">
                    <th className="pb-2 font-semibold">Date</th>
                    <th className="pb-2 font-semibold">Title</th>
                    <th className="pb-2 font-semibold">Category</th>
                    <th className="pb-2 font-semibold">Note</th>
                    <th className="pb-2 text-right font-semibold">Amount</th>
                    <th className="pb-2 text-right font-semibold">Action</th>
                  </tr>
                </thead>
                <tbody>
                  {items.map((e) => (
                    <tr key={e.id} className="border-t border-rose-100">
                      <td className="py-2 pr-3 text-rose-900">{e.expenseDate}</td>
                      <td className="py-2 pr-3 text-rose-900">{e.title}</td>
                      <td className="py-2 pr-3 text-rose-900">{e.category}</td>
                      <td className="py-2 pr-3 text-rose-900/80">{e.note ?? ""}</td>
                      <td className="py-2 text-right font-semibold text-rose-900">
                        {formatMoneyCents(e.amountCents, e.currency)}
                      </td>
                      <td className="py-2 text-right">
                        <button
                          type="button"
                          onClick={() => onDelete(e.id)}
                          className="rounded-lg border border-rose-200 bg-rose-100 px-3 py-1.5 text-xs font-semibold text-rose-700 transition hover:bg-rose-200"
                        >
                          Delete
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
