"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 LocalePageShell from "@/components/i18n/LocalePageShell";
import useInfiniteScroll from "@/hooks/useInfiniteScroll";
import { useTranslation } from "react-i18next";
import { useAppLanguage } from "@/contexts/LanguageProvider";

export interface IFinancial {
  _id: string;
  type: string;
  project_title?: string;
  project_id?: string;
  createdAt: string;
  amount: number;
  status: string;
}

export default function Financial() {
  const { t } = useTranslation("common");
  const { language } = useAppLanguage();

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

  const allTransactions =
    data?.pages.flatMap((page) => page.financial || []) ?? [];

  const getTransactionType = (type: string) => {
    if (type === "offer") return t("settings.financial.types.offer");
    if (type === "advertising") return t("settings.financial.types.advertising");
    if (type === "shop_order") return t("settings.financial.types.shop_order");
    return type || t("settings.financial.types.other");
  };

  const getStatusText = (status: string) => {
    if (status === "successful") return t("settings.financial.statuses.successful");
    if (status === "failed") return t("settings.financial.statuses.failed");
    return t("settings.financial.statuses.pending");
  };

  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 locale = language === "fa" ? "fa-IR" : "en-US";
      return new Intl.DateTimeFormat(locale, {
        dateStyle: "short",
        timeStyle: "short",
      }).format(date);
    } catch {
      return dateStr;
    }
  };

  const amountLocale = language === "fa" ? "fa-IR" : "en-US";

  return (
    <LocalePageShell>
      <Container>
        <PageTitle>{t("settings.nav.financial")}</PageTitle>

        <div className="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">
                      {t("settings.financial.amountPaid")}:{" "}
                      {Number(item.amount).toLocaleString(amountLocale)}{" "}
                      {t("settings.toman")}
                    </div>

                    <div className="flex items-center gap-2">
                      <span className="text-neutral-600 dark:text-neutral-300">
                        {t("settings.status")}:
                      </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>
    </LocalePageShell>
  );
}
