import {  useMemo } from "react";
import { useNavigate, useParams, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import { useQuery } from "@tanstack/react-query";
import { surveysService } from "@/api/surveys";
import { TaleDashbaordMainCard } from "@components/TaleDashbaordMainCard";
import { TaleLoadingFallback } from "@components/TaleLoadingFallback";
// import { lazily } from "react-lazily";
import { formatQuestionApiToUi } from "@/utils/questionFormatApiToUi";
import { isJSON } from "@/utils/isJSON";
import { useTranslation } from "@/hooks/useTranslation";

// Import React Icons
import {
    FiCheckCircle,
    FiAward,
    FiCalendar,
    FiClock,
    FiShare2,
    FiUser,
    FiBarChart2,
    FiMessageSquare,
    FiUsers,
    FiTarget,
} from "react-icons/fi";
import {
    BsBuilding,
    BsStars,
    BsArrowRight,
    BsFillClipboardCheckFill,
    BsCheck2Circle,
    BsCurrencyDollar
} from "react-icons/bs";
import TaleButton from "@components/TaleButton";

// const { NotFound } = lazily(() => import("@components/Errors/NotFound"));

const SurveyCompletionPage = () => {
    const { t } = useTranslation();
    const nav = useNavigate();
    const { surveyId } = useParams();
    const location = useLocation();
    const user = useSelector((state) => state.auth.user);

    // Get the last response ID from location state or fetch
    const lastResponseId = location.state?.lastResponseId;

    const {
        isPending: loading,
        data: surveyData,
        error,
    } = useQuery({
        queryKey: ["survey-completion", surveyId, user?.id, lastResponseId],
        queryFn: async () => {
            // Get survey details
            const surveyResponse = await surveysService.getSurvey(surveyId);

            // Get user's specific response if we have a response ID
            let userResponse = null;
            let userResponses = [];

            if (user?.id && lastResponseId) {
                try {
                    userResponse = await surveysService.getSurveyResponse(lastResponseId);
                } catch (err) {
                    console.log("Could not fetch specific response:", err);
                }
            }

            // Get all user responses to this survey
            if (user?.id) {
                userResponses = await surveysService.getUserResponsesToSurveyQuestions({ surveyId });
            }

            // Get user responses with question details
            const questionsWithAnswers = surveyResponse.questions.map(question => {
                const userAnswer = userResponses.find(res => res.questionId === question.id);

                let formattedAnswer = null;
                if (userAnswer) {
                    try {
                        if (isJSON(userAnswer.answer)) {
                            formattedAnswer = JSON.parse(userAnswer.answer);
                        } else {
                            formattedAnswer = userAnswer.answer;
                        }
                    } catch (e) {
                        formattedAnswer = userAnswer.answer;
                    }
                }

                return {
                    ...formatQuestionApiToUi(question),
                    userAnswer: formattedAnswer,
                    answeredAt: userAnswer?.createdAt,
                    answerId: userAnswer?.id
                };
            });

            const answeredQuestions = questionsWithAnswers.filter(q => q.userAnswer !== null);
            const completionPercentage = surveyResponse.questions.length > 0
                ? (answeredQuestions.length / surveyResponse.questions.length) * 100
                : 0;

            return {
                survey: surveyResponse,
                userResponse,
                userResponses,
                questionsWithAnswers,
                answeredQuestions,
                completionPercentage,
                pointsEarned: surveyResponse.rewardPoints || 0,
                completionTime: userResponse?.finishedAt ?
                    new Date(userResponse.finishedAt) - new Date(userResponse.startedAt) :
                    null
            };
        },
        retry: false,
    });

    // Format completion time
    const formatCompletionTime = useMemo(() => {
        if (!surveyData?.completionTime) return "N/A";
        const minutes = Math.floor(surveyData.completionTime / 60000);
        const seconds = Math.floor((surveyData.completionTime % 60000) / 1000);
        return `${minutes}m ${seconds}s`;
    }, [surveyData?.completionTime]);

    // Get completion date
    const completionDate = useMemo(() => {
        if (!surveyData?.userResponse?.finishedAt) return new Date().toLocaleDateString();
        return new Date(surveyData.userResponse.finishedAt).toLocaleDateString('en-US', {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        });
    }, [surveyData?.userResponse?.finishedAt]);

    const handleShare = () => {
        const shareText = t("surveyBuilder.completed.shareText", { title: surveyData?.survey?.title, points: surveyData?.pointsEarned });
        if (navigator.share) {
            navigator.share({
                title: t("surveyBuilder.completed.shareTitle"),
                text: shareText,
                url: window.location.href,
            });
        } else {
            navigator.clipboard.writeText(shareText);
            alert(t("surveyBuilder.completed.shareCopied"));
        }
    };

    /*const handleDownload = () => {
        const data = {
            survey: surveyData?.survey,
            userResponses: surveyData?.userResponses,
            completedAt: new Date().toISOString()
        };

        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `survey-${surveyId}-responses.json`;
        a.click();
        URL.revokeObjectURL(url);
    };*/

    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <TaleLoadingFallback className="py-20" />
            </div>
        );
    }

    if (error) {
        return (
            <div className="min-h-screen flex items-center justify-center">
                <div className="text-center">
                    <h2 className="text-2xl font-bold text-gray-900 mb-4">{t("surveyBuilder.completed.errorTitle")}</h2>
                    <p className="text-gray-600 mb-6">{error.message}</p>
                    <TaleButton onClick={() => nav(`/survey/${surveyId}`)}>
                        {t("surveyBuilder.completed.returnToSurvey")}
                    </TaleButton>
                </div>
            </div>
        );
    }

    return (

                <TaleDashbaordMainCard className="!rounded-2xl !shadow-xl !border-0 overflow-hidden mb-8">
                    {/* Success Header Section */}
                    <div className="bg-gradient-to-r from-green-500 to-emerald-600 text-white p-4 md:p-8 rounded-2xl m-2">
                        <div className="flex flex-row md:flex-row items-start justify-between gap-1 md:gap-6">
                            <div className="flex items-start gap-3 md:gap-4">
                                <div className="bg-white/20 p-3 rounded-xl backdrop-blur-sm">
                                    <FiCheckCircle className="w-4 h-4 md:w-8 md:h-8" />
                                </div>
                                <div>
                                    <h1 className="text-sm md:text-3xl font-bold mb-2">
                                        {t("surveyBuilder.completed.successTitle")}
                                    </h1>
                                    <p className="hidden md:block text-xs md:text-xl text-green-100 opacity-90">
                                        {t("surveyBuilder.completed.thankYouMessage")}
                                    </p>
                                </div>
                            </div>

                            <div className="text-right md:text-center rtl:text-left">
                                <div className="text-lg md:text-4xl font-black mb-1 flex items-center gap-1 justify-end rtl:justify-start">
                                    <FiAward className="w-4 h-4 md:w-8 md:h-8" />
                                    {surveyData?.pointsEarned}
                                </div>
                                <div className="text-xs md:text-lg text-green-100 opacity-90">
                                    {t("surveyBuilder.completed.pointsEarnedLabel")}
                                </div>
                            </div>
                        </div>

                        <p className="block md:hidden text-xs md:text-xl text-green-100 opacity-90">
                            {t("surveyBuilder.completed.thankYouMessage")}
                        </p>
                    </div>

                    <div className="p-3 md:p-8">
                        {/* Survey Information Row */}
                        <div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                            <div className="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-xl p-3 md:p-5 border border-blue-100">
                                <div className="flex items-center gap-3 mb-3">
                                    <div className="p-2 rounded-lg bg-blue-100">
                                        <BsBuilding className="w-3 h-3 md:w-5 md:h-5 text-blue-600" />
                                    </div>
                                    <div>
                                        <div className="text-xs md:text-sm font-medium text-gray-900">{t("surveyBuilder.completed.surveyDetailsLabel")}</div>
                                        <div className="text-sm md:text-lg font-bold text-gray-900">{surveyData?.survey?.title}</div>
                                    </div>
                                </div>
                                <div className="text-xs md:text-sm text-gray-600">
                                    <div className="flex items-center gap-2 mb-1">
                                        <FiUser className="w-4 h-4" />
                                        <span>{surveyData?.survey?.company?.companyName || t("surveyBuilder.completed.companyFallback")}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <FiTarget className="w-4 h-4" />
                                        <span>{surveyData?.survey?.category?.replace(/_/g, ' ') || t("surveyBuilder.completed.categoryFallback")}</span>
                                    </div>
                                </div>
                            </div>

                            <div className="bg-gradient-to-r from-amber-50 to-orange-50 rounded-xl p-3 md:p-5 border border-amber-100">
                                <div className="flex items-center gap-3 mb-3">
                                    <div className="p-2 rounded-lg bg-amber-100">
                                        <FiCalendar className="w-3 h-3 md:w-5 md:h-5 text-amber-600" />
                                    </div>
                                    <div>
                                        <div className="text-xs md:text-sm font-medium text-gray-900">{t("surveyBuilder.completed.completionStatsLabel")}</div>
                                        <div className="text-sm md:text-lg font-bold text-gray-900">{completionDate}</div>
                                    </div>
                                </div>
                                <div className="text-xs md:text-sm text-gray-600">
                                    <div className="flex items-center gap-2 mb-1">
                                        <FiClock className="w-4 h-4" />
                                        <span>{t("surveyBuilder.completed.timeTakenLabel", { time: formatCompletionTime })}</span>
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <FiUsers className="w-4 h-4" />
                                        <span>{t("surveyBuilder.completed.totalResponsesLabel", { count: surveyData?.survey?.responsesNumber || 0 })}</span>
                                    </div>
                                </div>
                            </div>

                            <div className="bg-gradient-to-r from-teal-50 to-emerald-50 rounded-xl p-3 md:p-5 border border-teal-100">
                                <div className="flex items-center gap-3 mb-3">
                                    <div className="p-2 rounded-lg bg-teal-100">
                                        <FiBarChart2 className="w-3 h-3 md:w-5 md:h-5 text-teal-600" />
                                    </div>
                                    <div>
                                        <div className="text-xs md:text-sm font-medium text-gray-900">{t("surveyBuilder.completed.yourPerformanceLabel")}</div>
                                        <div className="text-sm md:text-lg font-bold text-gray-900">
                                            {t("surveyBuilder.completed.questionsCountLabel", { answered: surveyData?.answeredQuestions?.length || 0, total: surveyData?.survey?.questions?.length || 0 })}
                                        </div>
                                    </div>
                                </div>
                                <div className="text-xs md:text-sm text-gray-600">
                                    <div className="flex items-center justify-between mb-1">
                                        <span>{t("surveyBuilder.completed.completionLabel")}</span>
                                        <span className="font-semibold">{Math.round(surveyData?.completionPercentage || 0)}%</span>
                                    </div>
                                    <div className="h-2 bg-gray-200 rounded-full overflow-hidden">
                                        <div
                                            className="h-full bg-gradient-to-r from-teal-500 to-emerald-600 rounded-full"
                                            style={{ width: `${surveyData?.completionPercentage || 0}%` }}
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>

                        {/* Your Responses Section */}
                        <div className="mb-8">
                            <div className="flex items-center justify-between mb-6">
                                <h2 className="text-lg md:text-xl font-bold text-gray-900 flex items-center gap-2">
                                    <BsFillClipboardCheckFill className="w-5 h-5 text-blue-600" />
                                    {t("surveyBuilder.completed.yourResponsesTitle")}
                                </h2>
                                <span className="text-xs md:text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                                  {t("surveyBuilder.completed.answeredCount", { count: surveyData?.answeredQuestions?.length || 0 })}
                                </span>
                            </div>

                            {surveyData?.answeredQuestions?.length === 0 ? (
                                <div className="text-center py-12 bg-gray-50 rounded-xl border border-gray-200">
                                    <FiMessageSquare className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                                    <h3 className="text-sm md:text-lg font-semibold text-gray-700 mb-2">{t("surveyBuilder.completed.noResponsesTitle")}</h3>
                                    <p className="text-xs md:text-sm text-gray-500">{t("surveyBuilder.completed.noResponsesMessage")}</p>
                                </div>
                            ) : (
                                <div className="space-y-4 max-h-[400px] overflow-y-auto pr-2">
                                    {surveyData?.questionsWithAnswers?.map((question, index) => (
                                        <div
                                            key={question.id || index}
                                            className={`rounded-lg border p-4 transition-all duration-200 ${
                                                question.userAnswer !== null
                                                    ? 'border-green-200 bg-green-50 hover:bg-green-100'
                                                    : 'border-gray-200 bg-gray-50 hover:bg-gray-100'
                                            }`}
                                        >
                                            <div className="flex items-start gap-3">
                                                <div className={`p-2 rounded-lg ${
                                                    question.userAnswer !== null
                                                        ? 'bg-green-100 text-green-700'
                                                        : 'bg-gray-100 text-gray-700'
                                                }`}>
                                                    {question.userAnswer !== null ? (
                                                        <BsCheck2Circle className="w-4 h-4" />
                                                    ) : (
                                                        <FiMessageSquare className="w-4 h-4" />
                                                    )}
                                                </div>

                                                <div className="flex-1">
                                                    <div className="flex items-center justify-between mb-2">
                                                        <span className="text-sm font-medium text-gray-900">
                                                            {t("reports.page.questionLabel", { value: index + 1 })}
                                                        </span>
                                                        <span className={`text-xs px-2 py-1 rounded-full ${
                                                            question.mandatory
                                                                ? 'bg-amber-100 text-amber-700'
                                                                : 'bg-gray-100 text-gray-600'
                                                        }`}>
                                                          {question.mandatory ? t("question.required_label") : t("question.optional_label")}
                                                        </span>
                                                    </div>

                                                    <h4 className="text-sm md:text-lg font-semibold text-gray-900 mb-1">
                                                        {question.question_text}
                                                    </h4>

                                                    {question.userAnswer !== null ? (
                                                        <div className="mt-3">
                                                            <div className="text-xs md:text-sm font-medium text-gray-700 mb-1">{t("surveyBuilder.completed.yourAnswerLabel")}</div>
                                                            <div className="bg-white rounded-lg border border-gray-200 p-1 md:p-3">
                                                                {question.questionType === 'RADIO' || question.questionType === 'CHECKBOX' ? (
                                                                    <div className="flex flex-wrap gap-2">
                                                                        {Array.isArray(question.userAnswer) ? (
                                                                            question.userAnswer.map((answer, idx) => (
                                                                                <span
                                                                                    key={idx}
                                                                                    className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm"
                                                                                >
                                                                                  {answer}
                                                                                </span>
                                                                            ))
                                                                        ) : (
                                                                            <span className="px-3 py-1 bg-blue-100 text-blue-700 rounded-full text-sm">
                                                                               {question.userAnswer}
                                                                            </span>
                                                                        )}
                                                                    </div>
                                                                ) : question.questionType === 'COMMENT' ? (
                                                                    <div className="text-gray-700 italic text-sm">
                                                                        "{question.userAnswer}"
                                                                    </div>
                                                                ) : question.questionType === 'SCALE_OF_TEN' ? (
                                                                    <div className="flex items-center gap-3">
                                                                        <div className="text-xl font-bold text-blue-700">
                                                                            {question.userAnswer}/10
                                                                        </div>
                                                                        <div className="flex">
                                                                            {[...Array(10)].map((_, i) => (
                                                                                <div
                                                                                    key={i}
                                                                                    className={`w-6 h-6 mx-0.5 rounded-full flex items-center justify-center text-xs ${
                                                                                        i < question.userAnswer
                                                                                            ? 'bg-gradient-to-r from-blue-500 to-indigo-500 text-white'
                                                                                            : 'bg-gray-200 text-gray-400'
                                                                                    }`}
                                                                                >
                                                                                    {i + 1}
                                                                                </div>
                                                                            ))}
                                                                        </div>
                                                                    </div>
                                                                ) : (
                                                                    <div className="text-xs md:text-sm text-gray-700">
                                                                        {question.userAnswer}
                                                                    </div>
                                                                )}
                                                            </div>
                                                        </div>
                                                    ) : (
                                                        <div className="mt-3">
                                                            <span className="text-gray-400 italic text-sm">{t("surveyBuilder.completed.notAnswered")}</span>
                                                        </div>
                                                    )}
                                                </div>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            )}
                        </div>

                        {/* Actions Section */}
                        <div className="border-t border-gray-200 pt-6">
                            <div className="flex flex-col md:flex-row items-center justify-between gap-4">
                                <div className="text-sm text-gray-600">
                                    <div className="flex items-center gap-2">
                                        <BsCurrencyDollar className="w-4 h-4 text-amber-500" />
                                        <span>{t("surveyBuilder.completed.earnedPointsPrefix")} <span className="font-semibold text-amber-600">{t("home.normal.pointsCount", { count: surveyData?.pointsEarned })}</span></span>
                                    </div>
                                </div>

                                <div className="flex flex-wrap gap-3">
                                    <TaleButton
                                        onClick={handleShare}
                                        variant="outline"
                                        className="!border-gray-300 !text-gray-700"
                                        startIcon={<FiShare2 className="w-4 h-4" />}
                                    >
                                        {t("surveys.item.share")}
                                    </TaleButton>

                                    {/*<TaleButton
                                        onClick={handleDownload}
                                        variant="outline"
                                        className="!border-gray-300 !text-gray-700"
                                        startIcon={<FiDownload className="w-4 h-4" />}
                                    >
                                        Download
                                    </TaleButton>*/}

                                    {/*<TaleButton
                                        onClick={() => nav(`/survey/${surveyId}`)}
                                        variant="outline"
                                        className="!border-gray-300 !text-gray-700"
                                        startIcon={<FiRepeat className="w-4 h-4" />}
                                    >
                                        Retake
                                    </TaleButton>*/}

                                    <TaleButton
                                        onClick={() => nav("/surveys")}
                                        variant="gradient"
                                        endIcon={<BsArrowRight className="w-4 h-4 rtl:-scale-x-100" />}
                                        className="!from-blue-600 !to-indigo-600"
                                    >
                                        {t("surveyBuilder.completed.findMore")}
                                    </TaleButton>
                                </div>
                            </div>

                            {/* Next Steps */}
                            <div className="mt-6 p-4 bg-gradient-to-r from-indigo-50 to-blue-50 rounded-lg border border-indigo-100">
                                <div className="flex items-center gap-3 mb-3">
                                    <BsStars className="w-5 h-5 text-indigo-600" />
                                    <h4 className="font-semibold text-gray-900">{t("surveyBuilder.completed.whatsNextTitle")}</h4>
                                </div>
                                <div className="grid grid-cols-3 md:grid-cols-3 gap-4">
                                    <div className="text-center">
                                        <div className="text-lg md:text-xl font-bold text-indigo-700 mb-1">24h</div>
                                        <div className="text-xs md:text-sm text-gray-600">{t("surveyBuilder.completed.resultsAvailableLabel")}</div>
                                    </div>
                                    <div className="text-center">
                                        <div className="text-lg md:text-xl font-bold text-indigo-700 mb-1">{surveyData?.pointsEarned}</div>
                                        <div className="text-xs md:text-sm text-gray-600">{t("surveyBuilder.completed.pointsAddedLabel")}</div>
                                    </div>
                                    <div className="text-center">
                                        <div className="text-lg md:text-xl font-bold text-indigo-700 mb-1">+1</div>
                                        <div className="text-xs md:text-sm text-gray-600">{t("surveyBuilder.completed.surveyCompletedLabel")}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </TaleDashbaordMainCard>


    );
};

export default SurveyCompletionPage;
