'use client'

import Link from 'next/link'
import { useQuery } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { api, type FinanceDashboard } from '@/lib/api'
import { Card } from '@/components/ui/Card'
import { Button } from '@/components/ui/Button'

export function FinanceDashboardPage() {
  const { t } = useTranslation()
  const { data, isLoading } = useQuery({
    queryKey: ['finance-dashboard'],
    queryFn: () => api.get<{ data: FinanceDashboard }>('/finance/dashboard'),
  })

  const dash = data?.data?.data

  if (isLoading || !dash) {
    return <div className="p-6 text-sm text-[var(--text-muted)]">{t('common.loading')}</div>
  }

  return (
    <div className="space-y-5">
      <div className="animate-fade-in-up flex flex-wrap items-center justify-between gap-3">
        <h1 className="premium-heading text-2xl font-bold">{t('finance.dashboard')}</h1>
        <div className="flex gap-2">
          <Link href="/finance/invoices">
            <Button size="sm" variant="secondary">
              {t('finance.invoices')}
            </Button>
          </Link>
          <Link href="/finance/purchases">
            <Button size="sm" variant="secondary">
              {t('finance.purchases')}
            </Button>
          </Link>
        </div>
      </div>

      <div className="grid gap-4 sm:grid-cols-2">
        <Card elevated className="animate-fade-in-up">
          <div className="text-xs uppercase tracking-wide text-[var(--text-muted)]">
            {t('finance.outstandingAr')}
          </div>
          <div className="mt-2 text-3xl font-bold text-brand-700">
            {Number(dash.outstanding_ar).toFixed(2)} €
          </div>
          <div className="mt-1 text-sm text-[var(--text-muted)]">
            {dash.counts.sales_open} {t('finance.openSales')}
          </div>
        </Card>
        <Card elevated className="animate-fade-in-up stagger-1">
          <div className="text-xs uppercase tracking-wide text-[var(--text-muted)]">
            {t('finance.outstandingAp')}
          </div>
          <div className="mt-2 text-3xl font-bold text-amber-700">
            {Number(dash.outstanding_ap).toFixed(2)} €
          </div>
          <div className="mt-1 text-sm text-[var(--text-muted)]">
            {dash.counts.purchase_open} {t('finance.openPurchases')}
          </div>
        </Card>
      </div>
    </div>
  )
}
