"use client";

import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { PageHeader } from "@/components/shared/page-header";
import { Card, CardContent } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { LoadingPage } from "@/components/ui/loading";
import { gamificationApi, RewardAwardLog } from "@/lib/api-client";
import { formatDate } from "@/lib/utils";

export default function RewardLogsPage() {
  const [eventKey, setEventKey] = useState("");
  const [userId, setUserId] = useState("");

  const { data, isLoading } = useQuery({
    queryKey: ["reward-logs", eventKey, userId],
    queryFn: async () => {
      const response = await gamificationApi.getRewardLogs({
        eventKey: eventKey || undefined,
        userId: userId || undefined,
        limit: 50,
      });
      return response.data;
    },
  });

  if (isLoading) {
    return <LoadingPage />;
  }

  const logs = data?.data || [];

  return (
    <div className="space-y-6">
      <PageHeader
        title="Reward Logs"
        description="Audit log of automatic rewards issued by rules"
      />

      <Card>
        <CardContent className="pt-6 space-y-4">
          <div className="flex flex-wrap gap-4">
            <Input
              value={eventKey}
              onChange={(e) => setEventKey(e.target.value)}
              placeholder="Filter by event key"
              className="w-56"
            />
            <Input
              value={userId}
              onChange={(e) => setUserId(e.target.value)}
              placeholder="Filter by user ID"
              className="w-72"
            />
          </div>

          {logs.length === 0 ? (
            <p className="text-muted-foreground text-sm">No logs found.</p>
          ) : (
            <div className="space-y-3">
              {logs.map((log: RewardAwardLog) => (
                <div key={log.id} className="border rounded-lg p-3 space-y-1">
                  <div className="flex flex-wrap items-center gap-2 text-sm">
                    <span className="font-medium">{log.eventKey}</span>
                    <span className="text-muted-foreground">{formatDate(log.createdAt)}</span>
                  </div>
                  <p className="text-xs text-muted-foreground">User: {log.userId}</p>
                  {log.ruleId ? (
                    <p className="text-xs text-muted-foreground">Rule: {log.ruleId}</p>
                  ) : null}
                  {log.awardsGiven ? (
                    <pre className="text-xs bg-muted/40 p-2 rounded overflow-x-auto">
                      {JSON.stringify(log.awardsGiven, null, 2)}
                    </pre>
                  ) : null}
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
