"use client";
import React, { useState, useEffect, useRef } from "react";
import { showModal } from "@/app/store/Slice/modalSlice";
import useApiPost from "@/app/hooks/postData";
import Delete from "../../../../public/assets/DeletePost.png";
import Image from "next/image";
import { ClipLoader } from "react-spinners";
import TextTranslate from "@/app/utils/TextTranslate";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { LinkIcon } from "lucide-react"; // Import Link icon

function DeletePost({
  postId,
  postType,
  onClose,
  onDelete
}: {
  postId: string;
  postType: string;
  onClose: () => void;
  onDelete: () => void;
}) {
  const [deleteConfirmation, setDeleteConfirmation] = useState(false);
  const { postData, loading } = useApiPost();
  
  const wrapperRef = useRef<HTMLDivElement | null>(null);
  const confirmRef = useRef<HTMLDivElement | null>(null);

  // Copy Link Function
  const handleCopyLink = async () => {
    const baseUrl = window.location.origin;
    const link = postType === "reel" 
      ? `${baseUrl}/Reels/${postId}`
       : `${baseUrl}/Home/Post/${postId}`;
    
    try {
      if (navigator.clipboard && window.isSecureContext) {
        await navigator.clipboard.writeText(link);
      } else {
        const textarea = document.createElement("textarea");
        textarea.value = link;
        textarea.style.position = "fixed";
        textarea.style.opacity = "0";
        document.body.appendChild(textarea);
        textarea.focus();
        textarea.select();
        document.execCommand("copy");
        document.body.removeChild(textarea);
      }
      showSuccessToast("Link copied!", "You can now share it anywhere.");
    } catch (err) {
      showErrorToast("Failed to copy link.", "Something went wrong.");
    }
    onClose();
  };

  // Detect click outside to close Delete popup
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        wrapperRef.current &&
        !wrapperRef.current.contains(event.target as Node) &&
        !confirmRef.current?.contains(event.target as Node)
      ) {
        onClose();
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [onClose]); 

  // API Call
  const handleDelete = async () => {
    try {
      if (postType === "reel") {
        await postData("/delete_reel", { reel_id: postId });
      } else {
        await postData("/delete_post", { post_id: postId });
      }

      showSuccessToast(
        "Deleted Successfully", 
        "The post has been removed from your profile."
      );

      setDeleteConfirmation(false);
      onDelete();
      onClose();

    } catch (error: any) {
      console.error("Delete failed:", error);

      if (error?.response?.status === 403 || error?.status === 403) {
        showErrorToast(
          "Action Restricted", 
          "In Demo account, you cannot delete posts."
        );
      } else {
        showErrorToast(
          "Delete Failed", 
          error?.response?.data?.message || "Something went wrong while trying to delete the post."
        );
      }
      
      setDeleteConfirmation(false);
    }
  };

  return (
    <>
      {/* Delete Button */}
      <div className="p-2">
        <div
          className="flex gap-2 cursor-pointer place-items-center"
          onClick={() => setDeleteConfirmation(true)}
        >
          <Image src={Delete} alt="report" className="w-6 h-6" />
          <p className="text-[#FF2525] font-gilroy_semibold text-base">
            Delete
          </p>
        </div>
      </div>

      {/* Copy Link Button */}
      <div className="p-2 border-t border-[var(--border-color)]">
        <div
          className="flex gap-2 cursor-pointer place-items-center"
          onClick={handleCopyLink}
        >
          <LinkIcon className="w-5 h-5 text-[var(--text-primary)]" />
          <p className="text-[var(--text-primary)] font-gilroy_semibold text-base">
            <TextTranslate text="Copy Link" />
          </p>
        </div>
      </div>

      {/* Confirmation for delete */}
      {deleteConfirmation && (
        <div className="fixed inset-0 z-[100] flex items-center justify-center backdrop-blur-sm bg-black/50">
          <div ref={confirmRef} className="bg-[var(--modal-color)] py-4 rounded-2xl shadow-xl w-full max-w-[420px] md:max-w-[550px] text-center border border-[var(--border-color)] mx-4">

            <p className="text-lg text-[var(--text-primary)] font-semibold -mb-1">
              <TextTranslate text="Delete Confirmation" />
            </p>

            <p className="text-[var(--text-secondary)] p-3 pb-4 border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_07%)]">
              Are you sure you want to delete this post?
            </p>

            <div className="flex gap-4 p-3 justify-center -mb-3 mt-1">
              <button
                className="px-12 py-2 border rounded-xl border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] font-medium text-[var(--text-primary)] hover:opacity-80"
                onClick={() => setDeleteConfirmation(false)}
              >
                <TextTranslate text="Cancel" />
              </button>

              <button
                className="px-12 py-2 text-white font-medium rounded-xl bg-gradient-custom hover:opacity-90 min-w-[100px]"
                onClick={handleDelete}
                disabled={loading}
              >
                {loading ? (
                  <ClipLoader color="#FFFFFF" size={15} loading={loading} />
                ) : (
                  <TextTranslate text="Confirm" />
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

export default DeletePost;