"use client";

import React, { useState, useEffect, useRef } from "react";
import { X, Send, Plus } from "react-feather";
import { useToast } from "@/components/ui/ToastContext";
import AutoDmHeader from "@/components/AutoDmHeader";

import apiClient from "@/lib/apiClient";
import { useAppDispatch, useAppSelector } from "@/hooks/useAppDispatch";
import { disconnectInstagram, resetCampaignData } from "@/features/autoDm/autoDmSlice";
import { editAutoDmConfig, EditAutoDmConfigRequest, fetchPostDetails } from "@/features/autoDm/autoDmThunk";
import { useRouter } from "next/navigation";
import { logger } from "@/lib/logger";
import GlobalLoadingOverlay from "@/components/ui/GlobalLoadingOverlay";

// Import Bootstrap’s Modal class
// Modal will be imported dynamically on client side

interface ReplyMessage {
  id: string;
  text: string;
}

interface Keyword {
  id: string;
  text: string;
}

// interface ApiData {
//     replyMessages?: ReplyMessage[];
//     keywords?: Keyword[];
// }

export default function AutoDmStep4() {
  const showToast = useToast();
  const router = useRouter();
  const dispatch = useAppDispatch();

  // State for disconnect confirmation modal
  const [showDisconnectConfirmation, setShowDisconnectConfirmation] = useState(false);
  const [isDisconnecting, setIsDisconnecting] = useState(false);
  const [isNavigating, setIsNavigating] = useState(false);

  // State for edit mode data
  const [isLoadingEditData, setIsLoadingEditData] = useState(false);

  // Show disconnect confirmation modal
  const handleDisconnectClick = () => {
    setShowDisconnectConfirmation(true);
  };

  // Handle actual Instagram disconnection
  const handleDisconnectInstagram = async () => {
    try {
      setIsDisconnecting(true);
      const response = await apiClient.get("/ig/disconnect");

      if (response.data.success) {
        // Clear all Instagram data from Redux and localStorage
        dispatch(disconnectInstagram());
        showToast("Your Instagram account has been disconnected.");
        setShowDisconnectConfirmation(false);
        // Redirect to connect Instagram page
        router.push("/auto-dm/step-1");
      } else {
        showToast("Unable to disconnect right now. Please try again.");
      }
    } catch (error) {
      logger.error("Failed to disconnect Instagram:", error);
      showToast("Unable to disconnect right now. Please try again.");
    } finally {
      setIsDisconnecting(true);
    }
  };

  // Close disconnect confirmation modal
  const closeDisconnectConfirmation = () => {
    setShowDisconnectConfirmation(false);
  };

  const {
    connected,
    username,  // ← from fetchConnectionStatus
    selectedPost,
    previewsByUrl,
    // deepLinks, // No longer needed since deeplink data comes with previews
    postToUpdate,
    postDetails
  } = useAppSelector((state) => state.autoDm);

  // Check if there are any deeplinks available
  const hasDeeplinks = Object.values(previewsByUrl).some(preview =>
    preview?.deeplinkData?.isCommissionable
  );

  // Load additional data when in edit mode
  useEffect(() => {
    if (postToUpdate && !postDetails) {
      setIsLoadingEditData(true);
      dispatch(fetchPostDetails(postToUpdate))
        .unwrap()
        .then(() => {
          setIsLoadingEditData(false);
        })
        .catch((error) => {
          logger.error("Failed to load campaign data:", error);
          showToast("Failed to load campaign data. Please try again.");
          setIsLoadingEditData(false);
        });
    }
  }, [postToUpdate, postDetails, dispatch, showToast]);

  // Populate state with data from postDetails when available
  useEffect(() => {
    if (postDetails) {
      // Update reply messages from postDetails
      if (postDetails.replyTemplate && postDetails.replyTemplate.length > 0) {
        const replyTemplates = postDetails.replyTemplate.map((text, index) => ({
          id: `edit-${index}`,
          text: text
        }));
        setReplyMessages(replyTemplates);
      }

      // Update keywords from postDetails
      if (postDetails.keywords && postDetails.keywords.length > 0) {
        const keywordsData = postDetails.keywords.map((text, index) => ({
          id: `edit-${index}`,
          text: text
        }));
        setKeywords(keywordsData);
      }

      // Update allowAnyKeyword toggle
      setIsToggleEnabled(postDetails.allowAnyKeyword || false);
    }
  }, [postDetails]);

  // Fallback data
  const fallbackReplies: ReplyMessage[] = [
    { id: "1", text: "Sent to your DM!" },
    { id: "2", text: "Links shared over DM!" },
    { id: "3", text: "Check your DM for the links" },
  ];

  const fallbackKeywords: Keyword[] = [
    { id: "1", text: "Link" },
    { id: "2", text: "Send" },
    { id: "3", text: "DM" },
  ];

  // State for managing replies
  const [replyMessages, setReplyMessages] =
    useState<ReplyMessage[]>(fallbackReplies);

  // State for managing keywords
  const [keywords, setKeywords] = useState<Keyword[]>(fallbackKeywords);

  // Loading state
  // const [isLoading, setIsLoading] = useState<boolean>(true);

  // State for form inputs
  const [customReply, setCustomReply] = useState("");
  const [customKeyword, setCustomKeyword] = useState("");

  // State for toggles
  const [showCustomReply, setShowCustomReply] = useState(false);
  const [showCustomKeyword, setShowCustomKeyword] = useState(false);
  const [isToggleEnabled, setIsToggleEnabled] = useState(false);

  //  Priority guards on mount
  useEffect(() => {
    if (!connected) {
      dispatch(resetCampaignData());
      router.replace("/auto-dm");
      return;
    }
    if (!selectedPost) {
      router.replace("/auto-dm/step-1");
      return;
    }
    const previewUrls = Object.keys(previewsByUrl);
    if (previewUrls.length === 0) {
      router.replace("/auto-dm/step-2");
      return;
    }
    // Check if any preview has deeplinkData instead of checking separate deepLinks
    const hasDeeplinkData = previewUrls.some((url) => {
      const preview = previewsByUrl[url];
      return preview && preview.deeplinkData;
    });
    if (!hasDeeplinkData) {
      router.replace("/auto-dm/step-2");
      return;
    }
  }, [connected, selectedPost, previewsByUrl, dispatch, router]);

  // API call to fetch initial data
  useEffect(() => {
    // const fetchInitialData = async () => {
    //     try {
    //         // setIsLoading(true);
    //         // Replace with your actual API endpoint
    //         const response = await apiClient.get('/auto-dm/defaults');
    //         const defaultSettings: ApiData = response.data;
    //         if (defaultSettings.replyMessages && defaultSettings.replyMessages.length > 0) {
    //             setReplyMessages(defaultSettings.replyMessages);
    //         }
    //         if (defaultSettings.keywords && defaultSettings.keywords.length > 0) {
    //             setKeywords(defaultSettings.keywords);
    //         }
    //         // if (response.ok) {
    //         //     const data: ApiData = await response.json();
    //         //     // Use API data if available, otherwise use fallback
    //         // if (data.replyMessages && data.replyMessages.length > 0) {
    //         //     setReplyMessages(data.replyMessages);
    //         // }
    //         // if (data.keywords && data.keywords.length > 0) {
    //         //     setKeywords(data.keywords);
    //         // }
    //         // } else {
    //         //
    //         // }
    //     } catch (error) {
    //
    //         // Fallback values are already set in useState
    //     } finally {
    //         // setIsLoading(false);
    //     }
    // };
    // fetchInitialData();
  }, []);

  // Functions for managing replies
  const addCustomReply = (e: React.FormEvent) => {
    e.preventDefault();
    if (customReply.trim()) {
      const newReply: ReplyMessage = {
        id: Date.now().toString(),
        text: customReply.trim(),
      };
      setReplyMessages([...replyMessages, newReply]);
      setCustomReply("");
      setShowCustomReply(false);
    }
  };

  const removeReply = (id: string) => {
    setReplyMessages(replyMessages.filter((reply) => reply.id !== id));
  };

  // Functions for managing keywords
  const addCustomKeyword = (e: React.FormEvent) => {
    e.preventDefault();
    if (customKeyword.trim()) {
      const newKeyword: Keyword = {
        id: Date.now().toString(),
        text: customKeyword.trim(),
      };
      setKeywords([...keywords, newKeyword]);
      setCustomKeyword("");
      setShowCustomKeyword(false);
    }
  };

  const removeKeyword = (id: string) => {
    const newKeywords = keywords.filter((keyword) => keyword.id !== id);
    setKeywords(newKeywords);
    // If all keywords are removed, enable the toggle
    if (!newKeywords.length) setIsToggleEnabled(true);
  };

  // Toggle functions
  const toggleCustomReply = () => {
    setShowCustomReply(!showCustomReply);
    if (showCustomReply) {
      setCustomReply("");
    }
  };

  const toggleCustomKeyword = () => {
    setShowCustomKeyword(!showCustomKeyword);
    if (showCustomKeyword) {
      setCustomKeyword("");
    }
  };
  const modalRef = useRef<HTMLDivElement>(null);

  const handlePublish = async () => {
    if (!selectedPost) return;
    setIsNavigating(true);
    try {
      // Get products data from Redux store

      const previewUrls = Object.keys(previewsByUrl);

      const products = previewUrls.map((url) => {
        const preview = previewsByUrl[url];
        const deepLink = preview?.deeplinkData;

        // Extract commission amount directly from the number
        const commissionAmount = deepLink?.commissionAmount || 0;

        return {
          url: url,
          domain: preview.domain,
          productName: preview.productName,
          short_url: deepLink?.short_url,

          imageUrl: preview.images.main || "",
          deeplinkUrl: deepLink?.deeplinkUrl || "",
          commissionRate: deepLink?.commissionRate || 0,
          commissionAmount: commissionAmount,
          fallback_url: deepLink?.fallback_url || "",
        };
      });

      const payload = {
        igPostId: selectedPost.id,
        media_url: selectedPost.media_url,
        caption: selectedPost.caption || products[0]?.productName || "",
        products: products,
        keywords: isToggleEnabled ? ["*"] : keywords.map((k) => k.text),
        replyTemplate: replyMessages.map((r) => r.text),
        allowAnyKeyword: isToggleEnabled,
        isActive: true,
      };
      const res = await apiClient.post("/product/save", payload);
      if (res.data.success && modalRef.current) {
        // 1) Create BS Modal instance dynamically
        const Modal = (await import("bootstrap/js/dist/modal")).default;
        const bsModal = new Modal(modalRef.current);
        // 2) Listen for any hide → then redirect
        const onHidden = () => {
          // No artificial delay - API call already completed
          router.push("/auto-dm/history");
          modalRef.current?.removeEventListener("hidden.bs.modal", onHidden);
        };
        modalRef.current.addEventListener("hidden.bs.modal", onHidden);
        // 3) Show it
        bsModal.show();
      } else {
        showToast("Something went wrong");
      }
    } catch (err) {
      logger.error("Failed to publish campaign:", err);
      showToast("Something went wrong");
    } finally {
      setIsNavigating(false);
    }
  };
  const handleUpdate = async () => {
    if (!selectedPost || !postToUpdate) return;
    setIsNavigating(true);
    try {
      // Current products visible in steps 2 & 3
      const previewUrls = Object.keys(previewsByUrl);
      const currentUrlSet = new Set(previewUrls);
      const originalProducts = postDetails?.products || [];

      // 1) Active products (still present)
      const activeProducts = previewUrls.map((url) => {
        const preview = previewsByUrl[url];
        const deepLink = preview?.deeplinkData;

        // Check if this URL existed in original products (coming from history)
        const originalProduct = originalProducts.find(
          (product) => product.url === url
        );

        const commissionAmount = deepLink?.commissionAmount || 0;

        return {
          url: url,
          domain: preview.domain,
          productName: preview.productName,
          imageUrl: preview.images.main || "",
          deeplinkUrl: deepLink?.deeplinkUrl || "",
          short_url: deepLink?.short_url || "",
          commissionRate: deepLink?.commissionRate || 0,
          commissionAmount: commissionAmount,
          // For existing links we preserve affiliateLinkId,
          // for new links this will be null (or empty) as required
          affiliateLinkId:
            deepLink?.affiliateLinkId ?? originalProduct?.affiliateLinkId ?? null,
          // Fallback URL from deeplink or original product
          fallback_url:
            deepLink?.fallback_url ?? originalProduct?.fallback_url ?? null,
          isDeleted: false,
        };
      });

      // 2) Removed products (were in original, not in current)
      const removedProducts =
        originalProducts
          .filter((product) => !currentUrlSet.has(product.url))
          .map((product) => ({
            url: product.url,
            domain: product.domain,
            productName: product.productName,
            imageUrl: product.imageUrl,
            deeplinkUrl: product.deeplinkUrl,
            short_url: product.short_url,
            commissionRate: product.commissionRate,
            commissionAmount: product.commissionAmount,
            affiliateLinkId: product.affiliateLinkId ?? null,
            fallback_url: product.fallback_url ?? null,
            isDeleted: true,
          })) || [];

      // 3) Final list: active (existing + new) + removed-with-flag
      const products = [...activeProducts, ...removedProducts];

      const payload: EditAutoDmConfigRequest = {
        igPostId: postToUpdate, // Use the ig_post_id from postToUpdate
        products: products,
        keywords: isToggleEnabled
          ? ["buy", "purchase", "shop", "interested", "price"]
          : keywords.map((k) => k.text),
        replyMessage: replyMessages.map((r) => r.text).join(" "), // Join reply templates into a single message
        replyTemplate: replyMessages.map((r) => r.text),
        allowAnyKeyword: isToggleEnabled,
        isActive: true
      };

      // Use the edit API thunk
      const result = await dispatch(editAutoDmConfig(payload)).unwrap();

      if (result.success && modalRef.current) {
        // 1) Create BS Modal instance dynamically
        const Modal = (await import("bootstrap/js/dist/modal")).default;
        const bsModal = new Modal(modalRef.current);
        // 2) Listen for any hide → then redirect
        const onHidden = () => {
          // No artificial delay - API call already completed
          router.push("/auto-dm/history");
          modalRef.current?.removeEventListener("hidden.bs.modal", onHidden);
        };
        modalRef.current.addEventListener("hidden.bs.modal", onHidden);
        // 3) Show it
        bsModal.show();
      } else {
        showToast("Something went wrong");
      }
    } catch (err) {
      logger.error("Failed to update campaign:", err);
      showToast("Something went wrong");
    } finally {
      setIsNavigating(false);
    }
  };

  // Show loading state when fetching edit data
  if (isLoadingEditData) {
    return (
      <div className="text-center py-20">
        <div className="spinner-border" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
        <p className="mt-3">Loading campaign data...</p>
      </div>
    );
  }

  return (<>
    <div className="pcoded-main-container bg-light webContent">
      <GlobalLoadingOverlay show={isLoadingEditData || isNavigating} />
      <div className="pcoded-content">
        <AutoDmHeader
          currentStep={4}
          totalSteps={4}
          username={username || ""}
          connected={connected}
          onDisconnect={handleDisconnectClick}
          onNext={postToUpdate ? handleUpdate : handlePublish}
          nextText={postToUpdate ? "Update Campaign" : "Publish"}
          nextDisabled={!hasDeeplinks}
          isLoading={isLoadingEditData || isNavigating}
        />

        <div className="row my-3">
          <div className="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-12 mb-3">
            <div className="row mb-3">
              <div className="col-xxl-7 col-xl-7 col-lg-7 col-md-12 col-sm-12 col-12 mb-lg-0 mb-3">
                <div className="card performance-card m-0">
                  <div className="card-body platform-cards">
                    <p className="mb-3">
                      Configure your keywords and auto-reply messages.
                    </p>
                    <h3 className="smallHeading mb-4 mt-4">
                      Auto-replies to comments
                    </h3>

                    <form role="form" className="mb-3">
                      <div className="row">
                        {/* Reply Messages Section */}
                        <div className="col-12 mb-3">
                          <div className="d-flex align-items-center flex-wrap gap-3 reply">
                            {replyMessages.map((reply) => (
                              <div
                                key={reply.id}
                                className="reply-card position-relative card m-0"
                              >
                                <a className="mb-0 reply-btn">{reply.text}</a>
                                {replyMessages.length > 1 && (
                                  <X
                                    className="x-btn"
                                    onClick={() => removeReply(reply.id)}
                                    style={{ cursor: "pointer" }}
                                  />
                                )}
                              </div>
                            ))}
                          </div>
                        </div>

                        {/* Custom Reply Form */}
                        <div
                          className="col-12 mb-3 customReply"
                          style={{
                            display: showCustomReply ? "block" : "none",
                          }}
                        >
                          <div className="card mb-0">
                            <div className="card-body d-flex flex-column gap-2">
                              <input
                                type="text"
                                placeholder="Add custom reply"
                                className="form-control"
                                value={customReply}
                                onChange={(e) =>
                                  setCustomReply(e.target.value)
                                }
                                required
                              />
                              <button
                                type="button"
                                className="btn-first but-w small-btn"
                                onClick={addCustomReply}
                              >
                                <Send className="ml-0" /> Add
                              </button>
                            </div>
                          </div>
                        </div>

                        {/* Add Custom Reply Button */}
                        <div className="col-12 mb-3">
                          <button
                            type="button"
                            className="button btn-first btn-first-pink small-btn"
                            onClick={toggleCustomReply}
                          >
                            <Plus className="ml-0" /> Add custom reply
                          </button>
                        </div>

                        {/* Keywords Section */}
                        <div className="col-12 mb-3 keywords-section">
                          <div className="row">
                            <div className="col-12 mb-3">
                              <h3 className="smallHeading mb-2 mt-4">
                                Keywords
                              </h3>
                              <p className="mb-3">
                                {isToggleEnabled
                                  ? "All comments will trigger Auto-DM when enabled"
                                  : "Select keywords to trigger Auto-DM replies on this post"}
                              </p>
                            </div>

                            {/* Only show keywords when toggle is disabled */}
                            {!isToggleEnabled && (
                              <>
                                <div className="col-12 mb-3">
                                  <div className="d-flex align-items-center flex-wrap gap-3 keywords">
                                    {keywords.map((keyword) => (
                                      <div
                                        key={keyword.id}
                                        className="affiliate-link position-relative card m-0"
                                      >
                                        <a className="mb-0 affiliate-btn">
                                          {keyword.text}
                                        </a>
                                        <X
                                          className="x-btn"
                                          onClick={() =>
                                            removeKeyword(keyword.id)
                                          }
                                          style={{ cursor: "pointer" }}
                                        />
                                      </div>
                                    ))}
                                  </div>
                                </div>

                                {/* Custom Keyword Form */}
                                <div
                                  className="col-12 mb-3 customKeyword"
                                  style={{
                                    display: showCustomKeyword
                                      ? "block"
                                      : "none",
                                  }}
                                >
                                  <div className="card mb-0">
                                    <div className="card-body d-flex flex-column gap-2">
                                      <input
                                        type="text"
                                        placeholder="Add custom keyword"
                                        className="form-control"
                                        value={customKeyword}
                                        onChange={(e) =>
                                          setCustomKeyword(e.target.value)
                                        }
                                        required
                                      />
                                      <button
                                        type="button"
                                        className="btn-first but-w small-btn"
                                        onClick={addCustomKeyword}
                                      >
                                        <Send className="ml-0" /> Add
                                      </button>
                                    </div>
                                  </div>
                                </div>

                                {/* Add Custom Keyword Button */}
                                <div className="col-12 mb-3">
                                  <button
                                    type="button"
                                    className="button btn-first btn-first-pink small-btn"
                                    onClick={toggleCustomKeyword}
                                  >
                                    <Plus className="ml-0" /> Add custom
                                    keyword
                                  </button>
                                </div>
                              </>
                            )}

                            {/* Toggle Switch */}
                            <div className="col-12 mb-3">
                              <div className="d-flex align-items-center flex-wrap gap-2">
                                <label className="switch">
                                  <input
                                    type="checkbox"
                                    role="switch"
                                    checked={isToggleEnabled}
                                    onChange={(e) =>
                                      setIsToggleEnabled(e.target.checked)
                                    }
                                  />
                                  <span className="slider" />
                                </label>
                                <span className="mt-0 mb-0">
                                  Let any word trigger Auto-DM
                                  {/* {isToggleEnabled
                                                                        ? "Toggle is enabled - Any word will trigger Auto-DM"
                                                                        : "Let any word trigger Auto-DM"
                                                                    } */}
                                </span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </form>
                  </div>
                </div>

                {/* Post Preview Section */}
              </div>
              {selectedPost && (
                <div className="col-xxl-5 col-xl-5 col-lg-5 col-md-12 col-sm-12 col-12 mb-lg-0 mb-3">
                  <div className="card performance-card m-0">
                    <div className="card-body">
                      <h3 className="smallHeading mb-3 mt-1">Post Preview</h3>

                      {selectedPost.media_type === "VIDEO" ? (
                        <div className="video-wrapper">
                          <video
                            controls
                            disablePictureInPicture
                            controlsList="nodownload nofullscreen noremoteplayback"
                            src={selectedPost.media_url}
                            autoPlay
                            loop
                            muted
                            className="w-100"
                          />
                        </div>
                      ) : (
                        <div className="video-wrapper">
                          <img
                            src={selectedPost.media_url}
                            alt={selectedPost.caption}
                            //   width={300}
                            //   height={300}
                            className="img-fluid m-0"
                          />
                        </div>
                      )}
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
    {/* Success Modal */}
    <section
      ref={modalRef}
      className="modal fade my-modal"
      id="publishModal"
      aria-hidden="true"
    >
      <div className="modal-dialog modal-dialog-centered">
        <div className="modal-content">
          <div className="modal-body text-center p-3">
            <div className="modal-name mb-0 d-flex justify-content-end">
              <button
                type="button"
                className="btn-close"
                data-bs-dismiss="modal"
                aria-label="Close"
              >
                ×
              </button>
            </div>
            <img
              src="/img/icons/check.svg"
              alt="check Image"
              loading="lazy"
              className="checkModal mb-3"
            />
            <h5 className="congratulations mb-3">Congratulations!</h5>
            <p className="px-2">
              Your shoppable links have been added to your Instagram post.
            </p>
          </div>
        </div>
      </div>
    </section>

    {/* Disconnect Instagram Confirmation Modal */}
    {showDisconnectConfirmation && (
      <>
        {/* Backdrop */}
        <div
          className="modal-backdrop fade show"
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            width: "100vw",
            height: "100vh",
            backgroundColor: "rgba(0, 0, 0, 0.5)",
            zIndex: 1040,
            cursor: isDisconnecting ? "not-allowed" : "pointer",
          }}
          onClick={() => {
            if (!isDisconnecting) closeDisconnectConfirmation();
          }}
          title="Click outside to close"
        />

        {/* Modal */}
        <section
          className="modal fade my-modal show d-block"
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            width: "100vw",
            height: "100vh",
            zIndex: 1050,
          }}
          aria-hidden="false"
          onClick={() => {
            if (!isDisconnecting) closeDisconnectConfirmation();
          }}
        >
          <div
            className="modal-dialog modal-dialog-centered"
            onClick={(e) => e.stopPropagation()}
          >
            <div
              className="modal-content"
              onClick={(e) => e.stopPropagation()}
            >
              <div className="modal-body text-center p-3">
                <div className="modal-name mb-0 d-flex justify-content-end">
                  <button
                    type="button"
                    className="btn-close"
                    onClick={closeDisconnectConfirmation}
                    aria-label="Close"
                    disabled={isDisconnecting}
                  >
                    <X size={20} />
                  </button>
                </div>

                <h4 className="mb-3">Disconnect Instagram?</h4>
                <p className="px-2 mb-4">
                  This will stop Auto-DM functionality until you reconnect.
                </p>

                <div className="d-flex gap-2 justify-content-center">
                  <button
                    type="button"
                    className="btn btn-secondary"
                    onClick={closeDisconnectConfirmation}
                    disabled={isDisconnecting}
                  >
                    Cancel
                  </button>
                  <button
                    type="button"
                    className="btn btn-danger"
                    onClick={handleDisconnectInstagram}
                    disabled={isDisconnecting}
                  >
                    {isDisconnecting ? "Disconnecting..." : "Disconnect"}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </section>
      </>
    )}
  </>
  );
}
