'use client';

import { useLocale, useTranslations } from 'next-intl';
import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { CheckCircle, Star } from 'lucide-react';

interface ReviewQuestion {
    id: number;
    name: string;
    note: string | null;
    review_section_id: number;
    type_response: string;
}

interface ReviewSection {
    id: number;
    name: string;
    review_id: number;
    review_questions: ReviewQuestion[];
}

interface ReviewResultData {
    success: boolean;
    groupReview: {
        group_id: number;
        review_id: number;
        show_note: number;
        is_completed: boolean;
        review: {
            id: number;
            name: string;
            description: string | null;
            review_sections: ReviewSection[];
        };
    };
    answers: {
        id: number;
        participant_id: number;
        group_review_id: number;
        note: number;
        answers: any[];
        questions: number[];
        persontage: string;
        // nested enriched data WITH question names
        group_review?: {
            review?: {
                name?: string;
                review_sections: ReviewSection[];
            };
        };
    };
}

export function ReviewResult({ resultData, courseName }: { resultData: ReviewResultData, courseName?: string }) {
    const t = useTranslations('programs');
    const locale = useLocale();
    const isArabic = locale === 'ar';

    console.log('ReviewResult received data:', resultData);

    if (!resultData?.answers) {
        return (
            <div className="min-h-screen flex items-center justify-center p-4">
                <Card className="max-w-md w-full">
                    <CardContent className="p-8 text-center">
                        <h2 className="text-2xl font-bold mb-2">{t('reviewNotAvailable')}</h2>
                        <p className="text-gray-600 mb-6">{t('reviewNotAvailableMessage')}</p>
                        <Button 
                            onClick={() => window.location.reload()}
                            className="bg-purple-700 hover:bg-purple-800"
                        >
                            {t('go-back')}
                        </Button>
                    </CardContent>
                </Card>
            </div>
        );
    }

    // Prefer sections from answers.group_review (has question names) over groupReview (no names)
    const sections =
        resultData.answers?.group_review?.review?.review_sections ||
        resultData.groupReview?.review?.review_sections ||
        [];
    const answers = resultData.answers.answers || [];
    const questions = resultData.answers.questions || [];
    const percentage = resultData.answers.persontage || '0%';
    const totalScore = resultData.answers.note || 0;
    // Also get the review name from the enriched source if available
    const reviewName =
        resultData.answers?.group_review?.review?.name ??
        resultData.groupReview?.review?.name ??
        '';


    const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
    const currentSection = sections[currentSectionIndex];

    return (
        <div className="h-screen flex flex-col bg-gray-50 overflow-hidden">
            {/* Purple Header */}
            <div className="bg-gradient-to-r from-purple-600 via-purple-700 to-indigo-700  text-white px-6 py-4 flex-shrink-0">
                <div className="max-w-4xl mx-auto flex items-center justify-between">
                    <div className="flex items-center gap-4">
                      
                        <h2 className="text-xl font-bold">{reviewName || t('review')}</h2>
                    </div>
                    <div className="flex items-center gap-4">
                        {/* <div className="flex items-center gap-2 text-sm">
                            <CheckCircle className="size-5" />
                            <span className="font-semibold">الدرجة: {totalScore}</span>
                        </div> */}
                        <div className="flex items-center gap-2 text-sm">
                            <span className="font-semibold">النسبة: {percentage}</span>
                        </div>
                    </div>
                      <Button
                            onClick={() => window.location.reload()}
                            variant="ghost"
                            className="bg-white text-purple-600 hover:bg-purple-50 p-2 rounded-lg transition-all hover:scale-105"
                        >
                            {t('go-back')}
                            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
                            </svg>
                        </Button>
                </div>
            </div>

            <div className="flex-1 overflow-y-auto">
                <div className="max-w-4xl mx-auto p-6 pb-20">
                    {/* Section Card */}
                    <div className="bg-white rounded-lg shadow-sm p-8">
                        {/* Section Numbers Navigation */}
                        <div className="mb-6">
                            <h3 className="text-sm font-semibold text-gray-700 mb-4">
                                {t('sectionOutOf', { current: currentSectionIndex + 1, total: sections.length })}
                            </h3>
                            <div className="flex gap-2 flex-wrap">
                                {sections.map((_, index) => (
                                    <button
                                        key={index}
                                        onClick={() => setCurrentSectionIndex(index)}
                                        className={`size-10 rounded-full font-semibold transition-all ${
                                            index === currentSectionIndex
                                                ? 'bg-gray-800 text-white'
                                                : 'bg-white text-gray-600 border-2 border-gray-300 hover:border-gray-400'
                                        }`}
                                    >
                                        {index + 1}
                                    </button>
                                ))}
                            </div>
                        </div>

                        {/* Section Title */}
                        <div className="mb-6">
                            <h3 className="text-xl font-bold text-purple-700">
                                {currentSection.name}
                            </h3>
                        </div>

                        {/* Questions and Answers */}
                        <div className="space-y-6">
                            {currentSection.review_questions.map((question) => {
                                const questionIndex = questions.indexOf(question.id);
                                const answer = questionIndex !== -1 ? answers[questionIndex] : null;

                                return (
                                    <div key={question.id} className="p-4 border rounded-lg bg-gray-50">
                                        <h4 className="font-semibold text-gray-900 mb-4">
                                            {question.name}
                                        </h4>
                                        
                                        {question.type_response === 'start' && (
                                            <div className="flex items-center gap-2">
                                                {[1, 2, 3, 4, 5].map((star) => (
                                                    <Star
                                                        key={star}
                                                        className={`h-6 w-6 ${
                                                            star <= (answer || 0)
                                                                ? 'fill-yellow-400 text-yellow-400'
                                                                : 'text-gray-300'
                                                        }`}
                                                    />
                                                ))}
                                                <span className="ml-2 text-gray-600">
                                                    ({answer || 0}/5)
                                                </span>
                                            </div>
                                        )}

                                        {question.type_response === 'text_response' && (
                                            <div className="bg-white rounded-lg p-4 border">
                                                <p className="text-gray-700">
                                                    {answer || t('noAnswer')}
                                                </p>
                                            </div>
                                        )}

                                        {question.type_response === 'true_false' && (
                                            <div className="flex items-center gap-2">
                                                <span className={`px-4 py-2 rounded-lg font-semibold ${
                                                    answer === 1 
                                                        ? 'bg-green-100 text-green-700' 
                                                        : 'bg-red-100 text-red-700'
                                                }`}>
                                                    {answer === 1 ? t('yes') : t('no')}
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}
