'use client';
import { useTranslations, useLocale } from 'next-intl';
import { useState } from 'react';
import { Star, Send, CheckCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { submitPublicSurvey } from '../../_actions/surveys';

interface ReviewQuestion {
    id: number;
    name: string;
    review_section_id: number;
    note: number | null;
    type_response: 'start' | 'true_false' | 'text_response';
    review_responses: Array<{
        id: number;
        name: string;
        note: number;
        review_question_id: number;
    }>;
}

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

interface SurveyData {
    success: boolean;
    reviewPublic: {
        id: number;
        name: string;
        description: string;
        review: {
            id: number;
            name: string;
            description: string | null;
            review_sections: ReviewSection[];
        };
    };
}

export function SurveyInterface({ surveyData }: { surveyData: SurveyData }) {
    const t = useTranslations();
    const locale = useLocale();
    const isArabic = locale === 'ar';

    const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
    const [answers, setAnswers] = useState<Record<number, any>>({});
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isSubmitted, setIsSubmitted] = useState(false);

    const sections = surveyData?.reviewPublic?.review?.review_sections || [];
    const currentSection = sections[currentSectionIndex];

    if (!sections.length) {
        return (
            <div className="min-h-[70vh] 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">الاستبيان غير متاح</h2>
                        <p className="text-gray-600">لا يوجد بيانات لعرضها في هذا الاستبيان.</p>
                    </CardContent>
                </Card>
            </div>
        );
    }

    const handleStarRating = (questionId: number, rating: number) => {
        setAnswers(prev => ({ ...prev, [questionId]: rating }));
    };

    const handleTextResponse = (questionId: number, text: string) => {
        setAnswers(prev => ({ ...prev, [questionId]: text }));
    };

    const handleTrueFalseResponse = (questionId: number, responseId: number) => {
        setAnswers(prev => ({ ...prev, [questionId]: responseId }));
    };

    const handleSubmit = async () => {
        setIsSubmitting(true);

        try {
            const questions: number[] = [];
            const my_rate: any[] = [];
            const additionalRates: Record<string, number> = {};

            sections.forEach(section => {
                if (!section?.review_questions) return;
                
                section.review_questions.forEach(question => {
                    if (!question?.id) return;
                    
                    const answer = answers[question.id];
                    const type = question.type_response || 'start';

                    if (type === 'start') {
                        questions.push(question.id);
                        my_rate.push(Number(answer) || 0);
                    } else if (type === 'text_response') {
                        questions.push(question.id);
                        my_rate.push(answer || '');
                    } else if (type === 'true_false') {
                        const selectedResponse = question.review_responses?.find(r => r.id === answer);
                        let isTrue = false;
                        if (selectedResponse) {
                            const name = selectedResponse.name?.toLowerCase() || '';
                            isTrue = name.includes('صحيح') || name.includes('true') || name.includes('نعم') || name.includes('yes') || name === '1';
                        }
                        additionalRates[`my_rate_${question.id}`] = isTrue ? 1 : 0;
                    } else {
                        questions.push(question.id);
                        my_rate.push(answer || '');
                    }
                });
            });

            const payload = {
                questions,
                my_rate,
                ...additionalRates
            };

            const submissionId = surveyData?.reviewPublic?.id;
            if (!submissionId) {
                throw new Error('No review ID available for submission');
            }

            const result = await submitPublicSurvey(submissionId.toString(), payload) as any;

            if (result.success) {
                setIsSubmitted(true);
            } else {
                const errorMsg = result.message || (isArabic ? "فشل إرسال التقييم. يرجى التأكد من ملء جميع البيانات." : "Failed to submit review.");
                alert(errorMsg);
            }
        } catch (error) {
            console.error('Error submitting review:', error);
            alert("حدث خطأ أثناء الإرسال");
        } finally {
            setIsSubmitting(false);
        }
    };

    if (isSubmitted) {
        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 text-black bg-white rounded-lg">
                        <CheckCircle className="h-16 w-16 text-green-600 mx-auto mb-4" />
                        <h2 className="text-2xl font-bold mb-2">تم الإرسال بنجاح</h2>
                        <p className="text-gray-600 mb-6">شكراً لك على مشاركتك في هذا التقييم</p>
                        <Button
                            onClick={() => window.location.href = '/surveys'}
                            className="bg-purple-700 hover:bg-purple-800"
                        >
                            العودة للاستبيانات
                        </Button>
                    </CardContent>
                </Card>
            </div>
        );
    }

    const renderStarRating = (question: ReviewQuestion) => {
        const rating = answers[question.id] || 0;
        return (
            <div className="flex items-center gap-2 justify-center my-4 text-black">
                {[1, 2, 3, 4, 5].map((star) => (
                    <button
                        key={star}
                        type="button"
                        onClick={() => handleStarRating(question.id, star)}
                        className="transition-transform hover:scale-110"
                    >
                        <Star
                            className={`h-8 w-8 ${star <= rating ? 'fill-yellow-400 text-yellow-400' : 'text-gray-300'}`}
                        />
                    </button>
                ))}
            </div>
        );
    };

    return (
        <div className="min-h-screen flex flex-col bg-gray-50 flex-1">
            <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-3xl mx-auto flex items-center justify-between">
                    <div className="flex flex-col gap-1 w-full max-w-full overflow-hidden">
                        <h2 className="text-xl font-bold truncate">استبيان: {surveyData.reviewPublic?.name || 'بدون عنوان'}</h2>
                        <span className="text-purple-100 text-sm">{surveyData.reviewPublic?.review?.name}</span>
                    </div>
                </div>
            </div>

            <div className="flex-1 w-full overflow-y-auto">
                <div className="max-w-3xl mx-auto p-4 md:p-6 pb-20">
                    <div className="bg-white rounded-lg shadow-sm p-6 md:p-8">
                        <div className="mb-6 border-b pb-4 text-start">
                            <h3 className="text-sm font-semibold text-gray-700 mb-4 whitespace-nowrap">
                                القسم {currentSectionIndex + 1} من {sections.length}
                            </h3>
                            <div className="flex gap-2 flex-wrap text-black">
                                {sections.map((_, index) => (
                                    <button
                                        key={index}
                                        onClick={() => setCurrentSectionIndex(index)}
                                        className={`size-10 rounded-full font-semibold transition-all flex items-center justify-center outline-none ${
                                            index === currentSectionIndex
                                                ? 'bg-purple-600 text-white border-purple-600'
                                                : 'bg-white text-gray-600 border border-gray-300 hover:border-purple-400'
                                        }`}
                                    >
                                        {index + 1}
                                    </button>
                                ))}
                            </div>
                        </div>

                        <div className="mb-6 text-start">
                            <h3 className="text-xl font-bold text-black border-r-4 border-purple-600 pr-3">
                                {currentSection.name}
                            </h3>
                        </div>

                        <div className="space-y-6 text-start">
                            {currentSection.review_questions.map((question, index) => (
                                <div key={question.id} className="p-4 md:p-6 border rounded-lg bg-gray-50/50 hover:bg-gray-50 transition-colors">
                                    <h4 className="font-semibold text-gray-900 mb-6 leading-relaxed">
                                        {index + 1}. {question.name}
                                    </h4>

                                    {question.type_response === 'start' && renderStarRating(question)}

                                    {question.type_response === 'text_response' && (
                                        <Textarea
                                            value={answers[question.id] || ''}
                                            onChange={(e) => handleTextResponse(question.id, e.target.value)}
                                            placeholder="اكتب إجابتك هنا..."
                                            className="min-h-[120px] bg-white text-black"
                                        />
                                    )}

                                    {question.type_response === 'true_false' && question.review_responses.length > 0 && (
                                        <RadioGroup
                                            value={answers[question.id]?.toString() || ''}
                                            onValueChange={(value) => handleTrueFalseResponse(question.id, parseInt(value))}
                                        >
                                            <div className="grid sm:grid-cols-2 gap-3 mt-4 text-black">
                                                {question.review_responses.map((response) => (
                                                    <div
                                                        key={response.id}
                                                        className={`flex items-center gap-3 p-4 rounded-lg border-2 transition-all cursor-pointer hover:bg-purple-50 ${answers[question.id] === response.id ? 'border-purple-600 bg-purple-50/50' : 'border-gray-200 bg-white'}`}
                                                    >
                                                        <RadioGroupItem value={response.id.toString()} id={`response-${response.id}`} className="text-purple-600" />
                                                        <Label htmlFor={`response-${response.id}`} className="cursor-pointer font-medium text-gray-700 flex-1 flex">
                                                            {response.name}
                                                        </Label>
                                                    </div>
                                                ))}
                                            </div>
                                        </RadioGroup>
                                    )}
                                </div>
                            ))}
                        </div>
                    </div>

                    <div className="flex gap-3 justify-end mt-8 pb-12">
                        {currentSectionIndex > 0 && (
                            <Button
                                onClick={() => setCurrentSectionIndex(prev => prev - 1)}
                                variant="outline"
                                className="px-6 py-2"
                            >
                                السابق
                            </Button>
                        )}
                        {currentSectionIndex < sections.length - 1 ? (
                            <Button
                                onClick={() => setCurrentSectionIndex(prev => prev + 1)}
                                disabled={currentSection.review_questions.some(q => !answers[q.id])}
                                className="bg-purple-600 hover:bg-purple-700 text-white px-8 py-2"
                            >
                                التالي
                            </Button>
                        ) : (
                            <Button
                                onClick={handleSubmit}
                                disabled={isSubmitting || currentSection.review_questions.some(q => !answers[q.id])}
                                className="bg-green-600 hover:bg-green-700 text-white px-8 py-2"
                            >
                                <Send className="h-4 w-4 mr-2" />
                                {isSubmitting ? 'جاري الإرسال...' : 'إرسال التقييم'}
                            </Button>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
}
