/* eslint-disable @next/next/no-img-element */

"use client";

import Container from "@/components/elements/Container";
import RoundedButton from "@/components/elements/RoundedButton";
import useAxios from "@/hooks/useAxios";
import Image from "next/image";
import { useRouter } from "next/navigation";
import React, { useState } from "react";
import toast from "react-hot-toast";
import Cookies from "js-cookie";
import { optimizeImageToWebP, optimizeVideoToMp4 } from "@/lib/media";
import TagUsersPicker, { TaggedUser } from "@/components/posts/TagUsersPicker";

function NewPost() {
  const router = useRouter();
  const { request, loading } = useAxios();
  const [postType, setPostType] = useState<"image" | "video" | null>("image");
  const [postFiles, setPostFiles] = useState<(File | null)[]>([null]);
  const [previews, setPreviews] = useState<string[]>([""]);
  const [description, setDescription] = useState<string>("");
  const [taggedUsers, setTaggedUsers] = useState<TaggedUser[]>([]);

  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);
    });
  };

  const selectFiles = (index: number) => async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (event.target.files && event.target.files[0]) {
      const file = event.target.files[0];
      const isValid = postType === "video" ? file.type.startsWith('video/') : file.type.startsWith('image/');

      if (!isValid) {
        toast.error(postType === "video" ? "فقط ویدئو مجاز است" : "فقط تصویر مجاز است");
        return;
      }

      if (postType === "video" && postFiles.length > 0) {
        toast.error("فقط یک ویدئو مجاز است");
        return;
      }

      const newFiles = [...postFiles];
      const newPreviews = [...previews];
      newFiles[index] = file;
      newPreviews[index] = URL.createObjectURL(file);
      setPostFiles(newFiles);
      setPreviews(newPreviews);

      if (postType === "image" && newFiles.filter((f) => f !== null).length < 10) {
        setPostFiles((prev) => [...prev, null]);
        setPreviews((prev) => [...prev, ""]);
        
      }
    }
  };

  const uploadPost = async () => {
    const validFiles = postFiles.filter((file) => file !== null);
    if (validFiles.length === 0) {
      toast.error("انتخاب تصویر یا ویدئو الزامی است");
      return;
    }
    if (!description) {
      toast.error("وارد کردن توضیحات الزامی است");
      return;
    }
    if (postType === "video" && validFiles.length > 1) {
      toast.error("برای ویدئو فقط یک فایل مجاز است");
      return;
    }
    if (postType === "image" && validFiles.length > 10) {
      toast.error("حداکثر 10 تصویر مجاز است");
      return;
    }

    try {
      toast.loading("در حال بهینه‌سازی مدیا…", { id: "upload-opt" });
      const optimizedFiles = await Promise.all(
        validFiles.map(async (file) => {
          if (postType === "video") {
            return optimizeVideoToMp4(file, (p) =>
              toast.loading(`فشرده‌سازی ویدئو ${p}%`, { id: "upload-opt" })
            );
          }
          return optimizeImageToWebP(file);
        })
      );
      toast.dismiss("upload-opt");

      const filesBase64 = await Promise.all(
        optimizedFiles.map(async (file) => ({
          name: file.name,
          type: file.type,
          data: await fileToBase64(file),
        }))
      );

      const tagLine = taggedUsers
        .map((u) => `@${u.user_name}`)
        .join(" ");
      const caption =
        [description, tagLine].filter(Boolean).join("\n") || description;

      const payload: Record<string, unknown> = {
        files: filesBase64,
        caption,
        tagged_user_ids: taggedUsers.map((u) => u._id),
      };

      console.log("DEBUG: Payload to send:", JSON.stringify(payload, null, 2));
      console.log("DEBUG: Authorization header:", Cookies.get('token') ? `Bearer ${Cookies.get('token')}` : 'No token');

      const response = await request("POST", "/posts/create-base64", payload, {
        headers: {
          "Content-Type": "application/json",
        },
      });
      console.log("DEBUG: Response from server:", response);
      toast.success("پست با موفقیت آپلود شد");
      router.push("/settings/profile");
    }  catch (err: unknown) {
      // اگر err یک Error معمولی باشه
      if (err instanceof Error) {
        console.error("DEBUG: Upload error:", err.message);
        toast.error("خطا در آپلود پست: " + err.message);
      } 
      // اگر err یه ساختار مشابه Axios error باشه
      else if (
        typeof err === "object" &&
        err !== null &&
        "response" in err &&
        typeof (err as { response?: { data?: { message?: string } } }).response?.data?.message === "string"
      ) {
        const msg = (err as { response: { data: { message: string } } }).response.data.message;
        console.error("DEBUG: Upload error:", msg);
        toast.error("خطا در آپلود پست: " + msg);
      } else {
        // حالت پیش فرض
        console.error("DEBUG: Upload error:", err);
        toast.error("خطا در ارتباط با سرور");
      }
    }
 }

  const removeFile = (index: number) => {
    const newFiles = [...postFiles];
    const newPreviews = [...previews];
  
    // آزادسازی URL برای فایل حذف شده
    if (newPreviews[index]) {
      URL.revokeObjectURL(newPreviews[index]);
    }
  
    newFiles.splice(index, 1);
    newPreviews.splice(index, 1);
  
    // اگر نوع پست image است و تعداد فایل‌ها کمتر از 10 شد، یک slot خالی اضافه می‌کنیم
    if (postType === "image" && newFiles.filter((f) => f !== null).length < 10) {
      newFiles.push(null);
      newPreviews.push("");
    }
  
    setPostFiles(newFiles);
    setPreviews(newPreviews);
  };
  

  const selectPostType = (type: "image" | "video" | null) => {
    setPostType(type);
  
    // آزادسازی همه previews قدیمی
    previews.forEach((url) => {
      if (url) URL.revokeObjectURL(url);
    });
  
    if (type === "image") {
      setPostFiles([null]);
      setPreviews([""]);
    } else {
      setPostFiles([]);
      setPreviews([]);
    }
  };
  

  return (
    <Container >
      <div className="flex flex-col items-center mb-4 px-3">
        <span className="text-xl font-bold mt-5">ثبت پست</span>
        
          <div className="flex gap-4 mt-10 ">
            <RoundedButton onClick={() => selectPostType("image")} className="w-36 h-10 active:bg-white focus:bg-slate-800">
              ثبت تصاویر
            </RoundedButton>
            <RoundedButton onClick={() => selectPostType("video")} className="w-36 h-10 active:bg-white focus:bg-slate-800">
              ثبت ویدئو
            </RoundedButton>
          </div>
        
          <>
            <div className="w-full max-w-md grid grid-cols-2 gap-4 mt-10">
              {postType === "video" && previews.length === 0 ? (
                <div className="w-full h-40 rounded-3xl border border-[#676767] flex items-center justify-center">
                  <label
                    htmlFor="fileInput-video"
                    className="cursor-pointer w-full h-full flex items-center justify-center text-white"
                  >
                    <Image
                      src="/images/icons/gallery-add.svg"
                      width={80}
                      height={80}
                      alt="افزودن ویدئو"
                    />
                  </label>
                  <input
                    id="fileInput-video"
                    type="file"
                    accept="video/*"
                    className="hidden"
                    onChange={selectFiles(0)}
                  />
                </div>
              ) : (
                previews.map((preview, index) => (
                  <div key={index} className="relative w-full h-40 rounded-3xl border border-[#676767] overflow-hidden flex items-center justify-center">
                    {preview ? (
                      <>
                        {postFiles[index]?.type?.startsWith('video/') ? (
                          <video
                            src={preview}
                            className="w-full h-full object-cover"
                            controls
                          />
                        ) : (
                          <img
                            src={preview}
                            alt={`Preview ${index + 1}`}
                            className="w-full h-full object-cover"
                          />
                        )}
                        <button
                          onClick={() => removeFile(index)}
                          className="p-2 absolute top-0 right-0"
                        >
                          <Image
                            src="/images/icons/close-circle.svg"
                            width={25}
                            height={25}
                            alt="حذف فایل"
                          />
                        </button>
                      </>
                    ) : (
                      <label
                        htmlFor={`fileInput-${index}`}
                        className="cursor-pointer w-full h-full flex items-center justify-center text-white"
                      >
                        <Image
                          src="/images/icons/gallery-add.svg"
                          width={80}
                          height={80}
                          alt="افزودن تصویر"
                        />
                      </label>
                    )}
                    <input
                      id={`fileInput-${index}`}
                      type="file"
                      accept={postType === "video" ? "video/*" : "image/*"}
                      className="hidden"
                      onChange={selectFiles(index)}
                    />
                  </div>
                ))
              )}
            </div>
         
          </>
        
      </div>
      <div className="flex flex-col items-center max-w-md mt-8 mx-auto px-3">
        <textarea
          placeholder="توضیحات"
          value={description}
          onChange={(e) => {
            if (e.target.value.length <= 1000) setDescription(e.target.value);
          }}
          className="w-full p-4 h-20 rounded-3xl border border-border-secondary-light dark:border-border-secondary-dark bg-secondary-light dark:bg-secondary-dark font-medium"
        />
        <span className="text-xs text-gray-500 mt-1">
          {description.length}/1000
        </span>
        <div className="mt-6 w-full">
          <TagUsersPicker
            selected={taggedUsers}
            onChange={setTaggedUsers}
            max={50}
          />
        </div>
        <div className="relative">
          <RoundedButton
            onClick={uploadPost}
            className="mt-10 w-40 h-10"
            disabled={loading || !postType}
          >
            {loading ? (
              <div className="flex items-center justify-center">
                <svg
                  className="animate-spin h-5 w-5 mr-2 text-white"
                  xmlns="http://www.w3.org/2000/svg"
                  fill="none"
                  viewBox="0 0 24 24"
                >
                  <circle
                    className="opacity-25"
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="4"
                  ></circle>
                  <path
                    className="opacity-75"
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  ></path>
                </svg>
                در حال آپلود...
              </div>
            ) : (
              "ثبت پست"
            )}
          </RoundedButton>
        </div>
      </div>
    </Container>
  );
}

export default NewPost;