"use client";
import React, { useState } from "react";
import Image from "next/image";
import Report from "../../../../public/assets/Report.png";
import useApiPost from "@/app/hooks/postData";
import { useAppDispatch } from "../../../app/hooks/hooks";
import { hideModal, showModal } from "../../store/Slice/modalSlice";
import { setReelId } from "../../store/Slice/ReelIdSlice";
import { ClipLoader } from "react-spinners";
import TextTranslate from "@/app/utils/TextTranslate";
import { IoChevronForward, IoCloseOutline } from "react-icons/io5";
import { LinkIcon } from "lucide-react";
import { showSuccessToast } from "@/app/components/Toast/SuccessToast";
import { showErrorToast } from "@/app/components/Toast/ErrorToast";

function ReportPost({
  postId,
  postType,
  userId, // ✅ add this
  onClose,
  username, // ✅ add username prop
}: {
  postId: string;
  postType: string;
  userId: number; // ✅ add this
  username?: string; // ✅ add optional username
  onClose: () => void;
}) {
  const [report, setReport] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState(false);

  const dispatch = useAppDispatch();
  const { data, postData, loading: apiLoading } = useApiPost();

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

  const handleReport = async () => {
    setIsLoading(true);
    try {
      setReport(true);
      await postData("/get_report_text", { type: postType }).catch((error) => {
        console.error("Error fetching report text:", error);
      });
    } catch (error) {
    } finally {
      setIsLoading(false);
    }
  };

  const Report_Text = data?.all_report_text || [];

  const handleSelectReport = async (reportId: string) => {
    try {
     await postData(
  postType === "image" ? "/post_add_report" : "/reel_add_report",
  {
    ...(postType === "image"
      ? { post_id: postId }
      : { reel_id: postId }),
    reported_user_id: userId, // ✅ ADD THIS
    report_text_id: reportId,
  }
);

      // Store the reported user's info in ReelId state for the success modal
      dispatch(setReelId({
        id: postId,
        user_id: String(userId),
        username: username || "user",
      }));

      setReport(false);

      dispatch(showModal("PostReportSuccess"));

      setTimeout(() => {
        dispatch(hideModal("ViewOtherUsersStory"));
        onClose();
      }, 100);

    } catch (error) {
      console.error("Report failed", error);
    }
  };

  const closeDialog = () => {
    setReport(false);
    onClose();
  };

  return (
    <>
      {/* Report Button */}
      <div className="p-2">
        <div className="flex gap-3 cursor-pointer items-center group" onClick={handleReport}>
          <Image src={Report} alt="report" className="w-5 h-5 object-contain" />
          <p className="text-[#FF2525] font-gilroy_semibold text-base group-hover:opacity-80 transition-opacity">
            <TextTranslate text="Report" />
          </p>
        </div>
      </div>

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

      {/* Report Selection List */}
      {report && (
        <div className="fixed inset-0 flex items-center justify-center bg-black/70 backdrop-blur-sm z-[150] p-4">
          <div className="bg-[var(--modal-color)] rounded-[10px] shadow-3xl w-full max-w-[420px] md:max-w-[550px] overflow-hidden animate-in fade-in zoom-in duration-200 border border-[var(--border-color)]">
            
            {/* Header */}
            <div className="relative border-b border-[var(--border-colordark)] dark:border-[color-mix(in_srgb,var(--border-color),white_10%)] h-[54px] flex items-center justify-center">
              <button 
                onClick={closeDialog}
                className="absolute left-4 text-[var(--text-primary)] hover:opacity-70"
              >
                <IoCloseOutline size={32} strokeWidth={1} />
              </button>
              
              <h2 className="text-[var(--text-primary)] font-gilroy_semibold text-[17px] mt-1">
                <TextTranslate text="Report" />
              </h2>
            </div>

            {/* Sub-header text */}
            <div className="px-4 sm:px-6 pt-4 pb-2 border-b border-[var(--border-color)]">
              <h3 className="text-[var(--text-primary)] font-medium text-[16px]">
                <TextTranslate text="Why are you reporting this post?" />
              </h3>
            </div>

            {/* List Area */}
            <div className="max-h-[400px] overflow-y-auto custom-scrollbar">
              {isLoading || apiLoading ? (
                <div className="flex justify-center items-center py-10">
                  <ClipLoader color="var(--text-primary)" size={25} />
                </div>
              ) : (
                <div className="flex flex-col">
                  {Report_Text.map((reportItem: any) => (
                    <button
                      key={reportItem.id}
                      className="w-full flex items-center justify-between px-4 sm:px-6 border-b border-[var(--border-color)] py-4 hover:bg-[color-mix(in_srgb,var(--text-primary),transparent_95%)] text-left transition-colors"
                      onClick={() => handleSelectReport(reportItem.id)}
                    >
                      <span className="text-[var(--text-primary)] text-[15px] font-normal">
                        {reportItem.text}
                      </span>
                      <IoChevronForward className="text-[var(--text-secondary)]" size={20} />
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}
    </>
  );
}

export default ReportPost;