"use client";

import { useState, useRef, useEffect, useMemo } from "react";
import { useForm, useFieldArray } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import { motion } from "framer-motion";
import { toast } from "react-hot-toast";
import { ImageIcon } from "lucide-react";
import { Image } from "lucide-react";

import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Textarea } from "../ui/Textarea";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Trash2, Video, Plus, Upload, FileVideo, Play } from "lucide-react";
import useAxios from "@/hooks/useAxios";
import { BASE_URL, IMAGE_BASE_URL, buildStorageUrl } from "../main/BaseUrl";
import { useTranslation } from "react-i18next";
import { useAppLanguage } from "@/contexts/LanguageProvider";

interface IAcademyCategory {
  _id: string;
  title: string;
  slug: string;
  description?: string;
  icon?: string;
  color?: string;
  parent?: string | null;
  level: number;
  order: number;
  course_count: number;
  status: string;
  is_featured: boolean;
}

function buildCourseSchema(t: (key: string) => string) {
  const videoSchema = z.object({
    title: z.string().min(1, t("academyCourse.validation.videoTitleRequired")),
    file: z.any(),
    url: z.string().optional(),
    isFree: z.boolean().default(false),
  });

  return z.object({
    cuorse_name: z.string().min(1, t("academyCourse.nameRequired")),
    price: z.number().min(0).optional(),
    category: z.string().min(1, t("academyCourse.categoryRequired")),
    offer: z.number().min(0).max(100).optional(),
    caption: z.string().min(1, t("academyCourse.captionRequired")),
    course_time: z.string().min(1, t("academyCourse.timeRequired")),
    teacher_name: z.string().min(1, t("academyCourse.teacherRequired")),
    packageImage: z.string().min(1, t("academyCourse.validation.packageImageRequired")),
    is_free: z.boolean().default(false),
    contact_mobile: z.string().optional(),
    contact_telegram: z.string().optional(),
    contact_whatsapp: z.string().optional(),
    contact_instagram: z.string().optional(),
    videos: z.array(videoSchema),
  });
}

type CourseFormValues = z.infer<ReturnType<typeof buildCourseSchema>>;

interface CourseFormProps {
  initialData?: any;
  initialData2?: any;
  onSubmit: (data: CourseFormValues) => void;
  isLoading?: boolean;
}

interface MediaFile {
  id: string;
  title: string;
  file: File | null;
  preview?: string;
  course_video: string;
  type: "image" | "video";
  isFree?: boolean;
  is_free?: boolean;
}

