import React, { Suspense, useCallback, useMemo } from "react";
import { Link, useNavigate, useParams } from "react-router-dom";
import { TaleDashbaordMainCard } from "@components/TaleDashbaordMainCard";
import { TaleLoadingFallback } from "@components/TaleLoadingFallback";
import { useQuery } from "@tanstack/react-query";
import { useSelector } from "react-redux";
import { lazily } from "react-lazily";
import TaleButton from "@components/TaleButton";
import { surveysService } from "@/api/surveys";
import { formatSurveyApiToUi } from "@/utils/surveyFormatApiToUi";

// Import React Icons
import { FiArrowLeft, FiCheckCircle, FiClock, FiHelpCircle, FiInfo, FiBarChart2, FiCalendar } from "react-icons/fi";
import { BsStarFill, BsQuestionSquare } from "react-icons/bs";
import { MdOutlineTimer } from "react-icons/md";
import {calculateEstimatedTimeMinutes} from "@/utils/surveyEstimatedTime";
import { useTranslation } from "@/hooks/useTranslation";
import { useSurveyViewedPixel } from "@/hooks/useSurveyViewedPixel";

const { NotFound } = lazily(() => import("@components/Errors/NotFound"));

const InfoBox = React.memo(({ points }) => (
  <div className="rounded-full shadow-lg">
    <div className="flex items-center gap-1.5">
      <div className="text-white text-sm font-semibold">{points}</div>
    </div>
  </div>
));

const DetailItem = ({ icon: Icon, label, value, color = "teal" }) => {
  const colorClasses = {
    teal: "bg-teal-100 text-teal-600",
    blue: "bg-[#FE346E60] text-[#FE346E]",
    amber: "bg-amber-100 text-amber-600",
    purple: "bg-purple-100 text-purple-600",
  };

  return (
      <div className="flex items-center gap-2 md:gap-4 p-0 md:p-4 bg-white rounded-xl">
        <div className={`p-2 md:p-3 rounded-lg ${colorClasses[color]}`}>
          <Icon className="w-4 h-4 md:w-6 md:h-6" />
        </div>
        <div className="flex-1">
          <div className="text-sm md:text-lg font-bold text-gray-900">{value}</div>
          <div className="text-xs md:text-sm font-medium text-gray-600">{label}</div>
        </div>
      </div>
  );
};

