import { Routes, Route, useNavigate, useParams, Navigate } from 'react-router-dom';
import { Home } from './pages/Home';
import { Ozet } from './pages/Ozet';
import { ExpenseSheet } from './components/ExpenseSheet';
import { useQuery } from '@tanstack/react-query';
import { api, type Expense } from './lib/api';
import { translations, getLang } from './lib/i18n';
import { useBackButton } from './hooks/useTelegramUI';

/** /edit/:id rotası — bot "Düzenle" butonundan gelen derin bağlantı */
function EditRoute() {
  const { id } = useParams();
  const navigate = useNavigate();
  const lang = getLang();
  const t = translations[lang];

  const { data: me } = useQuery({ queryKey: ['me'], queryFn: api.me });
  const { data: expense } = useQuery({
    queryKey: ['expense', Number(id)],
    queryFn: () => api.getExpense(Number(id)),
    enabled: !!id && !!me,
    retry: false,
  });

  useBackButton(() => navigate('/'));

  if (!me || !expense) {
    return (
      <div className="app px-4 pt-10 text-center text-sm text-[var(--tg-hint)]">
        {t.loading}
      </div>
    );
  }

  return (
    <>
      <div className="app px-4 pt-3 text-center text-sm font-semibold">{t.editExpense}</div>
      <ExpenseSheet
        categories={me.categories}
        initial={expense}
        onSave={async (data) => {
          await api.updateExpense(expense.id, data);
          navigate('/');
        }}
        onDelete={async (e: Expense) => {
          await api.deleteExpense(e.id);
          navigate('/');
        }}
        onClose={() => navigate('/')}
      />
    </>
  );
}

export function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="/ozet" element={<Ozet />} />
      <Route path="/edit/:id" element={<EditRoute />} />
      <Route path="*" element={<Navigate to="/" replace />} />
    </Routes>
  );
}
