"use client"

import { useState } from "react"
import {
  formatAmountCents,
  getReceiptDownloadUrl,
  usePaymentsQuery,
  useVoidPaymentMutation,
} from "@/services/finance"
import { useTranslations } from "next-intl"
import { Ban, Receipt } from "lucide-react"

import type { PaymentStatus } from "@/services/finance"

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

export default function PaymentsPage() {
  const t = useTranslations("finance")
  const [statusFilter, setStatusFilter] = useState<string>("ALL")
  const [page, setPage] = useState(0)

  const { data: payments, isLoading } = usePaymentsQuery({
    status:
      statusFilter === "ALL" ? undefined : (statusFilter as PaymentStatus),
    page,
    size: 20,
  })

  const voidMutation = useVoidPaymentMutation()

  const handleVoid = (id: string) => {
    const reason = prompt(t("voidReason"))
    if (reason) {
      voidMutation.mutate({ id, reason })
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">{t("payments")}</h1>
        <Select
          value={statusFilter}
          onChange={(e) => setStatusFilter(e.target.value)}
          className="w-[180px]"
        >
          <option value="ALL">{t("allStatuses")}</option>
          <option value="PAID">{t("status.paid")}</option>
          <option value="PENDING">{t("status.pending")}</option>
          <option value="OVERDUE">{t("status.overdue")}</option>
          <option value="VOIDED">{t("status.voided")}</option>
        </Select>
      </div>

      <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("member")}</th>
                  <th className="p-3 text-left font-medium">{t("amount")}</th>
                  <th className="p-3 text-left font-medium">{t("period")}</th>
                  <th className="p-3 text-left font-medium">
                    {t("paymentMethod")}
                  </th>
                  <th className="p-3 text-left font-medium">{t("date")}</th>
                  <th className="p-3 text-left font-medium">
                    {t("status.label")}
                  </th>
                  <th className="p-3 text-left font-medium">{t("actions")}</th>
                </tr>
              </thead>
              <tbody>
                {payments?.content?.map((payment) => (
                  <tr key={payment.id} className="border-b">
                    <td className="p-3">
                      {payment.memberName || payment.memberId.substring(0, 8)}
                    </td>
                    <td className="p-3 font-medium">
                      {formatAmountCents(payment.amountCents)}
                    </td>
                    <td className="p-3 text-muted-foreground">
                      {payment.periodFrom && payment.periodTo
                        ? `${payment.periodFrom} – ${payment.periodTo}`
                        : "—"}
                    </td>
                    <td className="p-3">
                      {t(`method.${payment.paymentMethod}`)}
                    </td>
                    <td className="p-3">{payment.paymentDate}</td>
                    <td className="p-3">
                      <Badge
                        variant={payment.voided ? "destructive" : "default"}
                      >
                        {payment.voided ? t("status.voided") : t("status.paid")}
                      </Badge>
                    </td>
                    <td className="p-3">
                      <div className="flex gap-1">
                        {!payment.voided && (
                          <>
                            <a
                              href={getReceiptDownloadUrl(payment.id)}
                              target="_blank"
                              rel="noopener noreferrer"
                            >
                              <Button variant="ghost" size="sm">
                                <Receipt className="h-4 w-4" />
                              </Button>
                            </a>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleVoid(payment.id)}
                            >
                              <Ban className="h-4 w-4 text-red-500" />
                            </Button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {(!payments?.content || payments.content.length === 0) && (
                  <tr>
                    <td
                      colSpan={7}
                      className="p-6 text-center text-muted-foreground"
                    >
                      {isLoading ? t("loading") : t("noPayments")}
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {payments && payments.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} / {payments.totalPages}
          </span>
          <Button
            variant="outline"
            size="sm"
            disabled={page >= payments.totalPages - 1}
            onClick={() => setPage(page + 1)}
          >
            {t("next")}
          </Button>
        </div>
      )}
    </div>
  )
}
