import React, {useCallback, useState} from "react";
import "@assets/style/global.css";
import { Link, useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { TaleText } from "@components/TaleText";
import SurveyListItem from "@components/NormalUserSurveyItem";
import { useQuery } from "@tanstack/react-query";
import { TaleLoadingFallback } from "@components/TaleLoadingFallback";
import { surveysService } from "@/api/surveys";
import { surveySamples } from "@/utils/samples";
import { FF } from "@/utils/featureFlip";
import { useTranslation } from "@/hooks/useTranslation";

const NormalUserHome = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user } = useSelector((state) => state.auth);
  
  // Fetch regular surveys
  const { data: surveysData, isPending: isSurveysPending } = useQuery({
    queryKey: ["surveys"],
    queryFn: async () => await surveysService.getSurveysPaginated(0, 2, "Private"),
  });

  // Fetch quick surveys
  const { data: quickSurveysData, isPending: isQuickSurveysPending } = useQuery({
    queryKey: ["quickSurveys"],
    queryFn: async () => await surveysService.getQuickSurveys(),
  });

  const surveysToDisplay = surveysData?.result ?? [];
  const quickSurveysToDisplay = quickSurveysData?.result ?? [];

  const [showAllQuickSurveys, setShowAllQuickSurveys] = useState(false);
  const QUICK_SURVEYS_COLLAPSED_LIMIT = 10; // 2 rows on the widest breakpoint (5 cols)
  const visibleQuickSurveys = showAllQuickSurveys
      ? quickSurveysToDisplay
      : quickSurveysToDisplay.slice(0, QUICK_SURVEYS_COLLAPSED_LIMIT);

  const StatCard = useCallback(({ img, number, text, background }) => {
    return (
        <div className="stats-card grow basis-1/4 transition-transform hover:scale-[1.02]" style={{background}}>
          <div className="rounded-full bg-opacity-30 bg-white w-14 h-14 flex items-center justify-center">
          <img
            src={process.env.PUBLIC_URL + "/" + img}
            alt="LogoTale"
            style={{ width: "42px", height: "42px" }}
          />
        </div>
        <div
          style={{ display: "flex", flexDirection: "column", color: "white" }}
        >
          <p className="stats-value self-end">{number}</p>
          <h3 className="stats-title">{text}</h3>
        </div>
      </div>
    );
  }, []);

  const PreviewCard = useCallback(({ title, count, text, url, children }) => {
    return (
      <div className="flex flex-col gap-5 bg-white basis-full p-6 rounded-xl !min-h-[320px] shadow-sm hover:shadow-md transition-shadow">
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
          <h3 className="survey-title flex gap-2 items-center">
            <TaleText role={"normal"} className="!font-bold !text-lg">
              {title}
            </TaleText>
            {!!count && (
              <div className="flex items-center justify-center h-[24px] !min-w-[24px] px-2.5 font-bold text-xs bg-gradient-to-r from-[#FF720D] to-[#FFAA1A] rounded-full text-white shadow-sm">
                {count}
              </div>
            )}
          </h3>
          <Link
            to={url}
            className="cta-link !text-sm !font-semibold !text-[#FF720D] hover:!text-[#FFAA1A] transition-colors flex items-center gap-1"
          >
            {text}
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M6 12L10 8L6 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </Link>
        </div>
        {children}
      </div>
    );
  }, []);

  const statsCards = [
    {
      background: "#FFAA1A",
      img: "image8.png",
      number: user.totalPoints,
      text: t("home.normal.statPoints"),
    },
    {
      background: "#FF720D",
      img: "image10.png",
      number: quickSurveysToDisplay.length,
      text: t("home.normal.statQuickSurveys"),
    },
    {
      background: "#00BFED",
      img: "image7.png",
      number: 0,
      text: t("home.normal.statUpcomingLive"),
    },
  ];

  return (
    <div className="flex flex-col gap-4">
      <div className="flex flex-col !gap-1 items-start bg-gradient-to-r from-white to-orange-50 rounded-2xl p-6 shadow-sm">
        <div className="font-bold text-2xl">{t("home.normal.welcome", {name: user?.firstname || user?.given_name || ""})}</div>
        <div className="text-sm text-[#333]">
          {t("home.normal.subText")}
        </div>
      </div>
      <div className="flex gap-4 items-center">
        {statsCards.map((e) => (
          <React.Fragment key={e.img}>{StatCard(e)}</React.Fragment>
        ))}
      </div>
      <div className="flex flex-col !gap-4 items-start bg-white rounded-2xl p-6 shadow-sm">
        <div className="flex justify-between items-center w-full">
          <div>
            <TaleText role="business" className="text-xl font-bold">
              {t("home.normal.quickSurveyTitle")}
            </TaleText>
            <span className="ml-2 rtl:ml-0 rtl:mr-2 text-xs font-bold text-white bg-[#FF720D] px-2 py-0.5 rounded-full align-middle">
              {t("home.normal.startHere")}
            </span>
            <span className="text-sm text-[#666] mt-1 block">
              {t("home.normal.quickSurveySubText")}
            </span>
          </div>
        </div>

        {isQuickSurveysPending ? (
            <div className="w-full flex justify-center py-10">
              <TaleLoadingFallback />
            </div>
        ) : !quickSurveysToDisplay?.length ? (
            <div className="w-full flex flex-col items-center justify-center py-10">
              <img
                  src="/assets/empty-box.svg"
                  alt="No quick surveys"
                  height={55}
                  width={59}
                  className="opacity-50"
              />
              <p className="text-[#666] mt-3 text-sm">{t("home.normal.noQuickSurveys")}</p>
            </div>
        ) : (
            <div className="grid grid-cols-1 md:grid-cols-4 lg:grid-cols-5 gap-5 w-full justify-start items-start">
              {visibleQuickSurveys.map((survey, index) => (
                  <SurveyListItem
                      coverPhotoClassName={"!w-auto"}
                      key={survey.id || index}
                      canParticipate={!survey.completed && survey.status === 'active'}
                      coverPhoto={survey.coverPhoto || `/surv${(index % 4) + 1}.png`}
                      id={survey.id}
                      points={survey.rewardPoints || 0}
                      questions={survey.questionsCount || 0}
                      isQuickSurvey={true}
                      quickSurveyCategory={survey.category || t("home.normal.someCategory", { index })}
                  />
              ))}
            </div>
        )}
        {quickSurveysToDisplay.length > QUICK_SURVEYS_COLLAPSED_LIMIT && (
            <button
                onClick={() => setShowAllQuickSurveys((prev) => !prev)}
                className="cta-link !text-sm !font-semibold !text-[#FF720D] hover:!text-[#FFAA1A] transition-colors flex items-center gap-1 self-center mt-2"
            >
              {showAllQuickSurveys
                  ? t("home.normal.showLess")
                  : t("home.normal.viewAllCount", { count: quickSurveysToDisplay.length })}
              <svg
                  width="16"
                  height="16"
                  viewBox="0 0 16 16"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  style={{ transform: showAllQuickSurveys ? "rotate(-90deg)" : "rotate(90deg)" }}
              >
                <path d="M6 12L10 8L6 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
        )}
      </div>
      <div className="flex gap-4">
        <PreviewCard
          title={t("home.business.surveys")}
          count={surveysData?.totalItems ?? 0}
          text={t("home.normal.viewAllSurveys")}
          url="/surveys"
        >
          {isSurveysPending ? (
            <TaleLoadingFallback />
          ) : !surveysToDisplay?.length ? (
            <div className="size-full flex flex-col gap-3 items-center justify-center py-8">
              <img
                src="/assets/empty-box.svg"
                alt="Empty box"
                height={55}
                width={59}
                className="opacity-50"
              />
              <div className="!text-sm !text-[#666] text-center">
                {t("home.business.noSurveys")}
              </div>
            </div>
          ) : (
            <div className="flex flex-col gap-4">
              {surveysToDisplay.map((survey, index) => (
                <div 
                  key={index} 
                  className="survey-item flex gap-4 p-4 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer border border-gray-100"
                  onClick={() => navigate(`/survey/${survey.id}`)}
                >
                  <div className="survey-image-container size-[30%] flex-shrink-0">
                    <img
                      className="survey-image rounded-lg"
                      src={(survey.assets ?? []).find((asset) => asset.description === "SURVEY_BANNER")?.url ?? "/assets/survey/respond/no-image.png"}
                      alt="Survey"
                    />
                    <div className="points-badge bg-gradient-to-r from-[#FF720D] to-[#FFAA1A]">
                      <div className="points-text font-semibold" style={{ fontSize: 10 }}>
                        {t("home.normal.ptsAbbrev", { count: survey.rewardPoints || "--" })}
                      </div>
                    </div>
                  </div>
                  <div className="flex flex-col justify-between" style={{ width: "100%" }}>
                    <h4 className="survey-name font-bold text-base line-clamp-2">{survey.title}</h4>
                    <div className="flex gap-4 text-xs text-[#666]">
                      <span className="flex items-center gap-1">
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M7 1V7L10 10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                          <circle cx="7" cy="7" r="6" stroke="currentColor" strokeWidth="1.5"/>
                        </svg>
                        {t("home.normal.questionsCount", { count: survey.questionsCount })}
                      </span>
                      <span className="flex items-center gap-1">
                        <svg width="14" height="14" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
                          <path d="M7 1L8.5 5H13L9.5 8L11 12L7 9L3 12L4.5 8L1 5H5.5L7 1Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/>
                        </svg>
                        {t("home.normal.pointsCount", { count: survey.rewardPoints || "--" })}
                      </span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </PreviewCard>
        {FF.USE_FOCUS_GROUP && (
          <PreviewCard
            title={t("home.business.focusGroup")}
            count={2}
            text={t("home.normal.viewAll")}
            url={"/focus-groups"}
          >
            <div className="!flex gap-5 p-4 rounded-lg border border-gray-100 hover:border-orange-200 transition-colors">
              <div className="relative flex-shrink-0">
                <img
                  className="survey-image !min-h-full !min-w-[230px] rounded-lg"
                  src={surveySamples.at(0).coverPhoto}
                  alt="Focus Group"
                />
                <div className="points-badgeFG absolute top-2 left-2 rtl:left-auto rtl:right-2 !text-xs !rounded-lg bg-gradient-to-r from-[#FF720D] to-[#FFAA1A] shadow-md">
                  {t("home.normal.pointsCount", { count: 60 })}
                </div>
              </div>

              {/* Right side with survey details */}
              <div className="survey-details grow !min-h-full flex flex-col justify-between">
                <div>
                  <h2 className="card-title font-bold text-xl font-sans mb-2 line-clamp-2">
                    {surveySamples.at(0).title}
                  </h2>
                  <div className="flex items-center gap-2 text-sm text-[#666]">
                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                      <rect x="2" y="3" width="12" height="11" rx="1" stroke="currentColor" strokeWidth="1.5"/>
                      <path d="M2 6H14M5 1V3M11 1V3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/>
                    </svg>
                    <span>25/12/2024 - 12:00</span>
                  </div>
                </div>
                <button
                    onClick={() => navigate("/focus-group/1")}
                    className="participate-btn !max-w-60 bg-gradient-to-r from-[#FF720D] to-[#FFAA1A] hover:shadow-lg transition-shadow"
                >
                  {t("home.normal.participate")}
                </button>
              </div>
            </div>
          </PreviewCard>
        )}
      </div>
    </div>
  );
};

export default NormalUserHome;