import React, { useState } from "react";
import {
  Loader2,
  BrainCircuit,
  CheckCircle,
  XCircle,
  RefreshCw,
} from "lucide-react";
import { generateSampleQuestion } from "@/services/apiService";

export const DemoWidget: React.FC = () => {
  const [topic, setTopic] = useState("TNPSC General Knowledge");
  const [question, setQuestion] = useState<any | null>(null);
  const [loading, setLoading] = useState(false);
  const [selectedOption, setSelectedOption] = useState<number | null>(null);
  const [isCorrect, setIsCorrect] = useState<boolean | null>(null);

  const handleGenerate = async () => {
    setLoading(true);
    setQuestion(null);
    setSelectedOption(null);
    setIsCorrect(null);
    const result = await generateSampleQuestion(topic);
    setQuestion(result);
    setLoading(false);
  };

  const handleOptionSelect = (index: number) => {
    if (selectedOption !== null) return;
    setSelectedOption(index);
    if (question) {
      setIsCorrect(index === question.correctAnswerIndex);
    }
  };

  return (
    <div className="bg-white rounded-2xl shadow-xl overflow-hidden border border-gray-100 max-w-2xl mx-auto">
      <div className="bg-brand-navy p-6 text-white">
        <div className="flex items-center gap-2 mb-2">
          <BrainCircuit className="w-6 h-6 text-brand-orange" />
          <h3 className="font-bold text-lg">AI Question Engine Demo</h3>
        </div>
        <p className="text-blue-100 text-sm">
          Explore how our AI-powered question engine generates practice
          questions based on selected topics.
        </p>
      </div>

      <div className="p-6">
        {!question && !loading && (
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Enter a Topic
              </label>
              <div className="flex gap-2 flex-wrap">
                <input
                  type="text"
                  value={topic}
                  onChange={(e) => setTopic(e.target.value)}
                  className="flex-1 border border-gray-300 rounded-[8px] px-4 py-2 focus:ring-2 focus:ring-brand-green focus:border-transparent outline-none"
                  placeholder="e.g. Physics, History, Math"
                />
                <button
                  onClick={handleGenerate}
                  className="bg-brand-green hover:bg-green-600 text-white px-6 py-2 rounded-[8px] font-medium transition-colors"
                >
                  Generate
                </button>
              </div>
            </div>

            <div className="bg-brand-light p-4 rounded-lg border border-green-100">
              <p className="text-sm text-green-800">
                <span className="font-bold mr-2">Note :</span>
                AI-assist tools support efficient question creation and
                assessment configuration institutions.
              </p>
            </div>
          </div>
        )}

        {loading && (
          <div className="py-12 flex flex-col items-center justify-center text-gray-500">
            <Loader2 className="w-10 h-10 animate-spin text-brand-orange mb-3" />
            <p>Generating a challenging question...</p>
          </div>
        )}

        {question && (
          <div className="animate-fade-in">
            <pre className="text-md text-wrap mb-4 font-Inter">
              {question.question}
            </pre>

            <div className="space-y-3 mb-6">
              {question.options.map((option, idx) => {
                let cardClass =
                  "w-full text-left p-4 rounded-lg border-2 transition-all duration-200 flex items-center justify-between ";

                if (selectedOption === null) {
                  cardClass +=
                    "border-gray-100 hover:border-brand-navy hover:bg-slate-50";
                } else {
                  if (idx === question.correctAnswerIndex) {
                    cardClass += "border-green-500 bg-green-50 text-green-800";
                  } else if (
                    selectedOption === idx &&
                    idx !== question.correctAnswerIndex
                  ) {
                    cardClass += "border-red-500 bg-red-50 text-red-800";
                  } else {
                    cardClass += "border-gray-100 opacity-50";
                  }
                }

                return (
                  <button
                    key={idx}
                    onClick={() => handleOptionSelect(idx)}
                    disabled={selectedOption !== null}
                    className={cardClass}
                  >
                    <pre className="font-medium text-wrap text-sm">
                      <b>{String.fromCharCode(65 + idx)}</b>. {option}
                    </pre>
                    {selectedOption !== null &&
                      idx === question.correctAnswerIndex && (
                        <CheckCircle className="w-5 h-5 text-green-600" />
                      )}
                    {selectedOption !== null &&
                      selectedOption === idx &&
                      idx !== question.correctAnswerIndex && (
                        <XCircle className="w-5 h-5 text-red-600" />
                      )}
                  </button>
                );
              })}
            </div>

            {selectedOption !== null && (
              <div className="bg-slate-50 p-4 rounded-lg border border-slate-200 mb-4">
                <p className="font-semibold text-slate-900 mb-1">
                  Explanation:
                </p>
                <pre className="text-slate-600 text-sm leading-relaxed text-md text-wrap">
                  {question.explanation}
                </pre>
              </div>
            )}

            <button
              onClick={handleGenerate}
              className="flex items-center justify-center gap-2 w-full py-2.5 text-brand-navy font-semibold hover:bg-slate-50 rounded-lg transition-colors border border-dashed border-gray-300"
            >
              <RefreshCw className="w-4 h-4" />
              Try Another Question
            </button>
          </div>
        )}
      </div>
    </div>
  );
};
