"use client"

import {
  formatAmountCents,
  getPortalReceiptDownloadUrl,
  useMyBalanceQuery,
  useMyPaymentsQuery,
} from "@/services/finance"
import { useTranslations } from "next-intl"
import { AlertCircle, CheckCircle, Clock, Receipt } from "lucide-react"

import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function PortalFinancePage() {
  const t = useTranslations("finance")
  const { data: balance } = useMyBalanceQuery()
  const { data: payments } = useMyPaymentsQuery({ page: 0, size: 20 })

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">{t("portal.title")}</h1>

      {/* Balance Cards */}
      <div className="grid gap-4 md:grid-cols-2">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">
              {t("portal.currentBalance")}
            </CardTitle>
            {balance?.status === "CURRENT" ? (
              <CheckCircle className="h-5 w-5 text-green-600" />
            ) : balance?.status === "OVERDUE" ? (
              <AlertCircle className="h-5 w-5 text-red-600" />
            ) : (
              <Clock className="h-5 w-5 text-muted-foreground" />
            )}
          </CardHeader>
          <CardContent>
            <div
              className={`text-2xl font-bold ${
                balance?.outstandingCents === 0
                  ? "text-green-600"
                  : (balance?.outstandingCents ?? 0) > 0
                    ? "text-red-600"
                    : ""
              }`}
            >
              {balance ? formatAmountCents(balance.outstandingCents) : "—"}
            </div>
            <p className="mt-1 text-xs text-muted-foreground">
              {balance?.status === "CURRENT"
                ? t("portal.allPaid")
                : balance?.status === "OVERDUE"
                  ? t("portal.paymentDue")
                  : t("portal.noFeeAssigned")}
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between pb-2">
            <CardTitle className="text-sm font-medium">
              {t("portal.feeSchedule")}
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="text-lg font-medium">
              {balance?.feeScheduleName || t("portal.noFee")}
            </div>
            {balance?.lastPaymentDate && (
              <p className="mt-1 text-xs text-muted-foreground">
                {t("portal.lastPayment")}: {balance.lastPaymentDate}
              </p>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Payment History */}
      <Card>
        <CardHeader>
          <CardTitle>{t("portal.paymentHistory")}</CardTitle>
        </CardHeader>
        <CardContent>
          {payments?.content && payments.content.length > 0 ? (
            <div className="space-y-3">
              {payments.content.map((payment) => (
                <div
                  key={payment.id}
                  className="flex items-center justify-between rounded-lg border p-3"
                >
                  <div className="flex items-center gap-3">
                    <div className="rounded-full bg-green-100 p-1.5 text-green-700 dark:bg-green-900/30 dark:text-green-400">
                      <CheckCircle className="h-4 w-4" />
                    </div>
                    <div>
                      <p className="text-sm font-medium">
                        {formatAmountCents(payment.amountCents)}
                      </p>
                      <p className="text-xs text-muted-foreground">
                        {payment.paymentDate}
                        {payment.periodFrom &&
                          payment.periodTo &&
                          ` • ${payment.periodFrom} – ${payment.periodTo}`}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge variant={payment.voided ? "destructive" : "default"}>
                      {payment.voided ? t("status.voided") : t("status.paid")}
                    </Badge>
                    {!payment.voided && (
                      <a
                        href={getPortalReceiptDownloadUrl(payment.id)}
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                        <Button variant="ghost" size="sm">
                          <Receipt className="h-4 w-4" />
                        </Button>
                      </a>
                    )}
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <p className="text-center text-sm text-muted-foreground">
              {t("portal.noPayments")}
            </p>
          )}
        </CardContent>
      </Card>
    </div>
  )
}
