'use client';

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';

import { ExpenseDetail } from '@/components/expenses/expense-detail';
import { ExpenseFormDialog } from '@/components/expenses/expense-form-dialog';
import { TrackEntityView } from '@/components/search/track-entity-view';
import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/lib/api/client';
import type { ExpenseRow } from '@/components/expenses/expense-columns';

export default function ExpenseDetailPage() {
  const params = useParams<{ portSlug: string; id: string }>();
  const router = useRouter();
  const [editOpen, setEditOpen] = useState(false);

  const { data } = useQuery<{ data: ExpenseRow }>({
    queryKey: ['expenses', params.id],
    queryFn: () => apiFetch(`/api/v1/expenses/${params.id}`),
    enabled: !!params.id,
  });

  return (
    <div className="max-w-3xl mx-auto">
      <TrackEntityView type="expense" id={params.id} />
      <ExpenseDetail
        expenseId={params.id}
        onEdit={() => setEditOpen(true)}
        onArchived={() => router.push(`/${params.portSlug}/expenses`)}
      />

      {data?.data && (
        <ExpenseFormDialog open={editOpen} onOpenChange={setEditOpen} expense={data.data} />
      )}
    </div>
  );
}
