"use client";

import { useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { Table, Tag, Button, Card } from "antd";
import type { ColumnsType } from "antd/es/table";
import { ArrowRight2, EmptyWallet } from "iconsax-react";

import { API_ROUTES, request } from "@/services/api";
import { Container } from "@/components/container";
import type { Transaction } from "@/types/transaction";

export default function UserHistoryPage() {
  const router = useRouter();
  const params = useParams();
  const userId = params.id as string;

  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);

  const fetchData = async () => {
    const res = await request.get(API_ROUTES.USER.HISTORY(userId), {
      page,
      limit: 10,
    });

    setTotal(res.data.total_count || 0);
    return res.data.transactions as Transaction[];
  };

  const { data, isLoading } = useQuery({
    queryKey: ["user-history", userId, page],
    queryFn: fetchData,
  });

  const columns: ColumnsType<Transaction> = [
    {
      title: "تاریخ",
      dataIndex: "created_at",
      key: "created_at",
      render: (date: string) => (
        <span dir="ltr">
          {new Date(date).toLocaleDateString("fa-IR", {
            year: "numeric",
            month: "2-digit",
            day: "2-digit",
            hour: "2-digit",
            minute: "2-digit",
          })}
        </span>
      ),
    },
    {
      title: "نوع",
      dataIndex: "type",
      key: "type",
      render: (type: string) => {
        let color: "default" | "green" | "blue" | "gold" = "default";
        let text = type;

        switch (type) {
          case "gift":
            color = "green";
            text = "هدیه";
            break;
          case "credit":
            color = "blue";
            text = "اعتبار";
            break;
          case "free":
            color = "gold";
            text = "رایگان";
            break;
        }

        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: "مقدار",
      dataIndex: "amount",
      key: "amount",
      render: (amount: number) => (
        <span className="font-bold text-lg">
          {amount.toLocaleString()}{" "}
          <span className="text-xs font-normal text-gray-500">امتیاز</span>
        </span>
      ),
    },
    {
      title: "توضیحات",
      dataIndex: "description",
      key: "description",
      ellipsis: true,
    },
  ];

  return (
    <Container>
      <div className="flex flex-col gap-6 py-8">
        {/* Header */}
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Button
              type="text"
              icon={<ArrowRight2 size={20} />}
              onClick={() => router.back()}
            />
            <h1 className="text-xl font-bold flex items-center gap-2">
              <EmptyWallet size={24} className="text-blue-600" />
              تاریخچه تراکنش‌های کاربر
            </h1>
          </div>
        </div>

        {/* Table */}
        <Card className="shadow-sm">
          <Table
            columns={columns}
            dataSource={data}
            rowKey="id"
            loading={isLoading}
            pagination={{
              current: page,
              pageSize: 10,
              total,
              onChange: setPage,
              position: ["bottomCenter"],
              showSizeChanger: false,
            }}
            locale={{
              emptyText: "هیچ تراکنشی یافت نشد",
            }}
          />
        </Card>
      </div>
    </Container>
  );
}
