"use client";

import { useEffect, useState } from "react";
import List from "./List";
import Head from "./Head";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import { safeJsonParse } from "@/lib/sanitize";

function Transactions({ user, loading }) {
  const [payments, setPayments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [status, setStatus] = useState(undefined); // undefined = all, 'pending', 'success', 'failed'

  useEffect(() => {
    const fetchPayments = async () => {
      setIsLoading(true);
      try {
        const userInfo = Cookies.get("userInfo");
        if (!userInfo) {
          setIsLoading(false);
          return;
        }

        const parsedData = safeJsonParse(userInfo);
        if (!parsedData) { setIsLoading(false); return; }

        const params = {
          page,
          limit: 10,
        };

        if (status) {
          params.status = status;
        }

        const response = await request.getMyPayments(params);

        if (Array.isArray(response?.data)) {
          setPayments(response.data);
          setTotalPages(response?.meta?.totalPages || 1);
        } else {
          setPayments([]);
          setTotalPages(1);
        }
      } catch (error) {
        console.error("Error fetching payments:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchPayments();
  }, [page, status]);

  const handlePageChange = (event, value) => {
    setPage(value);
  };

  const handleStatusChange = (newStatus) => {
    setStatus(newStatus);
    setPage(1); // Reset to first page when status changes
  };

  return (
    <div className="opacity-page">
      <p className="text-[#3B3B3B] hidden md:block text-[16px] font-bold">
        تاریخچه تراکنش ها
      </p>
      <Head status={status} setStatus={handleStatusChange} />
      <List
        payments={payments}
        loading={isLoading}
        page={page}
        totalPages={totalPages}
        onPageChange={handlePageChange}
      />
    </div>
  );
}

export default Transactions;
