"use client"
import { IconTrendingUp } from "@tabler/icons-react"

import {
  Card,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { useTranslation } from "react-i18next"
import { useEffect, useState } from "react"
import useAxios from "@/hooks/useAxios"
import toast from "react-hot-toast"

export function SectionCards() {
  const { t } = useTranslation("common");
  const [totalCourses, setTotalCourses] = useState(0);  
  const [totalSell, setTotalSell] = useState(0);  
  const [totalSettledSell, setTotalSettledSell] = useState(0);  
  const [totalSettled, setTotalSettled] = useState(0);  
  const [totalPrice, setTotalPrice] = useState(0);  
  const [isLoading, setIsLoading] = useState(false);
  const { request } = useAxios();

  const fetchCourses = async () => {
    setIsLoading(true);
    try {
      const response = await request(
        "GET",
        `/academy/academy/get/course`
      );

      if (response?.data?.courses) {
        setTotalCourses(response.data.pagination?.totalItems || 0);
      } else if (response?.courses) {
        setTotalCourses(response.pagination?.totalItems || 0);
      } else {
        toast.error(t("academyDashboard.fetchStructureError"));
      }
    } catch (err) {
      console.log("get error:", err);
      toast.error(t("academyDashboard.fetchError"));
    } finally {
      setIsLoading(false);
    }
  };

  const fetchCoursesPayment = async () => {
    setIsLoading(true);
    try {
      const response = await request(
        "GET",
        `/academy/course/getAllAcademyPayments?status=success`
      );

      setTotalPrice(response.data.stats.totalAmount)
      setTotalSell(response.data.payments.length)
    } catch (err) {
      console.log("get error:", err);
      toast.error(t("academyDashboard.fetchError"));
    } finally {
      setIsLoading(false);
    }
  };

  const fetchCoursesPayment2 = async () => {
    setIsLoading(true);
    try {
      const response = await request(
        "GET",
        `/academy/course/getAllAcademyPayments?status=settled`
      );

      setTotalSettled(response.data.stats.totalAmount)
      setTotalSettledSell(response.data.payments.length)
    } catch (err) {
      console.log("get error:", err);
      toast.error(t("academyDashboard.fetchError"));
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchCourses();
    fetchCoursesPayment();
    fetchCoursesPayment2();
  }, []);

  return (
    <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card grid grid-cols-1 gap-4 px-4 *:data-[slot=card]:bg-gradient-to-t *:data-[slot=card]:shadow-xs lg:px-6 @xl/main:grid-cols-2 @5xl/main:grid-cols-4">
      <Card className="@container/card">
        <CardHeader>
          <CardDescription>{t("academyDashboard.totalSales")}</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
            {(totalPrice + totalSettled).toLocaleString('fa-IR', {
              minimumFractionDigits: 0,
              maximumFractionDigits: 2
            })} {t("settings.toman")}
          </CardTitle>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            {t("academyDashboard.earnIncome")} <IconTrendingUp className="size-4" />
          </div>
          <div className="text-muted-foreground">
            {t("academyDashboard.totalSalesHint")}
          </div>
        </CardFooter>
      </Card>
      <Card className="@container/card">
        <CardHeader>
          <CardDescription>{t("academyDashboard.packageCount")}</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
            {totalCourses}
          </CardTitle>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            {t("academyDashboard.growPackages")}
          </div>
          <div className="text-muted-foreground">
            {t("academyDashboard.morePackagesHint")}
          </div>
        </CardFooter>
      </Card>
      <Card className="@container/card">
        <CardHeader>
          <CardDescription>{t("academyDashboard.packagesSold")}</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
            {totalSell + totalSettledSell}
          </CardTitle>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            {t("academyDashboard.packagesSoldHint")} <IconTrendingUp className="size-4" />
          </div>
          <div className="text-muted-foreground">{t("academyDashboard.sellMoreHint")}</div>
        </CardFooter>
      </Card>
      <Card className="@container/card">
        <CardHeader>
          <CardDescription>{t("academyDashboard.unsettledAmount")}</CardDescription>
          <CardTitle className="text-2xl font-semibold tabular-nums @[250px]/card:text-3xl">
            {(totalPrice).toLocaleString('fa-IR', {
              minimumFractionDigits: 0,
              maximumFractionDigits: 2
            })} {t("settings.toman")}
          </CardTitle>
        </CardHeader>
        <CardFooter className="flex-col items-start gap-1.5 text-sm">
          <div className="line-clamp-1 flex gap-2 font-medium">
            {t("academyDashboard.debtHint")} <IconTrendingUp className="size-4" />
          </div>
          <div className="text-muted-foreground">{t("academyDashboard.settlementHint")}</div>
        </CardFooter>
      </Card>
    </div>
  )
}
