"use client";

import React, { useState, useEffect } from "react";
import { ThemeProvider, useTheme } from "next-themes";

import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";

import { motion } from "framer-motion";

import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import useAxios from "@/hooks/useAxios";

interface Payment {
  _id: string;
  price: number;
  course_name: string;
  course_id: any;
  academy_id: string;
  status: string;
  createdAt: string;
  updatedAt: string;
  payment_authority: string;
  payment_ref_id: string;
  discountAmount: number;
  taxAmount: number;
  taxRate: number;
  user_id: {
    _id: string;
    user_name: string;
    profile_image: string;
  };
}

interface Transaction {
  id: string;
  type: "deposit" | "withdraw" | "expense";
  currency: string;
  amount: number;
  date: string;
  description: string;
  status: string;
  refId: string;
}

const WalletDashboard = () => {
  const [transactions, setTransactions] = useState<Transaction[]>([]);
  const [filterType, setFilterType] = useState<"all" | "deposit" | "withdraw" | "expense">("all");
  const [totalBalance, setTotalBalance] = useState(0);
  const [totalSettled, setTotalSettled] = useState(0);
  const [totalPending, setTotalPending] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  
  const { request } = useAxios();
  const { t } = useTranslation("common");

  // دریافت پرداخت‌های موفق (فروش‌های انجام شده)
  const fetchSuccessfulPayments = async () => {
    try {
      const response = await request(
        "GET",
        `/academy/course/getAllAcademyPayments?status=success`
      );
      
      console.log("پرداخت‌های موفق:", response?.data?.payments);
      
      if (response?.data?.payments && Array.isArray(response.data.payments)) {
        const payments: Payment[] = response.data.payments;
        
        // محاسبه مجموع فروش
        const total = payments.reduce((sum, p) => sum + p.taxAmount, 0);
        setTotalPending(total);
        
        // تبدیل به تراکنش‌های فروش ( expense type )
        const salesTransactions: Transaction[] = payments.map((payment) => ({
          id: payment._id,
          type: "expense",
          currency: "تومان",
          amount: payment.taxAmount,
          date: new Date(payment.createdAt).toLocaleDateString("fa-IR"),
          description: payment.course_name,
          status: "pending",
          refId: payment.payment_ref_id,
        }));
        
        return salesTransactions;
      }
      return [];
    } catch (err) {
      console.log("error fetching successful payments:", err);
      toast.error("خطا در دریافت فروش‌ها");
      return [];
    }
  };

  // دریافت پرداخت‌های تسویه شده
  const fetchSettledPayments = async () => {
    try {
      const response = await request(
        "GET",
        `/academy/course/getAllAcademyPayments?status=settled`
      );
      
      console.log("پرداخت‌های تسویه شده:", response?.data?.payments);
      
      if (response?.data?.payments && Array.isArray(response.data.payments)) {
        const payments: Payment[] = response.data.payments;
        
        // محاسبه مجموع تسویه شده
        const total = payments.reduce((sum, p) => sum + p.taxAmount, 0);
        setTotalSettled(total);
        
        // تبدیل به تراکنش‌های پرداخت شده ( withdraw type )
        const settledTransactions: Transaction[] = payments.map((payment) => ({
          id: payment._id,
          type: "withdraw",
          currency: "تومان",
          amount: payment.taxAmount,
          date: new Date(payment.updatedAt).toLocaleDateString("fa-IR"),
          description: `تسویه حساب - ${payment.course_name}`,
          status: "settled",
          refId: payment.payment_ref_id,
        }));
        
        return settledTransactions;
      }
      return [];
    } catch (err) {
      console.log("error fetching settled payments:", err);
      toast.error("خطا در دریافت تسویه‌ها");
      return [];
    }
  };

  // محاسبه موجودی کل (فروش - تسویه شده)
  const calculateBalance = (sales: number, settled: number) => {
    return sales - settled;
  };

  // بارگذاری تمام داده‌ها
  const fetchAllData = async () => {
    setIsLoading(true);
    try {
      const [salesTransactions, settledTransactions] = await Promise.all([
        fetchSuccessfulPayments(),
        fetchSettledPayments(),
      ]);
      
      // ترکیب تراکنش‌ها
      const allTransactions = [...salesTransactions, ...settledTransactions];
      
      // مرتب‌سازی بر اساس تاریخ (جدیدترین اول)
      allTransactions.sort((a, b) => {
        const dateA = new Date(a.date.split("/").reverse().join("/"));
        const dateB = new Date(b.date.split("/").reverse().join("/"));
        return dateB.getTime() - dateA.getTime();
      });
      
      setTransactions(allTransactions);
      
      // محاسبه موجودی
      const balance = calculateBalance(totalPending, totalSettled);
      setTotalBalance(balance);
      
    } catch (err) {
      console.log("error fetching all data:", err);
      toast.error("خطا در دریافت اطلاعات");
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchAllData();
  }, []);

  // فیلتر تراکنش‌ها
  const filteredTransactions = transactions.filter(
    (t) => filterType === "all" || t.type === filterType
  );

  // آمار کلی
  const stats = {
    sales: transactions.filter(t => t.type === "expense").reduce((sum, t) => sum + t.amount, 0),
    settled: transactions.filter(t => t.type === "withdraw").reduce((sum, t) => sum + t.amount, 0),
    pending: transactions.filter(t => t.type === "expense" && t.status === "pending").reduce((sum, t) => sum + t.amount, 0),
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex justify-center items-center">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-pink-500"></div>
      </div>
    );
  }

  return (
    <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
      <div  className="min-h-screen  text-foreground">
        <div className="container mx-auto p-6 space-y-8">
          {/* کارت‌های آمار - 3 کارت */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        

            {/* کل فروش */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.1 }}
            >
              <Card className="text-white">
                <CardHeader>
                  <CardTitle className="text-lg">کل فروش</CardTitle>
                  <CardDescription className="dark:text-green-100 text-green-500">
                    مجموع فروش‌های موفق
                  </CardDescription>
                </CardHeader>
                <CardContent >
                  <div className="text-3xl font-bold dark:text-white text-neutral-700">
                    {(stats.sales + stats.settled).toLocaleString()} تومان
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* تسویه شده */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.2 }}
            >
              <Card className="text-white">
                <CardHeader>
                  <CardTitle className="text-lg">تسویه شده</CardTitle>
                  <CardDescription className="dark:text-purple-100 text-purple-500">
                    مبالغ پرداخت شده به حساب
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="text-3xl font-bold dark:text-white text-neutral-700">
                    {stats.settled.toLocaleString()} تومان
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* جداول تراکنش‌ها */}
          <Card>
            <CardHeader className="flex flex-row items-center justify-between flex-wrap gap-4">
              <CardTitle>گزارش تراکنش‌ها</CardTitle>
              <div className="flex gap-2">
                <Select
                  value={filterType}
                  onValueChange={(value) =>
                    setFilterType(value as "all" | "deposit" | "withdraw" | "expense")
                  }
                >
                  <SelectTrigger className="w-[180px]">
                    <SelectValue placeholder="فیلتر بر اساس نوع" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">همه</SelectItem>
                    <SelectItem value="expense">فروش</SelectItem>
                    <SelectItem value="withdraw">پرداخت شده</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </CardHeader>
            <CardContent>
              {filteredTransactions.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground">
                  هیچ تراکنشی یافت نشد
                </div>
              ) : (
                <div className="w-full">
                {/* نمای دسکتاپ - جدول */}
                <div className="hidden md:block overflow-x-auto rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow className="bg-muted/50">
                        <TableHead className="text-right">شرح</TableHead>
                        <TableHead className="text-right">مبلغ</TableHead>
                        <TableHead className="text-right">تاریخ</TableHead>
                        <TableHead className="text-right">وضعیت</TableHead>
                        
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {filteredTransactions.length === 0 ? (
                        <TableRow>
                          <TableCell colSpan={5} className="text-center py-8">
                            هیچ تراکنشی یافت نشد
                          </TableCell>
                        </TableRow>
                      ) : (
                        filteredTransactions.map((transaction) => (
                          <TableRow key={transaction.id} className="border-b">
                            <TableCell className="font-medium text-right">
                              {transaction.description}
                            </TableCell>
                            <TableCell className="text-right">
                              <span
                                className={`font-bold ${
                                  transaction.type === "expense"
                                    ? "text-green-600"
                                    : "text-red-600"
                                }`}
                              >
                                {transaction.type === "expense" ? "+" : "-"}
                                {transaction.amount.toLocaleString()}
                              </span>
                            </TableCell>
                            <TableCell className="text-right">{transaction.date}</TableCell>
                            <TableCell className="text-right">
                              <Badge
                                variant="outline"
                                className={`${
                                  transaction.type === "expense"
                                    ? "bg-yellow-500/10 text-yellow-600 border-yellow-500/30"
                                    : "bg-green-500/10 text-green-600 border-green-500/30"
                                }`}
                              >
                                {transaction.type === "expense" ? "در انتظار تسویه" : "تسویه شده"}
                              </Badge>
                            </TableCell>
                           
                          </TableRow>
                        ))
                      )}
                    </TableBody>
                  </Table>
                </div>
              
                {/* نمای موبایل - کارت‌ها */}
                <div className="md:hidden space-y-3">
                  {filteredTransactions.length === 0 ? (
                    <div className="text-center py-8 text-muted-foreground">
                      هیچ تراکنشی یافت نشد
                    </div>
                  ) : (
                    filteredTransactions.map((transaction) => (
                      <Card key={transaction.id} className="p-4">
                        <div className="flex justify-between items-start mb-2">
                          <div className="flex-1">
                            <p className="font-medium text-sm">{transaction.description}</p>
                            <p className="text-xs text-muted-foreground mt-1">
                              {transaction.date}
                            </p>
                          </div>
                          <div className="text-right">
                            <p
                              className={`font-bold text-lg ${
                                transaction.type === "expense"
                                  ? "text-green-600"
                                  : "text-red-600"
                              }`}
                            >
                              {transaction.type === "expense" ? "+" : "-"}
                              {transaction.amount.toLocaleString()}
                            </p>
                            <Badge
                              variant="outline"
                              className={`mt-1 text-xs ${
                                transaction.type === "expense"
                                  ? "bg-yellow-500/10 text-yellow-600"
                                  : "bg-green-500/10 text-green-600"
                              }`}
                            >
                              {transaction.type === "expense" ? "در انتظار تسویه" : "تسویه شده"}
                            </Badge>
                          </div>
                        </div>
                      
                      </Card>
                    ))
                  )}
                </div>
              </div>
              )}
            </CardContent>
          </Card>
        </div>
      </div>
    </ThemeProvider>
  );
};

export default WalletDashboard;