'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { InteractiveQuestion, ReflectionConfig, ReflectionQuestion, EmojiOption } from '@/types';
import { MessageSquare, Heart, CheckCircle, User, BarChart3 } from 'lucide-react';

interface MiniSurveyReflectionProps {
  question: InteractiveQuestion;
  questionIndex: number;
  onAnswerChange: (answer: any) => void;
  adminLanguage: string;
}

export default function MiniSurveyReflection({
  question,
  questionIndex,
  onAnswerChange,
  adminLanguage
}: MiniSurveyReflectionProps) {
  const config = question.reflectionConfig as ReflectionConfig;
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  const [answers, setAnswers] = useState<{ [questionId: string]: any }>({});
  const [comments, setComments] = useState<{ [questionId: string]: string }>({});
  const [isCompleted, setIsCompleted] = useState(false);
  const [showResults, setShowResults] = useState(false);

  const currentQuestion = config.questions[currentQuestionIndex];
  const isLastQuestion = currentQuestionIndex === config.questions.length - 1;

  useEffect(() => {
    // Check if all required questions are answered
    const requiredQuestions = config.questions.filter(q => q.required);
    const answeredRequired = requiredQuestions.filter(q => answers[q.id] !== undefined);
    setIsCompleted(answeredRequired.length === requiredQuestions.length);
  }, [answers, config.questions]);

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

  const handleCommentChange = (questionId: string, comment: string) => {
    setComments(prev => ({
      ...prev,
      [questionId]: comment
    }));
  };

  const handleNext = () => {
    if (isLastQuestion) {
      handleSubmit();
    } else {
      setCurrentQuestionIndex(prev => prev + 1);
    }
  };

  const handlePrevious = () => {
    if (currentQuestionIndex > 0) {
      setCurrentQuestionIndex(prev => prev - 1);
    }
  };

  const handleSubmit = () => {
    const result = {
      answers,
      comments: config.allowComments ? comments : {},
      totalQuestions: config.questions.length,
      answeredQuestions: Object.keys(answers).length,
      completionRate: (Object.keys(answers).length / config.questions.length) * 100,
      categoryBreakdown: getCategoryBreakdown(),
      averageRating: getAverageRating(),
      isAnonymous: config.isAnonymous
    };

    onAnswerChange(result);
    setShowResults(true);
  };

  const getCategoryBreakdown = () => {
    const breakdown: { [category: string]: { total: number; average: number; count: number } } = {};
    
    config.questions.forEach(q => {
      if (answers[q.id] !== undefined) {
        if (!breakdown[q.category]) {
          breakdown[q.category] = { total: 0, average: 0, count: 0 };
        }
        breakdown[q.category].total += answers[q.id];
        breakdown[q.category].count += 1;
      }
    });

    Object.keys(breakdown).forEach(category => {
      breakdown[category].average = breakdown[category].total / breakdown[category].count;
    });

    return breakdown;
  };

  const getAverageRating = () => {
    const values = Object.values(answers) as number[];
    if (values.length === 0) return 0;
    return values.reduce((sum, val) => sum + val, 0) / values.length;
  };

  const getEmojiForValue = (value: number): EmojiOption | undefined => {
    return config.emojiScale?.options.find(option => option.value === value);
  };

  const getCategoryIcon = (category: string) => {
    switch (category) {
      case 'self-assessment': return <User className="w-4 h-4" />;
      case 'experience': return <Heart className="w-4 h-4" />;
      case 'preference': return <CheckCircle className="w-4 h-4" />;
      case 'behavior': return <BarChart3 className="w-4 h-4" />;
      default: return <MessageSquare className="w-4 h-4" />;
    }
  };

  const getCategoryName = (category: string) => {
    const names: { [key: string]: string } = {
      'self-assessment': 'Penilaian Diri',
      'experience': 'Pengalaman',
      'preference': 'Preferensi',
      'behavior': 'Perilaku'
    };
    return names[category] || category;
  };

  if (showResults) {
    const categoryBreakdown = getCategoryBreakdown();
    const averageRating = getAverageRating();

    return (
      <Card className="w-full max-w-3xl mx-auto">
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <MessageSquare className="w-5 h-5 text-blue-500" />
            Hasil Refleksi Diri
          </CardTitle>
        </CardHeader>

        <CardContent className="space-y-6">
          {/* Overall Summary */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div className="text-center p-4 bg-blue-50 rounded-lg">
              <div className="text-2xl font-bold text-blue-600">
                {Object.keys(answers).length}/{config.questions.length}
              </div>
              <p className="text-sm text-gray-600">Pertanyaan Dijawab</p>
            </div>
            
            <div className="text-center p-4 bg-green-50 rounded-lg">
              <div className="text-2xl font-bold text-green-600">
                {averageRating.toFixed(1)}
              </div>
              <p className="text-sm text-gray-600">Rata-rata Skor</p>
            </div>
            
            <div className="text-center p-4 bg-purple-50 rounded-lg">
              <div className="text-2xl font-bold text-purple-600">
                {Math.round((Object.keys(answers).length / config.questions.length) * 100)}%
              </div>
              <p className="text-sm text-gray-600">Tingkat Kelengkapan</p>
            </div>
          </div>

          {/* Category Breakdown */}
          <div>
            <h3 className="font-semibold mb-3">📊 Breakdown per Kategori:</h3>
            <div className="space-y-3">
              {Object.entries(categoryBreakdown).map(([category, data]) => (
                <div key={category} className="p-3 bg-gray-50 rounded-lg">
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      {getCategoryIcon(category)}
                      <span className="font-medium">{getCategoryName(category)}</span>
                    </div>
                    <Badge variant="outline">
                      {data.average.toFixed(1)} / {config.emojiScale?.options.length || 5}
                    </Badge>
                  </div>
                  
                  <div className="flex items-center gap-1">
                    {config.emojiScale?.options.map((option, index) => (
                      <div
                        key={index}
                        className={`
                          flex-1 h-2 rounded-full transition-all duration-300
                          ${data.average >= option.value ? 'bg-blue-500' : 'bg-gray-200'}
                        `}
                      />
                    ))}
                  </div>
                  
                  <p className="text-xs text-gray-500 mt-1">
                    {data.count} pertanyaan • Rata-rata: {getEmojiForValue(Math.round(data.average))?.emoji} {getEmojiForValue(Math.round(data.average))?.label}
                  </p>
                </div>
              ))}
            </div>
          </div>

          {/* Individual Answers */}
          <div>
            <h3 className="font-semibold mb-3">📝 Ringkasan Jawaban:</h3>
            <div className="space-y-3 max-h-60 overflow-y-auto">
              {config.questions.map((q) => (
                answers[q.id] !== undefined && (
                  <div key={q.id} className="p-3 border rounded-lg">
                    <div className="flex items-start justify-between gap-3">
                      <div className="flex-1">
                        <p className="text-sm font-medium">{q.question}</p>
                        {q.description && (
                          <p className="text-xs text-gray-500 mt-1">{q.description}</p>
                        )}
                        {config.allowComments && comments[q.id] && (
                          <p className="text-xs text-blue-600 mt-2 italic">
                            "{comments[q.id]}"
                          </p>
                        )}
                      </div>
                      <div className="text-center">
                        <div className="text-2xl mb-1">
                          {getEmojiForValue(answers[q.id])?.emoji}
                        </div>
                        <Badge variant="outline" className="text-xs">
                          {getEmojiForValue(answers[q.id])?.label}
                        </Badge>
                      </div>
                    </div>
                  </div>
                )
              ))}
            </div>
          </div>

          {/* Insights */}
          <div className="p-4 bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg border">
            <h3 className="font-semibold mb-2">💡 Insight:</h3>
            <p className="text-sm text-gray-700">
              {averageRating >= 4 ? 
                "Anda menunjukkan tingkat kepercayaan diri dan kepuasan yang tinggi dalam area yang dinilai. Pertahankan momentum positif ini!" :
                averageRating >= 3 ?
                "Anda berada di jalur yang baik dengan ruang untuk perbaikan di beberapa area. Fokus pada pengembangan berkelanjutan." :
                "Ada beberapa area yang mungkin memerlukan perhatian lebih. Ini adalah kesempatan bagus untuk pertumbuhan dan pembelajaran."
              }
            </p>
          </div>

          {config.isAnonymous && (
            <div className="text-center text-xs text-gray-500 bg-gray-50 p-2 rounded">
              🔒 Jawaban Anda bersifat anonim dan akan digunakan untuk analisis agregat saja.
            </div>
          )}
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-2xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <MessageSquare className="w-5 h-5 text-blue-500" />
            Mini Survey Reflection
          </span>
          <Badge variant="outline">
            {currentQuestionIndex + 1} / {config.questions.length}
          </Badge>
        </CardTitle>
        
        {/* Progress Bar */}
        <div className="w-full bg-gray-200 rounded-full h-2">
          <div 
            className="bg-blue-600 h-2 rounded-full transition-all duration-300"
            style={{ width: `${((currentQuestionIndex + 1) / config.questions.length) * 100}%` }}
          />
        </div>
      </CardHeader>

      <CardContent className="space-y-6">
        {/* Current Question */}
        <div className="space-y-4">
          <div className="flex items-start gap-3">
            {getCategoryIcon(currentQuestion.category)}
            <div className="flex-1">
              <Badge variant="outline" className="mb-2 text-xs">
                {getCategoryName(currentQuestion.category)}
              </Badge>
              <h3 className="font-semibold text-lg mb-2">
                {currentQuestion.question}
              </h3>
              {currentQuestion.description && (
                <p className="text-sm text-gray-600 mb-4">
                  {currentQuestion.description}
                </p>
              )}
              {currentQuestion.required && (
                <Badge variant="destructive" className="text-xs">
                  Wajib dijawab
                </Badge>
              )}
            </div>
          </div>

          {/* Emoji Scale */}
          {config.scaleType === 'emoji' && config.emojiScale && (
            <div className="space-y-4">
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                {config.emojiScale.options.map((option) => (
                  <Button
                    key={option.value}
                    variant={answers[currentQuestion.id] === option.value ? "default" : "outline"}
                    className={`
                      h-auto p-4 flex flex-col items-center gap-2 transition-all duration-200
                      ${answers[currentQuestion.id] === option.value ? 
                        'bg-blue-600 hover:bg-blue-700 scale-105' : 
                        'hover:bg-blue-50 hover:border-blue-300 hover:scale-105'
                      }
                    `}
                    onClick={() => handleEmojiSelect(currentQuestion.id, option.value)}
                  >
                    <span className="text-3xl">{option.emoji}</span>
                    {config.emojiScale?.showLabels && (
                      <span className="text-xs font-medium text-center">
                        {option.label}
                      </span>
                    )}
                    {option.description && (
                      <span className="text-xs text-center opacity-75">
                        {option.description}
                      </span>
                    )}
                  </Button>
                ))}
              </div>

              {/* Selected Value Display */}
              {answers[currentQuestion.id] !== undefined && (
                <div className="text-center p-3 bg-blue-50 rounded-lg">
                  <p className="text-sm text-gray-600">Pilihan Anda:</p>
                  <div className="flex items-center justify-center gap-2 mt-1">
                    <span className="text-2xl">
                      {getEmojiForValue(answers[currentQuestion.id])?.emoji}
                    </span>
                    <span className="font-medium">
                      {getEmojiForValue(answers[currentQuestion.id])?.label}
                    </span>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Comment Section */}
          {config.allowComments && (
            <div className="space-y-2">
              <label className="text-sm font-medium text-gray-700">
                Komentar tambahan (opsional):
              </label>
              <textarea
                className="w-full p-3 border rounded-lg resize-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                rows={3}
                placeholder="Bagikan pemikiran atau pengalaman Anda terkait pertanyaan ini..."
                value={comments[currentQuestion.id] || ''}
                onChange={(e) => handleCommentChange(currentQuestion.id, e.target.value)}
              />
            </div>
          )}
        </div>

        {/* Navigation */}
        <div className="flex justify-between items-center pt-4 border-t">
          <Button
            variant="outline"
            onClick={handlePrevious}
            disabled={currentQuestionIndex === 0}
          >
            Sebelumnya
          </Button>

          <div className="text-center text-sm">
            <div className="text-gray-500 mb-1">
              {Object.keys(answers).length} dari {config.questions.length} pertanyaan dijawab
            </div>
            {isLastQuestion && !isCompleted && (
              <div className="text-red-500 text-xs">
                Selesaikan semua pertanyaan wajib untuk melanjutkan
              </div>
            )}
            {isLastQuestion && isCompleted && (
              <div className="text-green-600 text-xs">
                ✓ Siap untuk menyelesaikan refleksi
              </div>
            )}
          </div>

          {isLastQuestion ? (
            <Button
              onClick={handleNext}
              disabled={!isCompleted}
              className={`${
                isCompleted 
                  ? 'bg-green-600 hover:bg-green-700' 
                  : 'bg-gray-400 cursor-not-allowed'
              }`}
            >
              {isCompleted ? '✓ Selesai' : 'Jawab Pertanyaan Wajib'}
            </Button>
          ) : (
            <Button
              onClick={handleNext}
              disabled={currentQuestion.required && answers[currentQuestion.id] === undefined}
              className="bg-blue-600 hover:bg-blue-700"
            >
              Selanjutnya
            </Button>
          )}
        </div>

        {/* Instructions */}
        <div className="text-center text-xs text-gray-500 bg-gray-50 p-3 rounded">
          💡 Jawab dengan jujur berdasarkan pengalaman dan perasaan Anda. 
          {config.isAnonymous && " Semua jawaban bersifat anonim."}
        </div>
      </CardContent>
    </Card>
  );
}