"use client";

import { useEffect, useMemo, useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
import { CourseForm } from "./CourseForm";
import { CourseList } from "./CourseList";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Course } from "@/types/types";
import { toast } from "react-hot-toast";
import useAxios from "@/hooks/useAxios";
import SubscriptionCard from "./SubscriptionCard";
import Cookies from "js-cookie";
import { useTranslation } from "react-i18next";
function appendCourseFormFields(formData: FormData, data: any) {
  formData.append("is_free", data.is_free ? "true" : "false");
  formData.append("price", data.is_free ? "0" : String(data.price ?? "0"));
  formData.append("cuorse_name", data.cuorse_name);
  formData.append("category", data.category);
  formData.append("offer", data.offer != null && data.offer !== "" ? String(data.offer) : "0");
  formData.append("caption", data.caption);
  formData.append("course_time", data.course_time);
  formData.append("number_of_course_content", "0");
  formData.append("teacher_name", data.teacher_name);
  formData.append("contact_mobile", data.contact_mobile || "");
  formData.append("contact_telegram", data.contact_telegram || "");
  formData.append("contact_whatsapp", data.contact_whatsapp || "");
  formData.append("contact_instagram", data.contact_instagram || "");
}

// دیتای موقت برای نمایش
const mockCourses: Course[] = [
  {
    id: "1",
    name: "دوره جامع React",
    price: 1200000,
    category: "programming",
    discount: 20,
    caption: "آموزش کامل React از مقدماتی تا پیشرفته",
    duration: "15 ساعت",
    videoCount: 25,
    instructor: "علی رضایی",
    packageImage: "/courses/react.jpg",
    videos: [
      { title: "مقدمه", url: "video1.mp4", isFree: true },
      { title: "نصب و راه اندازی", url: "video2.mp4", isFree: false },
    ],
  },
];

