import { useNavigate, useParams, useLocation } from "react-router-dom";
import { useState, useCallback, useMemo, useRef, useLayoutEffect } from "react";
import { useMagicBag } from "../context/MagicBagContext";
import { RewardModal } from "./RewardModal";
import { getTopicConfig } from "../../config/topicConfig";
import { usePageTracking } from "../../hooks/usePageTracking";
import { AppHeader } from "./AppHeader";
import { useInbox } from "../context/InboxContext";
import { AppBackground } from "./shared/AppBackground";
import { backgroundImages } from "../../config/backgroundConfig";
import { BottomNav } from "./BottomNav";

export function SubmitChallengePage() {
  const navigate = useNavigate();
  const location = useLocation();
  const { topicId = "1" } = useParams<{ topicId: string }>();
  const topicConfig = getTopicConfig(topicId);

  usePageTracking(`ثبت ماموریت ${topicConfig.title}`);
  const { addNewItem } = useMagicBag();
  const { refreshInbox } = useInbox();
  const [showRewardModal, setShowRewardModal] = useState(false);
  const headerWrapperRef = useRef<HTMLDivElement>(null);
  const [headerHeight, setHeaderHeight] = useState(172);

  // دریافت doingMission از location state
  const doingMission = (location.state as any)?.doingMission;
  const selectedMissionTitleFromState = (location.state as any)?.selectedMissionTitle;

  const selectedChallengeTitle = useMemo(() => {
    return (
      selectedMissionTitleFromState ||
      localStorage.getItem("current_mission_title") ||
      doingMission?.title ||
      "چالش انتخاب‌شده"
    );
  }, [selectedMissionTitleFromState, doingMission]);

  const handleBack = useCallback(() => {
    navigate(-1);
  }, [navigate]);

  const handleSubmit = (data: any) => {
    console.log("Submitting challenge:", data);
    // Show reward modal
    setShowRewardModal(true);
    // Add badge to magic bag
    addNewItem();
    // Refresh inbox to load new messages
    refreshInbox();
  };

  const handleCloseModal = () => {
    setShowRewardModal(false);
    // Navigate to feed after closing modal
    navigate(`/feed/${topicId}`);
  };

  // Dynamically render the form component from config
  const FormComponent = topicConfig.formComponent;

  useLayoutEffect(() => {
    const measureHeader = () => {
      const measuredHeight = headerWrapperRef.current?.getBoundingClientRect().height ?? 0;
      if (measuredHeight > 0) {
        setHeaderHeight(Math.ceil(measuredHeight));
      }
    };

    measureHeader();

    const observer = new ResizeObserver(() => {
      measureHeader();
    });

    if (headerWrapperRef.current) {
      observer.observe(headerWrapperRef.current);
    }

    window.addEventListener("resize", measureHeader);

    return () => {
      observer.disconnect();
      window.removeEventListener("resize", measureHeader);
    };
  }, []);

  return (
    <div className="min-h-screen w-full relative overflow-hidden">
      <AppBackground position="fixed" zIndex={0} imageUrl={backgroundImages.submitChallenge} />

      {/* Content */}
      <div className="relative z-10 max-w-md mx-auto">
        <div ref={headerWrapperRef}>
          {/* Header */}
          <AppHeader showBack onBack={handleBack} />
          <div className="px-4 pb-2 text-center">
            <h2
              className="mt-1 text-[20px] font-extrabold leading-8"
              style={{
                display: "inline-block",
                background:
                  "linear-gradient(90deg, #F6D8A5 0%, #F3A599 20%, #DB7EB2 48%, #AA6798 72%, #CB75AB 100%)",
                WebkitBackgroundClip: "text",
                backgroundClip: "text",
                WebkitTextFillColor: "transparent",
                color: "transparent",
                textShadow: "0 2px 10px rgba(255, 119, 202, 0.4)",
              }}
            >
              {`ثبت چالش ${selectedChallengeTitle}`}
            </h2>
          </div>
        </div>

        {/* Main Content - Scrollable */}
        <div
          className="fixed top-0 left-0 right-0 bottom-0 max-w-md mx-auto overflow-hidden"
          style={{ paddingTop: `${headerHeight}px`, zIndex: 1 }}
        >
          <div
            className="h-full overflow-y-auto relative px-[24px] pt-[2px] pb-[132px]"
            style={{
              scrollbarWidth: "none",
              msOverflowStyle: "none",
              maskImage: "linear-gradient(to bottom, transparent 0%, black 4px)",
              WebkitMaskImage: "linear-gradient(to bottom, transparent 0%, black 4px)",
            }}
          >
            {/* Dynamic Form Component */}
            <FormComponent
              topicId={topicId}
              topicTitle={topicConfig.title}
              onSubmit={handleSubmit}
              doingMission={doingMission}
            />
          </div>

        </div>
      </div>

      <style>{`
        .h-full.overflow-y-auto::-webkit-scrollbar { display: none; }
      `}</style>

      <BottomNav />

      {/* Reward Modal */}
      <RewardModal
        isOpen={showRewardModal}
        onClose={handleCloseModal}
        topicTitle={topicConfig.title}
      />
    </div>
  );
}