export function CourseForm({
  initialData,
  initialData2,
  onSubmit,
  isLoading,
}: CourseFormProps) {
  const { t } = useTranslation("common");
  const { language } = useAppLanguage();
  const textDir = language === "fa" ? "rtl" : "ltr";
  const courseSchema = useMemo(() => buildCourseSchema(t), [t]);
  const [previewImage, setPreviewImage] = useState<string>("");

  const [previewProfile, setPreviewProfile] = useState<string>("");
  const [avatar, setAvatar] = useState<string | null>(null);
  // State برای عکس پکیج
  const [packageImageFile, setPackageImageFile] = useState<File | null>(null);
  const [packageImagePreview, setPackageImagePreview] = useState<string>("");

  // State برای عکس‌ها
  const [imageFields, setImageFields] = useState<MediaFile[]>([]);
  const [imageTitle, setImageTitle] = useState("");
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState("");
  const [imagePreviewUrls, setImagePreviewUrls] = useState<{
    [key: number]: string;
  }>({});

  // State برای ویدیوها (مثل قبل)
  const [videoFields, setVideoFields] = useState<MediaFile[]>([]);
  const [videoTitle, setVideoTitle] = useState("");
  const [videoFile, setVideoFile] = useState<File | null>(null);
  const [videoPreview, setVideoPreview] = useState("");
  const [isFreeVideo, setIsFreeVideo] = useState(false);
  const [videoPreviewUrls, setVideoPreviewUrls] = useState<{
    [key: number]: string;
  }>({});

  // ==========================================
  // تغییر: استفاده از دسته‌بندی آکادمی به جای تبلیغات
  // ==========================================
  const [academyCategories, setAcademyCategories] = useState<
    IAcademyCategory[]
  >([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);

  const [uploadProgress, setUploadProgress] = useState(0);
  const [isUploading, setIsUploading] = useState(false);
  const { request, loading, error } = useAxios();

  // ==========================================
  // دریافت دسته‌بندی‌های آکادمی از API جدید
  // ==========================================
  useEffect(() => {
    const fetchAcademyCategories = async () => {
      setCategoriesLoading(true);
      try {
        const response = await request<{ data: { docs: IAcademyCategory[] } }>(
          "GET",
          "/academy/categories?status=active&limit=100"
        );
        // بررسی ساختار پاسخ
        if (response?.data?.docs) {
          setAcademyCategories(response.data.docs);
        } else if (response?.data && Array.isArray(response.data)) {
          setAcademyCategories(response.data);
        } else if (Array.isArray(response)) {
          setAcademyCategories(response);
        } else {
          setAcademyCategories([]);
        }
        console.log("دسته‌بندی‌های آکادمی:", response);
      } catch (err) {
        console.log("خطا در دریافت دسته‌بندی‌های آکادمی:", err);
        toast.error(t("academyCourse.toast.fetchCategoriesError"));
      } finally {
        setCategoriesLoading(false);
      }
    };

    fetchAcademyCategories();
  }, []);

  useEffect(() => {
    const getAcademyCourses = async () => {
      console.log(initialData2._id);

      try {
        const getAcademyCourses = (await request(
          "GET",
          `/academy/academy/course/content?courseId=${initialData2._id}&page=1&limit=20`,
          {}
        )) as MediaFile;

        setVideoFields(getAcademyCourses.data.courses);
      } catch (err) {
        console.log("get error:", err);
        toast.error(t("academyCourse.toast.fetchContentError"));
      } finally {
      }
    };

    getAcademyCourses();
  }, []);

  // تابع اضافه کردن عکس
  const handleAddImage = () => {
    if (!imageTitle.trim()) {
      toast.error(t("academyCourse.toast.imageTitleRequired"));
      return;
    }
    if (!imageFile) {
      toast.error(t("academyCourse.toast.selectImageFile"));
      return;
    }

    const previewUrl = URL.createObjectURL(imageFile);
    const newIndex = imageFields.length;

    setImageFields([
      ...imageFields,
      {
        id: Date.now().toString(),
        title: imageTitle,
        file: imageFile,
        course_video: previewUrl,
        type: "image",
      },
    ]);

    setImagePreviewUrls((prev) => ({ ...prev, [newIndex]: previewUrl }));

    // Reset form
    setImageTitle("");
    setImageFile(null);
    setImagePreview("");
    const fileInput = document.getElementById(
      "imageFileInput"
    ) as HTMLInputElement;
    if (fileInput) fileInput.value = "";

    toast.success(t("academyCourse.toast.imageAdded"));
  };

  // تابع حذف عکس
  const handleRemoveImage = (index: number) => {
    if (imagePreviewUrls[index]) {
      URL.revokeObjectURL(imagePreviewUrls[index]);
    }
    setImageFields(imageFields.filter((_, i) => i !== index));
    toast.success(t("academyCourse.toast.imageRemoved"));
  };

  const form = useForm<CourseFormValues>({
    resolver: zodResolver(courseSchema),
    defaultValues:
      initialData && typeof initialData === "object"
        ? {
            cuorse_name: initialData.cuorse_name || "",
            price: initialData.is_free ? 0 : Number(initialData.price) || 0,
            category: initialData.category || "",
            offer:
              initialData.offer && initialData.offer !== "0"
                ? Number(initialData.offer)
                : undefined,
            caption: initialData.caption || "",
            course_time: initialData.course_time || "",
            teacher_name: initialData.teacher_name || "",
            packageImage: initialData.course_image || "",
            is_free: Boolean(initialData.is_free),
            contact_mobile: initialData.contactInfo?.mobile || "",
            contact_telegram: initialData.contactInfo?.telegramLink || "",
            contact_whatsapp: initialData.contactInfo?.whatsappNumber || "",
            contact_instagram: initialData.contactInfo?.instagramLink || "",
            videos: initialData.videos || [],
          }
        : {
            cuorse_name: "",
            price: 0,
            category: "",
            offer: undefined,
            caption: "",
            course_time: "",
            teacher_name: "",
            packageImage: "",
            is_free: false,
            contact_mobile: "",
            contact_telegram: "",
            contact_whatsapp: "",
            contact_instagram: "",
            videos: [],
          },
  });

  const isFreePackage = form.watch("is_free");

  useEffect(() => {
    if (!initialData || typeof initialData !== "object") {
      const preloadContactInfo = async () => {
        try {
          const response = await request<{ data: { contactInfo?: Record<string, string> } }>(
            "GET",
            "/users/contact-info"
          );
          const contactInfo = response?.data?.contactInfo;
          if (!contactInfo) return;

          if (contactInfo.mobile) form.setValue("contact_mobile", contactInfo.mobile);
          if (contactInfo.telegramLink)
            form.setValue("contact_telegram", contactInfo.telegramLink);
          if (contactInfo.whatsappNumber)
            form.setValue("contact_whatsapp", contactInfo.whatsappNumber);
          if (contactInfo.instagramLink)
            form.setValue("contact_instagram", contactInfo.instagramLink);
        } catch {
          // اطلاعات تماس اختیاری است
        }
      };

      void preloadContactInfo();
    }
  }, [initialData, request, form]);

  const {
    // fields: videoFields,
    append: appendVideo,
    remove: removeVideo,
  } = useFieldArray({
    control: form.control,
    name: "videos",
  });

  // تابع برای انتخاب فایل ویدیو
  const handleVideoFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      // چک کردن نوع فایل
      if (!file.type.startsWith("video/")) {
        toast.error(t("academyCourse.toast.invalidVideoFile"));
        return;
      }

      // چک کردن حجم فایل (حداکثر 500 مگابایت)
      if (file.size > 1024 * 1024 * 1024) {
        toast.error(t("academyCourse.toast.videoSizeLimitMb"));
        return;
      }

      setVideoFile(file);
      const previewUrl = URL.createObjectURL(file);
      setVideoPreview(previewUrl);
    }
  };

  const fileToBase64 = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  };

  // اضافه کردن state های جدید
  const [uploadChunks, setUploadChunks] = useState([]);
  const [currentChunk, setCurrentChunk] = useState(0);
  const [totalChunks, setTotalChunks] = useState(0);

  // تابع تبدیل فایل به تکه‌های کوچک
  const splitFileIntoChunks = (file, chunkSize = 10 * 1024 * 1024) => {
    const chunks = [];
    let start = 0;

    while (start < file.size) {
      const end = Math.min(start + chunkSize, file.size);
      const chunk = file.slice(start, end);
      chunks.push({
        data: chunk,
        index: chunks.length,
        start: start,
        end: end,
      });
      start = end;
    }

    return chunks;
  };

  // تابع تبدیل تکه به Base64 (برای هر تکه جداگانه)
  const chunkToBase64 = (chunk) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
      reader.readAsDataURL(chunk);
    });
  };

  // تابع اصلی آپلود با روش تکه‌تکه
  // اضافه کردن تابع برای بررسی تکه‌های آپلود شده قبلی
  const checkUploadedChunks = async (courseId, fileName) => {
    try {
      const response = await request(
        "GET",
        `/academy/academy/course/upload-status?courseId=${courseId}&originalFileName=${fileName}`,
        {},
        { timeout: 10000 }
      );
      return response;
    } catch (error) {
      console.log("Error checking uploaded chunks:", error);
      return { uploadedChunks: [], totalChunks: 0 };
    }
  };

  // تابع اصلی آپلود با قابلیت Resume
  const uploadVideoInChunks = async (file, courseId, isFree, fileName) => {
    const CHUNK_SIZE = 10 * 1024 * 1024; // 10 مگابایت
    const chunks = splitFileIntoChunks(file, CHUNK_SIZE);
    const totalChunksCount = chunks.length;

    setTotalChunks(totalChunksCount);
    setCurrentChunk(0);

    // بررسی تکه‌های قبلی آپلود شده
    const uploadStatus = await checkUploadedChunks(courseId, file.name);
    const uploadedChunksSet = new Set(uploadStatus.uploadedChunks || []);

    let startFromChunk = 0;
    if (uploadedChunksSet.size > 0) {
      // پیدا کردن اولین تکه که آپلود نشده
      for (let i = 0; i < totalChunksCount; i++) {
        if (!uploadedChunksSet.has(i)) {
          startFromChunk = i;
          break;
        }
      }

      if (startFromChunk > 0) {
        toast.success(
          t("academyCourse.toast.resumeUploadChunk", {
            chunk: startFromChunk + 1,
          })
        );
      }
    }

    for (let i = startFromChunk; i < chunks.length; i++) {
      const chunk = chunks[i];

      // تبدیل تکه فعلی به Base64
      const base64Chunk = await chunkToBase64(chunk.data);

      // ارسال تکه به سرور با قابلیت retry
      let retryCount = 0;
      let success = false;

      while (retryCount < 3 && !success) {
        try {
          const response = await request(
            "POST",
            "/academy/academy/course/creat/video-chunk",
            {
              courseId: courseId,
              is_free: isFree,
              file_name: fileName,
              chunk: base64Chunk,
              chunkIndex: i,
              totalChunks: totalChunksCount,
              originalFileName: file.name,
              fileSize: file.size,
              mime_type: file.type,
            },
            {
              timeout: 180000,
              maxContentLength: Infinity,
              maxBodyLength: Infinity,
            }
          );

          if (response?.error) {
            throw new Error(response.message);
          }

          success = true;
          console.log(`✅ Chunk ${i + 1}/${totalChunksCount} uploaded`);
        } catch (err) {
          retryCount++;
          console.log(`❌ Chunk ${i + 1} failed, retry ${retryCount}/3`);

          if (retryCount === 3) {
            throw new Error(
              `Chunk ${i + 1} failed after 3 attempts: ${err.message}`
            );
          }

          //等待 2 秒后再重试
          await new Promise((resolve) => setTimeout(resolve, 2000));
        }
      }

      // به روز رسانی پیشرفت
      const progress = Math.round(((i + 1) / totalChunksCount) * 100);
      setUploadProgress(progress);
      setCurrentChunk(i + 1);
    }

    // بعد از اتمام همه تکه‌ها، درخواست نهایی برای ترکیب
    const finalResponse = await request(
      "POST",
      "/academy/academy/course/creat/video-chunk/merge",
      {
        courseId: courseId,
        originalFileName: file.name,
        totalChunks: totalChunksCount,
      },
      {
        timeout: 60000,
      }
    );

    return finalResponse;
  };

  // تابع handleAddVideo جدید (جایگزین تابع قبلی)
  const handleAddVideo = async () => {
    if (!videoTitle.trim()) {
      toast.error(t("academyCourse.toast.enterVideoTitle"));
      return;
    }
    if (!videoFile) {
      toast.error(t("academyCourse.toast.selectVideoFile"));
      return;
    }

    if (!initialData2?._id) {
      toast.error(t("academyCourse.courseIdMissing"));
      return;
    }

    // بررسی حجم فایل
    if (videoFile.size > 1024 * 1024 * 1024) {
      toast.error(t("academyCourse.toast.videoSizeLimitGb"));
      return;
    }

    const previewUrl = URL.createObjectURL(videoFile);
    setIsUploading(true);
    setUploadProgress(0);

    try {
      const loadingToast = toast.loading(t("academyCourse.toast.uploadingVideoChunks"));

      // آپلود با روش تکه‌تکه
      const response = await uploadVideoInChunks(
        videoFile,
        initialData2._id,
        isFreeVideo,
        videoTitle
      );

      toast.dismiss(loadingToast);
      console.log("پاسخ سرور:", response);

      if (response?.success) {
        toast.success(t("academyCourse.toast.videoUploadSuccess"));

        setVideoFields([
          ...videoFields,
          {
            id: Date.now().toString(),
            title: videoTitle,
            file: videoFile,
            course_video: previewUrl,
            type: "video",
            is_free: isFreeVideo,
            _id: response.data?._id,
          },
        ]);

        // پاک کردن فرم
        setVideoTitle("");
        setVideoFile(null);
        setVideoPreview("");
        setIsFreeVideo(false);
        setUploadProgress(0);
        setCurrentChunk(0);
        setTotalChunks(0);

        const fileInput = document.getElementById(
          "videoFileInput"
        ) as HTMLInputElement;
        if (fileInput) fileInput.value = "";
      } else {
        toast.error(response?.message || t("academyCourse.toast.videoUploadError"));
      }
    } catch (err: any) {
      console.error("Upload error:", err);
      toast.error(err?.response?.data?.message || t("academyCourse.toast.videoUploadError"));
    } finally {
      setIsUploading(false);
    }
  };

  const fileToBase64WithProgress = (file, onProgress) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();

      reader.onprogress = (event) => {
        if (event.lengthComputable && onProgress) {
          const percentComplete = Math.round((event.loaded / event.total) * 50); // 50% برای تبدیل
          onProgress(percentComplete);
        }
      };

      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
      reader.readAsDataURL(file);
    });
  };

  const handleRemoveVideo = async (index: number, field) => {
    console.log(field.courseId);
    const deleteCourseContent = await request(
      "DELETE",
      `/academy/academy/course/content/video`,
      {
        courseContentId: field._id,
        courseId: field.courseId,
      }
    );
    setVideoFields(videoFields.filter((_, i) => i !== index));
    toast.success(t("academyCourse.toast.videoRemoved"));
  };

  const selectImage = (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      const previewUrl = URL.createObjectURL(file);
      if (file) {
        const url = URL.createObjectURL(file);
        setPreviewImage(url);
        form.setValue("packageImage", url);
      }
      setPreviewProfile(previewUrl);
      setAvatar(previewUrl);
    }
  };

  // تابع برای ارسال فرم (در CourseForm)
  const onSubmitForm = (data: CourseFormValues) => {
    // ارسال همه داده‌ها به پدر
    const formDataToSend = {
      ...data,
      videos: videoFields.map((video) => ({
        title: video.title,
        file: video.file,
        isFree: video.isFree || false,
      })),
      imageFields: imageFields.map((image) => ({
        title: image.title,
        file: image.file,
      })),
    };

    onSubmit(formDataToSend);
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmitForm)} className="space-y-6">
        <Tabs defaultValue="basic" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger
              className={`${initialData === "videos" ? "hidden" : ""}`}
              value="basic"
            >
              {t("academyCourse.form.tabBasicInfo")}
            </TabsTrigger>
            <TabsTrigger
              className={`${initialData === "videos" ? "" : "hidden"}`}
              value="videos"
            >
              {t("academyCourse.form.tabVideosCount", {
                count: videoFields.length,
              })}
            </TabsTrigger>
            {/* <TabsTrigger
              className={`${initialData === "videos" ? "hidden" : ""}`}
              value="media"
            >
              رسانه
            </TabsTrigger> */}
          </TabsList>

          {/* تب اطلاعات پایه */}
          <TabsContent dir={textDir} value="basic" className="space-y-4 mt-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="cuorse_name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("academyCourse.form.packageName")}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("academyCourse.form.packageNamePlaceholder")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="teacher_name"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("academyCourse.form.teacherName")}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("academyCourse.form.teacherNamePlaceholder")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="price"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("academyCourse.form.price")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("academyCourse.form.pricePlaceholder")}
                        disabled={isFreePackage}
                        onChange={(e) =>
                          field.onChange(
                            e.target.value === ""
                              ? undefined
                              : Number(e.target.value)
                          )
                        }
                        value={isFreePackage ? 0 : field.value ?? ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="is_free"
                render={({ field }) => (
                  <FormItem className="flex items-center gap-2 space-y-0 md:col-span-2">
                    <FormControl>
                      <Checkbox
                        checked={field.value}
                        onCheckedChange={(checked) => {
                          const isFree = checked === true;
                          field.onChange(isFree);
                          if (isFree) {
                            form.setValue("price", 0);
                            form.setValue("offer", undefined);
                          }
                        }}
                      />
                    </FormControl>
                    <FormLabel className="!mt-0 cursor-pointer">
                      {t("academyCourse.form.freePackage")}
                    </FormLabel>
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="offer"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("academyCourse.form.discount")}</FormLabel>
                    <FormControl>
                      <Input
                        type="number"
                        placeholder={t("academyCourse.form.discountPlaceholder")}
                        disabled={isFreePackage}
                        onChange={(e) =>
                          field.onChange(
                            e.target.value === ""
                              ? undefined
                              : Number(e.target.value)
                          )
                        }
                        value={field.value ?? ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="category"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("academyCourse.form.academyCategory")}</FormLabel>
                    <Select
                      onValueChange={(selectedId) => {
                        // پیدا کردن دسته‌بندی انتخاب شده
                        const selectedCategory = academyCategories.find(
                          (cat) => cat._id === selectedId
                        );
                        // ذخیره کردن title (اسم دسته‌بندی) به جای _id
                        field.onChange(selectedCategory?.title || selectedId);
                      }}
                      defaultValue={field.value}
                    >
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue
                            placeholder={t("academyCourse.form.selectCategory")}
                          />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        {categoriesLoading ? (
                          <SelectItem value="loading" disabled>
                            {t("academyCourse.loading")}
                          </SelectItem>
                        ) : academyCategories.length === 0 ? (
                          <SelectItem value="empty" disabled>
                            {t("academyCourse.form.noCategories")}
                          </SelectItem>
                        ) : (
                          academyCategories.map((category) => (
                            <SelectItem
                              dir={textDir}
                              key={category._id}
                              value={category._id}
                            >
                              <div className="flex items-center gap-2">
                                {category.icon && (
                                  <span className="text-lg">
                                    {category.icon}
                                  </span>
                                )}
                                <span style={{ color: category.color }}>
                                  {category.title}
                                </span>
                                {category.course_count > 0 && (
                                  <span className="text-xs text-gray-400">
                                    ({category.course_count})
                                  </span>
                                )}
                              </div>
                            </SelectItem>
                          ))
                        )}
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="course_time"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>{t("academyCourse.form.courseTime")}</FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("academyCourse.form.courseTimePlaceholder")}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-3 rounded-xl border border-border-primary-light p-4">
              <FormLabel className="text-base">
                {t("academyCourse.form.contactInfoOptional")}
              </FormLabel>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="contact_mobile"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input
                          placeholder={t("academyCourse.form.mobilePlaceholder")}
                          maxLength={11}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="contact_telegram"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input
                          placeholder={t("academyCourse.form.telegramPlaceholder")}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="contact_whatsapp"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input
                          placeholder={t("academyCourse.form.whatsappPlaceholder")}
                          maxLength={11}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <FormField
                  control={form.control}
                  name="contact_instagram"
                  render={({ field }) => (
                    <FormItem>
                      <FormControl>
                        <Input
                          placeholder={t("academyCourse.form.instagramPlaceholder")}
                          {...field}
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>
            </div>

            <FormField
              control={form.control}
              name="caption"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>{t("academyCourse.form.caption")}</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder={t("academyCourse.form.captionPlaceholder")}
                      className="min-h-[120px]"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormItem>
              <FormLabel>{t("academyCourse.form.packageImage")}</FormLabel>
              <FormControl>
                <Input
                  id="fileInput"
                  type="file"
                  accept="image/*"
                  onChange={selectImage}
                />
              </FormControl>
              {previewImage && (
                <motion.img
                  src={previewProfile}
                  alt="Preview"
                  className="w-48 h-48 object-cover rounded-lg mt-2 border"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                />
              )}
              <FormMessage />
            </FormItem>
          </TabsContent>

          {/* تب ویدیوها */}
          <TabsContent dir={textDir} value="videos" className="space-y-4 mt-4">
            {/* بخش آپلود ویدیو */}
            <Card className="border-2 border-dashed mt-6">
              <CardContent className="pt-6">
                <div className="flex items-center gap-2 mb-4">
                  <Video className="w-5 h-5 text-primary" />
                  <h3 className="text-lg font-semibold">
                    {t("academyCourse.form.addNewVideo")}
                  </h3>
                  <span className="text-xs text-muted-foreground">
                    {t("academyCourse.form.optional")}
                  </span>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="text-sm font-medium mb-2 block">
                      {t("academyCourse.form.videoTitle")}
                    </label>
                    <Input
                      placeholder={t("academyCourse.form.videoTitlePlaceholder")}
                      value={videoTitle}
                      onChange={(e) => setVideoTitle(e.target.value)}
                    />
                  </div>

                  <div>
                    <label className="text-sm font-medium mb-2 block">
                      {t("academyCourse.form.videoFile")}
                    </label>
                    <div className="flex items-center gap-2">
                      <Input
                        id="videoFileInput"
                        type="file"
                        accept="video/*"
                        onChange={handleVideoFileSelect}
                        className="flex-1"
                      />
                      {videoFile && (
                        <span className="text-xs text-green-600">
                          {videoFile.name}
                        </span>
                      )}
                    </div>
                    {videoPreview && (
                      <div className="mt-3">
                        <video
                          src={videoPreview}
                          controls
                          className="w-full max-h-48 rounded-lg border"
                          controlsList="nodownload"
                        />
                      </div>
                    )}
                  </div>

                  <div className="flex items-center gap-2">
                    <Checkbox
                      id="isFree"
                      checked={isFreeVideo}
                      onCheckedChange={(checked) =>
                        setIsFreeVideo(checked as boolean)
                      }
                    />
                    <label htmlFor="isFree" className="text-sm cursor-pointer">
                      {t("academyCourse.form.freeVideo")}
                    </label>
                  </div>

                  <Button
                    type="button"
                    onClick={handleAddVideo}
                    className="w-full"
                    variant="outline"
                    disabled={!videoTitle.trim() || !videoFile || isUploading}
                  >
                    <Plus className="w-4 h-4 ml-2" />
                    {isUploading
                      ? t("academyCourse.form.uploading")
                      : t("academyCourse.form.submitVideo")}
                  </Button>

                  {isUploading && (
                    <div className="mt-4 space-y-2">
                      <div className="flex justify-between text-sm">
                        <span className="text-gray-600">
                          {t("academyCourse.form.uploading")}
                        </span>
                        <span className="text-gray-600 font-medium">
                          {uploadProgress}%
                        </span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2.5 overflow-hidden">
                        <motion.div
                          className="bg-gradient-to-r from-pink-500 to-purple-500 h-2.5 rounded-full"
                          initial={{ width: 0 }}
                          animate={{ width: `${uploadProgress}%` }}
                          transition={{ duration: 0.3 }}
                        />
                      </div>
                      <p className="text-xs text-gray-400 text-center">
                        {t("academyCourse.form.uploadWaitHint")}
                      </p>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>

            {/* لیست ویدیوهای اضافه شده */}
            {videoFields.length > 0 && (
              <div className="space-y-3 mt-6">
                <h3 className="font-semibold flex items-center gap-2">
                  <Video className="w-4 h-4" />
                  {t("academyCourse.form.addedVideosCount", {
                    count: videoFields.length,
                  })}
                </h3>

                {videoFields.map((field, index) => (
                  <div
                    key={field.id}
                    className="border rounded-lg overflow-hidden bg-muted/30"
                  >
                    <div className="p-3">
                      <div className="flex items-start justify-between">
                        <div className="flex-1">
                          <div className="flex items-center gap-2 mb-2">
                            <Play className="w-4 h-4 text-primary" />
                            <span className="font-medium">{field.title}</span>
                            {field.is_free && (
                              <span className="text-xs bg-green-100 text-green-700 px-2 py-0.5 rounded">
                                {t("academyCourse.form.freeBadge")}
                              </span>
                            )}
                          </div>
                        </div>
                        <Button
                          type="button"
                          variant="ghost"
                          size="sm"
                          onClick={() => handleRemoveVideo(index, field)}
                          className="text-red-500 hover:text-red-700"
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </div>

                      <div className="mt-2">
                        <video
                          src={buildStorageUrl(field.course_video)}
                          controls
                          className="w-full max-h-64 rounded-lg"
                          controlsList="nodownload"
                        >
                          {t("academyCourse.form.videoUnsupported")}
                        </video>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}

            {/* اخطار برای زمانی که چیزی اضافه نشده */}
            {videoFields.length === 0 && (
              <div className="text-center py-8 text-muted-foreground border-2 border-dashed rounded-lg mt-6">
                <FileVideo className="w-12 h-12 mx-auto mb-3 opacity-50" />
                <p>{t("academyCourse.form.noVideos")}</p>
                <p className="text-sm">
                  {t("academyCourse.form.noVideosHint")}
                </p>
              </div>
            )}
          </TabsContent>

          {/* تب رسانه */}
          {/* <TabsContent dir="rtl" value="media" className="space-y-4 mt-4">
            <FormItem>
              <FormLabel>عکس پکیج</FormLabel>
              <FormControl>
                <Input
                  id="fileInput"
                  type="file"
                  accept="image/*"
                  onChange={selectImage}
                />
              </FormControl>
              {previewImage && (
                <motion.img
                  src={previewProfile}
                  alt="Preview"
                  className="w-48 h-48 object-cover rounded-lg mt-2 border"
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                />
              )}
              <FormMessage />
            </FormItem>
          </TabsContent> */}
        </Tabs>

        <div className="flex justify-end gap-3 pt-4 border-t">
          <Button type="submit" disabled={isLoading}>
            {isLoading
              ? t("academyCourse.submitting")
              : initialData
              ? t("academyCourse.editPackage")
              : t("academyCourse.createPackageBtn")}
          </Button>
        </div>
      </form>
    </Form>
  );
}