export function CourseManager() {
  const { t } = useTranslation("common");
  const subscriptionPlans = useMemo(
    () => [
      { duration: "1month", label: t("academyCourse.plans.oneMonth"), price: 99000 },
      {
        duration: "3month",
        label: t("academyCourse.plans.threeMonth"),
        price: 270000,
        discount: 10,
      },
      {
        duration: "1year",
        label: t("academyCourse.plans.oneYear"),
        price: 990000,
        discount: 20,
      },
    ],
    [t]
  );
  const [courses, setCourses] = useState<Course[]>([]);
  const [selectedCourse, setSelectedCourse] = useState<
    Course | undefined | string
  >();
  const [selectedCourse2, setSelectedCourse2] = useState<
    Course | undefined | string
  >();
  const [selectedCourseId, setSelectedCourseId] = useState<
    Course | undefined | string
  >();
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isDialogOpen1, setIsDialogOpen1] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("list");

  // State های مربوط به صفحه‌بندی
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalCourses, setTotalCourses] = useState(0);
  const itemsPerPage = 6;

  const { request, loading, error } = useAxios();

  // تابع دریافت دوره‌ها با صفحه‌بندی
  const fetchCourses = async (page = 1) => {
    setIsLoading(true);
    try {
      const response = await request(
        "GET",
        `/academy/academy/get/course?page=${page}&limit=${itemsPerPage}`
      );

      // توجه: با توجه به ساختار دیتای شما
      if (response?.data?.courses) {
        setCourses(response.data.courses);
        setTotalPages(response.data.pagination?.totalPages || 1);
        setTotalCourses(response.data.pagination?.totalItems || 0);
        setCurrentPage(page);
      } else if (response?.courses) {
        // ساختار جایگزین
        setCourses(response.courses);
        setTotalPages(response.pagination?.totalPages || 1);
        setTotalCourses(response.pagination?.totalItems || 0);
        setCurrentPage(page);
      } else {
        console.error("ساختار پاسخ نامعتبر:", response);
        toast.error(t("academyDashboard.fetchStructureError"));
      }
    } catch (err) {
      console.error("get error:", err);
      toast.error(t("academyDashboard.fetchError"));
    } finally {
      setIsLoading(false);
    }
  };

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

  const handlePageChange = (page: number) => {
    if (page < 1 || page > totalPages) return;
    fetchCourses(page);
    // اسکرول به بالای صفحه
    window.scrollTo({ top: 0, behavior: "smooth" });
  };

  const handleCreateCourse = async (data: any) => {
    setIsLoading(true);

    try {
      // اینجا درخواست به API بزن
      const newCourse = {
        ...data,
        id: Date.now().toString(),
        createdAt: new Date(),
      };

      const fileInput = document.getElementById(
        "fileInput"
      ) as HTMLInputElement;

      if (!data.cuorse_name) {
        toast.error(t("academyCourse.nameRequired"));
        setIsLoading(false);
        return;
      }
      if (!data.teacher_name) {
        toast.error(t("academyCourse.teacherRequired"));
        setIsLoading(false);
        return;
      }
      if (!data.is_free && !data.price) {
        toast.error(t("academyCourse.priceRequired"));
        setIsLoading(false);
        return;
      }
      if (!data.category) {
        toast.error(t("academyCourse.categoryRequired"));
        setIsLoading(false);
        return;
      }
      if (!data.course_time) {
        toast.error(t("academyCourse.timeRequired"));
        setIsLoading(false);
        return;
      }
      if (!data.caption) {
        toast.error(t("academyCourse.captionRequired"));
        setIsLoading(false);
        return;
      }

      if (!fileInput?.files?.[0]) {
        toast.error(t("academyCourse.mediaRequired"));
        setIsLoading(false);
        return;
      }

      const formData = new FormData();
      formData.append("course_image", fileInput.files[0]);
      appendCourseFormFields(formData, data);

      try {
        await request("POST", "/academy/academy/creat/course", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });

        toast.success(t("academyCourse.createSuccess"));
        setIsDialogOpen(false);
        setSelectedCourse(undefined);
        await fetchCourses(currentPage);
      } catch (err) {
        console.error("Upload error:", err);
        toast.error(t("academyCourse.saveError"));
      } finally {
        setIsLoading(false);
      }
    } catch (error) {
      toast.error(t("academyCourse.createError"));
    } finally {
      setIsLoading(false);
    }
  };
  const handleEditCourse = async (data: any) => {
    setIsLoading(true);

    const fileInput = document.getElementById("fileInput") as HTMLInputElement;

    try {
      const formData = new FormData();

      appendCourseFormFields(formData, data);
      formData.append("courseId", data._id);

      // ========== اضافه کردن عکس (فقط در صورت وجود) ==========
      if (fileInput && fileInput.files && fileInput.files[0]) {
        formData.append("course_image", fileInput.files[0]);
      }
      // اگر عکس جدیدی انتخاب نشده، فیلد course_image رو ارسال نکن

      const response = await request(
        "PATCH",
        "/academy/academy/update/course",
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );

      toast.success(t("academyCourse.updateSuccess"));
      setIsDialogOpen(false);
      setSelectedCourse(undefined);
      await fetchCourses(currentPage);
    } catch (err) {
      console.error("Upload error:", err);
      toast.error(t("academyCourse.updateError"));
    } finally {
      setIsLoading(false);
    }
  };

  const handleDeleteCourse = async (_id: string) => {
    if (confirm(t("academyCourse.deleteConfirm"))) {
      setIsLoading(true);
      try {
        await request("DELETE", "/academy/academy/delete/course", {
          courseId: _id,
        });

        toast.success(t("academyCourse.deleteSuccess"));

        // بعد از حذف، صفحه جاری را مجدداً fetch کن
        fetchCourses(currentPage);
      } catch (err) {
        console.error("Upload error:", err);
        toast.error(t("academyCourse.deleteError"));
      } finally {
        setIsLoading(false);
      }
    }
  };
  const handlePurchase = async (plan: {
    duration: string;
    label: string;
    price: number;
    discount?: number;
  }) => {
    let loadingToastId = null;

    try {
      // اعتبارسنجی
      if (!selectedCourseId) {
        toast.error(t("academyCourse.courseIdMissing"));
        return;
      }

      if (!plan?.duration) {
        toast.error(t("academyCourse.planTypeMissing"));
        return;
      }

      const token = Cookies.get("token");
    
      if (!token) {
        toast.error(t("academyCourse.loginRequired"));
        
      }

      // نمایش لودینگ
      loadingToastId = toast.loading(t("academyCourse.connectingPayment"));

      const response = await request(
        "POST",
        "/academy/academy/course/payment",
        {
          courseId: selectedCourseId,
          planDuration: plan.duration,
        }
      );

      // بستن لودینگ
      toast.dismiss(loadingToastId);

      // پردازش پاسخ (ساختارهای مختلف احتمالی)
      let authority = null;
      let paymentUrl = null;

      if (response?.data?.authority) {
        authority = response.data.authority;
        paymentUrl = `https://www.zarinpal.com/pg/StartPay/${authority}`;
      } else if (response?.authority) {
        authority = response.authority;
        paymentUrl = `https://www.zarinpal.com/pg/StartPay/${authority}`;
      } else if (response?.data?.paymentUrl) {
        paymentUrl = response.data.paymentUrl;
      } else if (response?.paymentUrl) {
        paymentUrl = response.paymentUrl;
      }

      if (paymentUrl) {
        window.open(paymentUrl, "_blank", "noopener,noreferrer");
        toast.success(t("academyCourse.redirectedToPayment"));

        setTimeout(() => {
          setIsDialogOpen1?.(false);
        }, 1000);
      } else {
        console.error("ساختار پاسخ نامعتبر:", response);
        toast.error(
          response?.data?.message ||
            response?.message ||
            t("academyCourse.paymentInfoError")
        );
      }
    } catch (err: any) {
      // بستن لودینگ در صورت خطا
      if (loadingToastId) {
        toast.dismiss(loadingToastId);
      }

      console.error("خطا در شروع پرداخت:", err);

      // استخراج پیام خطا
      let errorMessage = t("academyCourse.paymentStartError");

      if (err?.response?.data?.message) {
        errorMessage = err.response.data.message;
      } else if (err?.response?.data?.error) {
        errorMessage = err.response.data.error;
      } else if (err?.message) {
        errorMessage = err.message;
      }

      // نمایش خطاهای خاص زرین‌پال
      if (errorMessage.includes("amount") || errorMessage.includes("مبلغ")) {
        errorMessage = t("academyCourse.invalidAmount");
      } else if (errorMessage.includes("merchant")) {
        errorMessage = t("academyCourse.gatewayConfigError");
      }

      toast.error(errorMessage);
    }
  };

  const handleEdit = (course: Course) => {
    setSelectedCourse(course);
    setActiveTab("list");
    setIsDialogOpen(true);
  };
  const handleVideo = (course: Course) => {
    setSelectedCourse2(course);
    setSelectedCourse("videos");
    setActiveTab("list");
    setIsDialogOpen(true);
    setSelectedCourseId(course._id);
  };
  const handlePro = (courseId: string) => {
    setIsDialogOpen1(true);
    setSelectedCourseId(courseId);
  };
  const handleAddVideo = async (data: any) => {
    setIsLoading(true);

    try {
      //   // پردازش ویدیوها
      //   if (data.videos && data.videos.length > 0) {
      //     for (const video of data.videos) {
      //       const formData = new FormData();
      //       formData.append("courseId", selectedCourseId as string);
      //       formData.append("title", video.title);
      //       formData.append("isFree", video.isFree ? "true" : "false");
      //       formData.append("video", video.file);

      //       const response = await request("POST", "/academy/academy/course/add-video", formData, {
      //         headers: {
      //           "Content-Type": "multipart/form-data",
      //         },
      //       });

      //       console.log("ویدیو با موفقیت اضافه شد:", response);
      //       toast.success(`ویدیو "${video.title}" با موفقیت اضافه شد`);
      //     }
      //   }

      //   // پردازش عکس‌ها
      //   if (data.imageFields && data.imageFields.length > 0) {
      //     for (const image of data.imageFields) {
      //       const formData = new FormData();
      //       formData.append("courseId", selectedCourseId as string);
      //       formData.append("title", image.title);
      //       formData.append("image", image.file);

      //       const response = await request("POST", "/academy/academy/course/add-image", formData, {
      //         headers: {
      //           "Content-Type": "multipart/form-data",
      //         },
      //       });

      //       console.log("عکس با موفقیت اضافه شد:", response);
      //       toast.success(`عکس "${image.title}" با موفقیت اضافه شد`);
      //     }
      //   }

      setIsDialogOpen(false);
    } catch (error) {
      console.error("خطا در آپلود:", error);
      toast.error(t("academyCourse.uploadError"));
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="container mx-auto px-4 py-6 lg:px-6">
      <div className="flex justify-between items-center mb-6">
        <h1 className="text-3xl font-bold">{t("academyCourse.manageTitle")}</h1>
        <Button
          onClick={() => {
            setSelectedCourse(undefined);
            setIsDialogOpen(true);
          }}
        >
          <Plus className="w-4 h-4 ml-2" />
          {t("academyCourse.createPackage")}
        </Button>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-1">
          <TabsTrigger value="list">{t("academyCourse.listTab")}</TabsTrigger>
          {/* <TabsTrigger value="create">ایجاد پکیج جدید</TabsTrigger> */}
        </TabsList>

        <TabsContent value="list" className="mt-6">
          {courses.length === 0 ? (
            <div className="text-center py-12">
              <p className="text-muted-foreground">{t("academyCourse.empty")}</p>
              <Button
                variant="outline"
                className="mt-4"
                onClick={() => setIsDialogOpen(true)}
              >
                {t("academyCourse.createFirst")}
              </Button>
            </div>
          ) : (
            <CourseList
              courses={courses}
              onEdit={handleEdit}
              onDelete={handleDeleteCourse}
              onVideo={handleVideo}
              onPro={handlePro}
              currentPage={currentPage}
              totalPages={totalPages}
              totalCourses={totalCourses}
              onPageChange={handlePageChange}
              isLoading={isLoading}
            />
          )}
        </TabsContent>

        {/* <TabsContent value="create" className="mt-6">
          <div className="max-w-4xl mx-auto">
            <CourseForm
              initialData={selectedCourse}
              onSubmit={selectedCourse ? handleEditCourse : handleCreateCourse}
              isLoading={isLoading}
            />
          </div>
        </TabsContent> */}
      </Tabs>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {selectedCourse ? t("academyCourse.editPackage") : t("academyCourse.createPackage")}
            </DialogTitle>
          </DialogHeader>
          <CourseForm
            initialData={selectedCourse}
            onSubmit={
              selectedCourse === "videos"
                ? handleAddVideo
                : selectedCourse
                ? handleEditCourse
                : handleCreateCourse
            }
            initialData2={selectedCourse2}
            isLoading={isLoading}
          />
        </DialogContent>
      </Dialog>
      <Dialog open={isDialogOpen1} onOpenChange={setIsDialogOpen1}>
        <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">

          <div>
            <SubscriptionCard
              benefits={[t("academyCourse.highlightBenefit")]}
              plans={subscriptionPlans}
              currency={t("settings.toman")}
              onPurchase={handlePurchase}
            />
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
