"use client"

import { useState } from "react"
import {
  formatAmountCents,
  getKassenbuchCsvDownloadUrl,
  useLedgerQuery,
} from "@/services/finance"
import { endOfMonth, format, startOfMonth } from "date-fns"
import { useTranslations } from "next-intl"
import { Download, TrendingDown, TrendingUp } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"

export default function KassenbuchPage() {
  const t = useTranslations("finance")
  const now = new Date()
  const [from, setFrom] = useState(format(startOfMonth(now), "yyyy-MM-dd"))
  const [to, setTo] = useState(format(endOfMonth(now), "yyyy-MM-dd"))
  const [page, setPage] = useState(0)

  const { data: ledger, isLoading } = useLedgerQuery(from, to, {
    page,
    size: 50,
  })

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">{t("kassenbuch")}</h1>
        <a href={getKassenbuchCsvDownloadUrl(from, to)}>
          <Button variant="outline">
            <Download className="mr-2 h-4 w-4" />
            {t("exportCsv")}
          </Button>
        </a>
      </div>

      {/* Date range picker */}
      <Card>
        <CardContent className="flex items-end gap-4 pt-6">
          <div className="space-y-2">
            <Label>{t("from")}</Label>
            <Input
              type="date"
              value={from}
              onChange={(e) => setFrom(e.target.value)}
            />
          </div>
          <div className="space-y-2">
            <Label>{t("to")}</Label>
            <Input
              type="date"
              value={to}
              onChange={(e) => setTo(e.target.value)}
            />
          </div>
        </CardContent>
      </Card>

      {/* Ledger table */}
      <Card>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/50">
                  <th className="p-3 text-left font-medium">{t("date")}</th>
                  <th className="p-3 text-left font-medium">{t("type")}</th>
                  <th className="p-3 text-left font-medium">
                    {t("description")}
                  </th>
                  <th className="p-3 text-right font-medium">{t("income")}</th>
                  <th className="p-3 text-right font-medium">{t("expense")}</th>
                  <th className="p-3 text-right font-medium">{t("balance")}</th>
                </tr>
              </thead>
              <tbody>
                {ledger?.content?.map((entry) => (
                  <tr key={entry.id} className="border-b">
                    <td className="p-3">{entry.transactionDate}</td>
                    <td className="p-3">
                      <span className="flex items-center gap-1">
                        {entry.transactionType === "INCOME" ? (
                          <TrendingUp className="h-3 w-3 text-green-600" />
                        ) : (
                          <TrendingDown className="h-3 w-3 text-red-600" />
                        )}
                        {entry.transactionType === "INCOME"
                          ? t("incomeLabel")
                          : t("expenseLabel")}
                      </span>
                    </td>
                    <td className="p-3">{entry.description}</td>
                    <td className="p-3 text-right text-green-600">
                      {entry.transactionType === "INCOME"
                        ? formatAmountCents(entry.amountCents)
                        : ""}
                    </td>
                    <td className="p-3 text-right text-red-600">
                      {entry.transactionType === "EXPENSE"
                        ? formatAmountCents(entry.amountCents)
                        : ""}
                    </td>
                    <td className="p-3 text-right font-medium">
                      {entry.runningBalanceCents != null
                        ? formatAmountCents(entry.runningBalanceCents)
                        : "—"}
                    </td>
                  </tr>
                ))}
                {(!ledger?.content || ledger.content.length === 0) && (
                  <tr>
                    <td
                      colSpan={6}
                      className="p-6 text-center text-muted-foreground"
                    >
                      {isLoading ? t("loading") : t("noTransactions")}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* Pagination */}
      {ledger && ledger.totalPages > 1 && (
        <div className="flex justify-center gap-2">
          <Button
            variant="outline"
            size="sm"
            disabled={page === 0}
            onClick={() => setPage(page - 1)}
          >
            {t("previous")}
          </Button>
          <span className="flex items-center px-3 text-sm text-muted-foreground">
            {page + 1} / {ledger.totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={page >= ledger.totalPages - 1}
            onClick={() => setPage(page + 1)}
          >
            {t("next")}
          </Button>
        </div>
      )}
    </div>
  )
}
