import { useEffect, useState } from "react";

import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { apiGet } from "@/lib/api";
import { useAuthStore } from "@/store/authStore";
import type { Payment } from "@/lib/types";
import { formatDateTime, formatMoney } from "@/lib/format";

export function PaymentsPage() {
  const selectedPropertyId = useAuthStore((s) => s.selectedPropertyId);
  const [rows, setRows] = useState<Payment[]>([]);

  useEffect(() => {
    apiGet<{ data: Payment[] }>("/payments").then((r) => setRows(r.data));
  }, [selectedPropertyId]);

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">Payments</h1>
      <Card className="rounded-2xl">
        <CardHeader>
          <CardTitle className="text-base">Payment records</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Booking</TableHead>
                <TableHead>Status</TableHead>
                <TableHead>When</TableHead>
                <TableHead className="text-right">Amount</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {rows.map((p) => (
                <TableRow key={p.id}>
                  <TableCell className="text-sm">{p.bookingId}</TableCell>
                  <TableCell>
                    <Badge>{p.status}</Badge>
                  </TableCell>
                  <TableCell className="text-xs text-muted-foreground">
                    {formatDateTime(p.createdAt)}
                  </TableCell>
                  <TableCell className="text-right font-medium">
                    {formatMoney(p.amount)} {p.last4 && `· ${p.last4}`}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