const SurveyDetail = React.memo(() => {
  const { t } = useTranslation();
  const { surveyId } = useParams();
  const navigate = useNavigate();

  const {
    isPending: loading,
    data: survey,
    error,
  } = useQuery({
    queryKey: ["survey", surveyId],
    queryFn: async () => {
      try {
        const data = await surveysService.getSurvey(surveyId);
        return formatSurveyApiToUi(data);
      } catch (error) {
        throw new Error(error.message || "Failed to load survey");
      }
    },
    retry: false,
  });

  // Only respondents are reported to the company's pixel. This page is also open to the company's
  // own staff and to admins, and their visits are not traffic the company paid to bring in.
  const { user } = useSelector((state) => state.auth);
  const isRespondent = (user?.userType || user?.roles?.[0]) === "NORMAL_USER";
  useSurveyViewedPixel(survey?.company, error ? undefined : survey, isRespondent);

  const handleBackClick = useCallback(() => {
    navigate("/surveys");
  }, [navigate]);

  const loadingItem = useMemo(() => <TaleLoadingFallback className="py-20" />, []);

  const canStart = useMemo(() => !loading && survey && ["IN_PROGRESS", "LIVE"].includes(survey.status || "IN_PROGRESS"), [survey, loading]);

  const estimatedTimeMinutes = useMemo(
      () => calculateEstimatedTimeMinutes(survey),
      [survey]
  );

  const getStatusBadge = (status) => {
    const statusConfig = {
      IN_PROGRESS: { bg: "bg-[#2FB30078]", text: "text-white", label: t("surveyBuilder.detail.statusActive") },
      LIVE: { bg: "bg-blue-100", text: "text-blue-800", label: t("surveyBuilder.detail.statusLive") },
      COMPLETED: { bg: "bg-gray-100", text: "text-gray-800", label: t("surveyBuilder.detail.statusCompleted") },
      DRAFT: { bg: "bg-amber-100", text: "text-amber-800", label: t("surveyBuilder.detail.statusDraft") },
    };

    const config = statusConfig[status] || { bg: "bg-gray-100", text: "text-gray-800", label: status };
    return <span className={`px-3 py-1 rounded-full text-xs font-semibold ${config.bg} ${config.text}`}>{config.label}</span>;
  };

  return (
    <div className="min-h-screen ">
      {/* Main Card */}
      <TaleDashbaordMainCard className="!rounded-2xl !shadow-xl !border-0 overflow-hidden">
        {loading ? loadingItem : null}
        {error && !loading ? (
          <Suspense fallback={loadingItem}>
            <NotFound />
          </Suspense>
        ) : null}

        {!(error || loading) && survey ? (
          <>
            {/* Header Section */}
            <div className="p-0 md:p-8 md:pb-0">
              <div className="flex items-start justify-between mb-4 md:mb-6">
                <div className="flex items-start gap-4">
                  <button
                      onClick={handleBackClick}
                      className="w-9 h-9 rounded-xl border-2 border-gray-800 flex items-center justify-center text-gray-500 hover:bg-gray-50 disabled:opacity-30 disabled:cursor-not-allowed shrink-0"
                  >
                    <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <path d="M5.83333 0.5L0.5 5.83333M0.5 5.83333L5.83333 11.1667M0.5 5.83333H11.1667" stroke="#333333" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>
                  <div>
                    <h1 className="text-xl md:text-3xl font-bold text-gray-900">{survey.title}</h1>
                    <div className="flex items-center gap-3 mt-2">
                      <div className="relative">
                        <img alt={survey.company?.companyName || "Company"} className="w-10 h-10 md:w-14 md:h-14 rounded-full border-2 border-white shadow-lg" src={survey.logo?.url ?? survey.company?.assets?.[0]?.url ?? "/assets/survey/respond/no-image.png"} />
                        <div className="absolute -bottom-1 -right-1 bg-gradient-to-r from-green-500 to-teal-500 text-white p-1 rounded-full">
                          <FiCheckCircle className="w-3 h-3" />
                        </div>
                      </div>
                      <div className="flex items-center gap-2 text-sm text-gray-600">
                        <span className="font-medium">{survey.company?.companyName}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* Hero Image */}
              <div className="relative rounded-2xl overflow-hidden mb-8">
                <div className="absolute top-4 left-4 rtl:left-auto rtl:right-4 z-10">
                  <InfoBox points={getStatusBadge(survey.status)} />
                </div>

                <img alt={survey.title} src={survey.banner?.url ?? "/assets/survey/respond/no-image.png"} className="w-full h-[180px] md:h-[300px] object-cover" />

                {/* Gradient Overlay */}
                <div className="absolute inset-0 bg-gradient-to-r from-black/100 via-black/60 to-transparent" />

                {/* Company Info */}
                <div className="absolute bottom-4 md:left-6 rtl:md:left-auto rtl:md:right-6 flex flex-column items-center gap-2 p-4 pb-0 md:pb-4" style={{flexDirection: 'column'}}>
                  <h1 className="text-lg md:text-3xl font-bold text-white">{t("surveyBuilder.detail.ctaHeadline")}</h1>
                  <div className="bottom-4 left-6 rtl:left-auto rtl:right-6 flex items-center gap-4 w-full">
                    <TaleButton Component={Link} to={canStart ? `/survey/${surveyId}/questions` : "#"} role="normal" variant="filled" disabled={!canStart} className="shadow-md hover:shadow-lg transition-shadow" startIcon={<FiArrowLeft className="w-5 h-5 rotate-180 rtl:rotate-0" />}>
                      {!canStart ? t("surveyBuilder.detail.notAvailable") : t("surveyBuilder.detail.startSurvey")}
                    </TaleButton>
                  </div>
                </div>
              </div>
            </div>

            {/* Content Section */}
            <div className="p-0 md:p-8 md:pt-0">
              {/* Survey Stats */}
              <div className="mb-4">
                {/*<div className="flex items-center gap-3 mb-6">*/}
                {/*  <div className="p-2 rounded-lg bg-blue-50">*/}
                {/*    <BsGraphUp className="w-5 h-5 text-blue-600" />*/}
                {/*  </div>*/}
                {/*  <h2 className="text-base md:text-xl font-bold text-gray-900">Survey Details</h2>*/}
                {/*</div>*/}

                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2 md:gap-3">
                  <DetailItem icon={BsQuestionSquare} label={t("survey_detail.questions_count_label")} value={survey.questionsCount || 0} color="teal" />
                  <DetailItem icon={FiClock} label={t("survey_detail.estimated_time_label")} value={estimatedTimeMinutes ? `${estimatedTimeMinutes} min` : "10-15 min"} color="blue" />
                  <DetailItem icon={BsStarFill} label={t("survey_detail.points_to_earn_label")} value={survey.rewardPoints || "--"} color="amber" />
                  {/*<DetailItem icon={FiUsers} label="Responses" value={survey.responsesNumber || 0} color="purple" />*/}
                </div>
              </div>

              {/* Introduction */}
              <div className="mb-6 md:mb-10">
                {/*<div className="flex items-center gap-3 mb-6">*/}
                {/*  <div className="p-2 rounded-lg bg-teal-50">*/}
                {/*    <MdOutlineDescription className="w-5 h-5 text-teal-600" />*/}
                {/*  </div>*/}
                {/*  <h2 className="text-base md:text-xl font-bold text-gray-900">Introduction</h2>*/}
                {/*</div>*/}

                <div className="bg-[#EFEFEF] rounded-xl p-4">
                  <h2 className="text-base md:text-xl font-bold text-gray-900">{t("survey_detail.about_title")}</h2><br></br>
                  <p className="text-gray-900 leading-relaxed">{survey.description || t("survey_detail.no_description")}</p>
                </div>
              </div>

              {/* Additional Info */}
              {survey.createdAt && (
                <div className="mb-10">
                  <div className="flex items-center gap-3 mb-6">
                    <div className="p-2 rounded-lg bg-purple-50">
                      <FiInfo className="w-5 h-5 text-purple-600" />
                    </div>
                    <h2 className="text-base md:text-xl font-bold text-gray-900">{t("surveyBuilder.detail.additionalInfoTitle")}</h2>
                  </div>

                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div className="bg-gradient-to-br from-gray-50 to-white rounded-xl p-4 border border-gray-200">
                      <div className="flex items-center gap-3 mb-2">
                        <div className="p-2 rounded-lg bg-gray-100">
                          <FiCalendar className="w-4 h-4 text-gray-600" />
                        </div>
                        <div>
                          <div className="text-sm text-gray-600">{t("surveyBuilder.detail.createdLabel")}</div>
                          <div className="font-semibold text-gray-900">{new Date(survey.createdAt).toLocaleDateString()}</div>
                        </div>
                      </div>
                    </div>

                    <div className="bg-gradient-to-br from-gray-50 to-white rounded-xl p-4 border border-gray-200">
                      <div className="flex items-center gap-3 mb-2">
                        <div className="p-2 rounded-lg bg-gray-100">
                          <MdOutlineTimer className="w-4 h-4 text-gray-600" />
                        </div>
                        <div>
                          <div className="text-sm text-gray-600">{t("surveyBuilder.detail.statusLabel")}</div>
                          <div className="font-semibold text-gray-900">{survey.status === "IN_PROGRESS" ? t("surveyBuilder.detail.statusActiveShort") : survey.status === "LIVE" ? t("surveyBuilder.detail.statusLiveShort") : survey.status === "COMPLETED" ? t("surveyBuilder.detail.statusCompletedShort") : survey.status || t("surveyBuilder.detail.statusActiveShort")}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              )}

              {/* Terms & Conditions */}
              {survey.termsAndConditions && (
                <div className="mb-10">
                  <div className="flex items-center gap-3 mb-6">
                    <div className="p-2 rounded-lg bg-amber-50">
                      <FiHelpCircle className="w-5 h-5 text-amber-600" />
                    </div>
                    <h2 className="text-base md:text-xl font-bold text-gray-900">{t("survey_detail.terms_title")}</h2>
                  </div>

                  <div className="bg-gradient-to-br from-amber-50/50 to-amber-100/50 rounded-xl p-6 border border-amber-200">
                    <div className="bg-white rounded-lg p-4">
                      <p className="text-sm text-gray-600 leading-relaxed">{survey.termsAndConditions}</p>
                    </div>
                  </div>
                </div>
              )}

              {/* Survey Tips */}
              <div className="">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="bg-[#EFEFEF] rounded-xl p-4">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="p-2 rounded-lg bg-gray-200">
                        <FiClock className="w-5 h-5 text-gray-900" />
                      </div>
                      <h3 className="font-semibold text-gray-900">{t("surveyBuilder.detail.timeCommitmentTitle")}</h3>
                    </div>
                    <ul className="space-y-2 text-sm text-gray-600">
                      <li>• {t("surveyBuilder.detail.tipOwnPace")}</li>
                      <li>• {t("surveyBuilder.detail.tipSaveProgress")}</li>
                      <li>• {t("surveyBuilder.detail.tipMinutesEstimated", { time: survey.estimatedTime || "10-15" })}</li>
                    </ul>
                  </div>

                  <div className="bg-[#EFEFEF]  rounded-xl p-4">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="p-2 rounded-lg bg-gray-200">
                        <FiBarChart2 className="w-5 h-5 text-gray-900" />
                      </div>
                      <h3 className="font-semibold text-gray-900">{t("surveyBuilder.detail.yourImpactTitle")}</h3>
                    </div>
                    <ul className="space-y-2 text-sm text-gray-600">
                      <li>• {t("surveyBuilder.detail.tipImprove")}</li>
                      <li>• {t("surveyBuilder.detail.tipResearch")}</li>
                      <li>• {t("surveyBuilder.detail.tipEarnPoints", { points: survey.rewardPoints || '--' })}</li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </>
        ) : null}
      </TaleDashbaordMainCard>
    </div>
  );
});

export default SurveyDetail;
