"use client";
import React, { useState, useRef, useEffect } from "react";
import Cookies from "js-cookie";
import toast from "react-hot-toast";
import { useGetAllStoryQuery } from "@/app/store/api/GetStoryByUser";
import { motion } from "framer-motion";
import Image from "next/image";
import { generateCanvasStory } from "@/app/components/generateCanvasStory";
import { generateThumbnailFromVideo } from "@/app/components/GenerateThumbnail";
import { ClipLoader } from "react-spinners";
import { useAppDispatch, useAppSelector } from "@/app/hooks/hooks";
import { hideModal } from "@/app/store/Slice/modalSlice";
import TextEditor from "./TextEditor";
import TextTranslate from "@/app/utils/TextTranslate";
import { X } from "lucide-react";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";

function AddStory() {
  const [isLoading, setIsLoading] = useState(false);
  const [step, setStep] = useState(1); // Track current step: 1 for upload, 2 for edit
 const [formData, setFormData] = useState<{
  text: string;
  type: "image" | "video" | "";
  url: File | null;
}>({
  text: "",
  type: "",
  url: null,
});
  const token = Cookies.get("Snapta_auth_token");
  const { refetch } = useGetAllStoryQuery({ token: token || "" });

  const [selectedFont, setSelectedFont] = useState("Arial, sans-serif");
  const [selectedColor, setSelectedColor] = useState("#FFFFFF");

  const fileInputRef = useRef<HTMLInputElement>(null);
  const [mediaPreview, setMediaPreview] = useState<string | null>(null);
  const [storyMedia, setStoryMedia] = useState(false);
  const [showTextInput, setShowTextInput] = useState(false);
  const [storyText, setStoryText] = useState("");

  const [position, setPosition] = useState({ x: 225, y: 375 });
  const [dragging, setDragging] = useState(false);

  const dispatch = useAppDispatch();
  const onClose = () => {
    dispatch(hideModal("AddStory"));
    // Reset state on close
    setStep(1);
    setStoryMedia(false);
    setMediaPreview(null);
  };

  const isAddStoryModalVisible = useAppSelector(
    (state) => state.modals.AddStory
  );

  if (!isAddStoryModalVisible) return null;

  const handleMediaChange = (e: React.ChangeEvent<HTMLInputElement>) => {
  if (e.target.files && e.target.files[0]) {
    const file = e.target.files[0];
    
    // Allow more video formats
    const allowedTypes = [
      "image/jpeg",
      "image/png", 
      "image/jpg",
      "video/mp4",
      "video/quicktime",  // .mov files
      "video/x-msvideo",  // .avi files
      "video/webm",       // .webm files
      "video/mpeg",       // .mpeg files
      "video/3gpp",       // .3gp files
      "video/x-matroska"  // .mkv files
    ];

    // Also check by file extension for broader compatibility
    const fileExtension = file.name.split('.').pop()?.toLowerCase();
    const allowedExtensions = ['jpg', 'jpeg', 'png', 'mp4', 'mov', 'avi', 'webm', 'mpeg', '3gp', 'mkv'];

    if (!allowedTypes.includes(file.type) && !allowedExtensions.includes(fileExtension || '')) {
      showErrorToast("Only JPG, PNG, JPEG images and MP4, MOV, AVI, WEBM videos are allowed.");
      e.target.value = "";
      return;
    }

    const fileType = file.type.startsWith("video") ? "video" : "image";
    setFormData((prev) => ({ ...prev, url: file, type: fileType as "image" | "video" }));
    const mediaUrl = URL.createObjectURL(file);
    setMediaPreview(mediaUrl);
    setStoryMedia(true);
  }
};

  const uploadStory = async (formDataToSend: FormData) => {
    try {
      setIsLoading(true);
      await fetch(`${process.env.NEXT_PUBLIC_API_URL}/add_story`, {
        method: "POST",
        body: formDataToSend,
        headers: { Authorization: `Bearer ${token}` },
      });
      showSuccessToast("Story Uploaded Successfully!", "Your story has been uploaded.");
      setStoryMedia(false);
      refetch();
      onClose();
    } catch (error) {
      console.error("Error adding story:", error);
      showErrorToast("Failed to upload story.", "Something went wrong.");
    } finally {
      setIsLoading(false);
    }
  };

const handleAddStory = async () => {
  try {
    if (!formData.url) {
      showErrorToast("Please select a media first.", "A media file is required to add a story.");
      return;
    }

    // Debug logging
    console.log("Form Data Type:", formData.type);
    console.log("Form Data URL:", formData.url);
    console.log("File type:", formData.url.type);
    console.log("File size:", formData.url.size);

    const formDataToSend = new FormData();
    let thumbnailFile: File | undefined;

    if (formData.type === "video") {
      console.log("Processing video...");
      thumbnailFile = await generateThumbnailFromVideo(formData.url);
      console.log("Thumbnail generated:", thumbnailFile);
      
      // Append the original video file
      formDataToSend.append("url", formData.url);
      if (thumbnailFile) {
        formDataToSend.append("video_thumbnail", thumbnailFile);
      }
    } else {
      console.log("Processing image...");
      thumbnailFile = await generateCanvasStory({
        src: mediaPreview || "",
        type: "image",
        text: storyText,
        font: selectedFont,
        color: selectedColor,
        position,
      });
      formDataToSend.append("url", thumbnailFile);
    }

    formDataToSend.append("text", storyText);
    formDataToSend.append("type", formData.type);

    // Log FormData contents for debugging
    for (let pair of formDataToSend.entries()) {
      console.log(pair[0], pair[1]);
    }

    await uploadStory(formDataToSend);
  } catch (err) {
    console.error("Failed to handle add story:", err);
    showErrorToast("Something went wrong while preparing your story.");
  }
};

  const handleMouseDown = () => setDragging(true);
  const handleMouseMove = (e: any) => {
    if (!dragging) return;
    setPosition((prev) => ({
      x: prev.x + e.movementX,
      y: prev.y + e.movementY,
    }));
  };
  const handleMouseUp = () => setDragging(false);

  useEffect(() => {
    if (dragging) {
      window.addEventListener("mousemove", handleMouseMove);
      window.addEventListener("mouseup", handleMouseUp);
    } else {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    }
    return () => {
      window.removeEventListener("mousemove", handleMouseMove);
      window.removeEventListener("mouseup", handleMouseUp);
    };
  }, [dragging]);

  return (
    <div className="fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm z-[200] p-4">
      <div className="bg-[var(--modal-color)] rounded-3xl shadow-2xl w-full max-w-[420px] md:max-w-[500px] overflow-hidden animate-in fade-in zoom-in duration-200">
        
        {/* Header */}
        <div className="relative flex items-center justify-center px-4 py-4 border-b border-[var(--border-color)] dark:border-[color-mix(in_srgb,var(--border-color),white_07%)]">
          <button onClick={onClose} className="absolute left-6 text-[var(--text-primary)]/80 hover:text-[var(--text-primary)] transition-colors">
            <X size={24} />
          </button>
          <h2 className="text-[var(--text-primary)] font-medium text-[16px] translate-y-0.5">
            <TextTranslate text={step === 1 ? "Add Story" : "Edit Story"}/>
          </h2>
        </div>

        <div className="flex flex-col items-center p-4">
          
          {/* Step 2: Media Preview Section */}
          {step === 2 && storyMedia ? (
            <motion.div
              key="add-story"
              initial={{ opacity: 0, scale: 0.9 }}
              animate={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.3 }}
              className="relative w-full aspect-[9/16] max-h-[550px] rounded-2xl overflow-hidden shadow-xl flex items-center justify-center bg-black"
            >
              <div className="absolute inset-0 bg-black bg-opacity-40 z-10"></div>

              {formData.type === "image" && (
                <div className="z-20">
                  <TextEditor
                    storyText={storyText}
                    setStoryText={setStoryText}
                    selectedFont={selectedFont}
                    setSelectedFont={setSelectedFont}
                    selectedColor={selectedColor}
                    setSelectedColor={setSelectedColor}
                  />
                </div>
              )}

              {formData.type === "video" ? (
                <video autoPlay loop muted className="h-full w-full object-contain">
                  <source src={mediaPreview!} type={formData.url?.type} />
                </video>
              ) : (
                <img
                  src={mediaPreview!}
                  alt="Story Preview"
                  className="h-full w-full object-contain relative"
                />
              )}

              {showTextInput && (
                <div
                  className="absolute z-30 cursor-move flex flex-col items-center"
                  style={{ top: `${position.y}px`, left: `${position.x}px` }}
                  onMouseDown={handleMouseDown}
                >
                  <textarea
                    value={storyText}
                    onChange={(e) => setStoryText(e.target.value)}
                    placeholder="Add text..."
                    className="text-lg bg-black/50 p-2 rounded resize-none focus:outline-none text-white"
                    autoFocus
                    style={{ fontFamily: selectedFont, color: selectedColor }}
                  />
                </div>
              )}
            </motion.div>
         ) : (
 <div
  className="relative rounded-2xl cursor-pointer w-full aspect-[9/16] max-h-[400px] overflow-hidden flex items-center justify-center transition-all"
  style={{
    background: mediaPreview 
      ? "black" 
      : "linear-gradient(180deg, #FFFFFF 35%, #E6E0F3 50%, #BBA9E0 70%, #6C47B7 92%, #341F60 100%)",
  }}
  onClick={() => fileInputRef.current?.click()}
>
  {/* Optional: Pattern Overlay (Doodle) - only shows when no media */}
  {!mediaPreview && (
    <div 
      className="absolute inset-0 opacity-[0.08] pointer-events-none"
      style={{
        backgroundImage: `url('/assets/pattern-bg.png')`, 
        backgroundSize: 'cover',
      }}
    ></div>
  )}

  {/* Background Media Preview - No margins, full bleed */}
  {mediaPreview && (
    <div className="absolute inset-0 z-0 w-full h-full">
      {formData.type === "video" ? (
        <video 
          autoPlay 
          muted 
          loop 
          className="w-full h-full object-cover block"
        >
          <source src={mediaPreview} />
        </video>
      ) : (
        <img 
          src={mediaPreview} 
          className="w-full h-full object-cover block" 
          alt="Full Preview" 
        />
      )}
      {/* Subtle overlay to keep "Change Media" text readable */}
      <div className="absolute inset-0 bg-black/30 z-[1]"></div>
    </div>
  )}

  {/* Overlay Content */}
  <div className="relative z-10 flex flex-col items-center justify-center text-center w-full h-full">
    {!mediaPreview ? (
      <>
        <img
          src="/assets/gallery1.png"
          alt="Upload photo"
          className="w-12 h-12 mb-4 img-theme"
          style={{ 
            filter: "invert(29%) sepia(88%) saturate(1511%) hue-rotate(242deg) brightness(88%) contrast(91%)" 
          }}
        />
        <div className="text-black/60 font-medium text-[15px] font-gilroy_md drop-shadow-sm px-6">
          <TextTranslate text="Browse to Upload Image"/>
          <div className="text-black/40 text-xs mt-1 font-normal">
            (jpg, png, jpeg, mp4 format)
          </div>
        </div>
      </>
    ) : (
      <div className="text-white font-medium text-[15px] font-gilroy_md drop-shadow-lg hover:underline px-6">
        <TextTranslate text="Change Selected Media"/>
      </div>
    )}
    
    <input
  type="file"
  accept=".jpg,.jpeg,.png,.mp4,.mov,.avi,.webm,.mpeg,.3gp,.mkv"
  className="hidden"
  onChange={handleMediaChange}
  ref={fileInputRef}
/>
  </div>
</div>
          )}

          {/* Action Button */}
          <div className="w-full mt-3 -mb-1.5 ">
            {step === 1 ? (
              <button
                type="button"
                className="w-full py-2.5 bg-[#341F60] hover:bg-[#6C47B7] text-white font-medium rounded-xl text-[16px] transition-all active:scale-[0.98] shadow-md flex justify-center items-center disabled:opacity-80 disabled:cursor-not-allowed"
                onClick={() => setStep(2)}
                disabled={!storyMedia}
              >
                <TextTranslate text="Next"/>
              </button>
            ) : (
              <button
                type="button"
                className="w-full  py-2.5 bg-[#341F60] hover:bg-[#6C47B7] text-white font-medium rounded-xl text-[16px] transition-all active:scale-[0.98] shadow-md flex justify-center items-center disabled:opacity-80"
                onClick={handleAddStory}
                disabled={isLoading}
              >
                {isLoading ? (
                  <ClipLoader loading={isLoading} size={20} color="#FFFFFF" />
                ) : (
                  <TextTranslate text="Add Your Story"/>
                )}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

export default AddStory;