"use client";

import React from "react";

import Container from "@/components/elements/Container";
import PageTitle from "@/components/settings/PageTitle";
import UserDetails from "@/components/settings/UserDetails";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";

export interface IFinancial {
  _id: string;
  type: string;
  project_title?: string; // اختیاری
  project_id?: string;
  createdAt: string;
  amount: number;
  status: string;
}

export default function Financial() {
 

  const {
    data,
   
    isFetchingNextPage,
   
    containerRef,
  } = useInfiniteScroll({
    endpoint: "/financial",
    queryKey: ["financial"],
    limit: 15,
  });

  // فلت کردن تمام تراکنش‌ها
  const allTransactions = data?.pages.flatMap((page) => page.financial || []) ?? [];


 
  

  // ترجمه نوع تراکنش
  const getTransactionType = (type: string) => {
    switch (type) {
      case "offer":
        return "درخواست همکاری";
      case "advertising":
        return "تبلیغات";
      default:
        return type || "سایر";
    }
  };

  // ترجمه وضعیت
  const getStatusText = (status: string) => {
    switch (status) {
      case "successful":
        return "پرداخت شده";
      case "failed":
        return "پرداخت ناموفق";
      default:
        return "در انتظار پرداخت";
    }
  };

  const getStatusClass = (status: string) => {
    switch (status) {
      case "successful":
        return "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400";
      case "failed":
        return "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400";
      default:
        return "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400";
    }
  };

  const formatDate = (dateStr: string) => {
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return dateStr;
  
      const persianDate = new Intl.DateTimeFormat("fa-IR", {
        dateStyle: "short",
        timeStyle: "short",
      }).format(date);
  
      return persianDate; // خروجی مثلاً: ۱۴۰۴/۱۱/۲۸، ۱۴:۳۳
    } catch {
      return dateStr;
    }
  };

  return (
    <Container>
      <PageTitle>مالی</PageTitle>

      <div className="px-4 text-xs md:text-sm">
        <UserDetails />

        <div className="w-full mt-10 min-h-[50vh]">
    
            <div
              ref={containerRef}
              className="space-y-4 max-h-[65vh] overflow-y-auto  scrollbar-thin scrollbar-thumb-neutral-300 dark:scrollbar-thumb-neutral-600"
            >
              {allTransactions[0]?.docs?.map((item: IFinancial) => (
                <div
                  key={item._id}
                  className="p-5 border rounded-3xl border-neutral-200 dark:border-neutral-700 bg-white dark:bg-neutral-800 shadow-sm hover:shadow-md transition-all duration-200"
                >
                  {/* ردیف اول: عنوان + تاریخ */}
                  <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">
                    <div className="font-medium text-base md:text-lg text-neutral-900 dark:text-white flex items-center gap-2">
                      {getTransactionType(item.type)}
                      {item.project_title && (
                        <span className="text-sm text-neutral-500 dark:text-neutral-400">
                          ({item.project_title})
                        </span>
                      )}
                    </div>
                    <div className="text-sm text-neutral-500 dark:text-neutral-400 whitespace-nowrap">
                      {formatDate(item.createdAt)}
                    </div>
                  </div>

                  {/* ردیف دوم: مبلغ + وضعیت */}
                  <div className="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
                    <div className="font-semibold text-lg text-neutral-900 dark:text-white">
                      مبلغ پرداختی: {Number(item.amount).toLocaleString("fa-IR")} تومان
                    </div>

                    <div className="flex items-center gap-2">
                      <span className="text-neutral-600 dark:text-neutral-300">وضعیت:</span>
                      <span
                        className={`font-medium px-4 py-1.5 rounded-full text-sm ${getStatusClass(
                          item.status
                        )}`}
                      >
                        {getStatusText(item.status)}
                      </span>
                    </div>
                  </div>
                </div>
              ))}

              {isFetchingNextPage && (
                <div className="py-10 flex justify-center">
                  <div className="animate-spin rounded-full h-12 w-12 border-4 border-blue-500 border-t-transparent" />
                </div>
              )}
            </div>
          
        </div>
      </div>
    </Container>
  );
}