"use client";

import { useState } from "react";
import { Question } from "@/types/quiz";

const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

interface QuestionRendererProps {
  question: Question;
  selectedAnswers: string[];
  onAnswerChange: (answers: string[]) => void;
  disabled?: boolean;
  variant?: "classmaker" | "modern";
  showFeedback?: boolean;
}

function OpenEndedRenderer({
  value,
  onChange,
  disabled,
  showFeedback,
  expectedAnswers,
}: {
  value: string;
  onChange: (v: string) => void;
  disabled: boolean;
  showFeedback: boolean;
  expectedAnswers: string[];
}) {
  const [hintVisible, setHintVisible] = useState(false);
  return (
    <div className="space-y-3">
      <textarea
        value={value}
        onChange={(e) => onChange(e.target.value)}
        disabled={disabled}
        placeholder="Напишете го вашиот одговор овде..."
        rows={4}
        className="w-full px-3 py-2 border border-gray-300 rounded-lg text-gray-900 text-sm resize-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none disabled:bg-gray-50 disabled:text-gray-500"
      />
      {showFeedback && expectedAnswers.length > 0 && (
        <div>
          <button
            onClick={() => setHintVisible((v) => !v)}
            className="text-sm text-blue-600 hover:text-blue-800 underline"
          >
            {hintVisible ? "Скриј го очекуваниот одговор" : "Прикажи очекуван одговор"}
          </button>
          {hintVisible && (
            <div className="mt-2 p-3 bg-blue-50 border border-blue-200 rounded-lg">
              {expectedAnswers.map((ans, i) => (
                <p key={i} className="text-sm text-blue-900">{ans}</p>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default function QuestionRenderer({
  question,
  selectedAnswers,
  onAnswerChange,
  disabled = false,
  variant = "classmaker",
  showFeedback = false,
}: QuestionRendererProps) {
  function handleSingleSelect(optionId: string) {
    if (disabled) return;
    onAnswerChange([optionId]);
  }

  function handleMultiSelect(optionId: string) {
    if (disabled) return;
    const has = selectedAnswers.includes(optionId);
    if (has) {
      onAnswerChange(selectedAnswers.filter((a) => a !== optionId));
    } else {
      onAnswerChange([...selectedAnswers, optionId]);
    }
  }

  // Multiple-dropdown helpers
  function getSubAnswer(subId: string): string {
    const entry = selectedAnswers.find((a) => a.startsWith(subId + ":"));
    return entry ? entry.split(":")[1] : "";
  }

  function handleSubDropdownChange(subId: string, optionId: string) {
    if (disabled) return;
    const filtered = selectedAnswers.filter((a) => !a.startsWith(subId + ":"));
    if (optionId) {
      onAnswerChange([...filtered, `${subId}:${optionId}`]);
    } else {
      onAnswerChange(filtered);
    }
  }

  if (variant === "classmaker") {
    return (
      <div className="space-y-6">
        {question.imageUrl && (
          <img
            src={question.imageUrl}
            alt="Question illustration"
            className="max-w-full rounded-lg border border-gray-200"
          />
        )}
        <p className="text-base text-gray-800 leading-relaxed">
          {question.text}
        </p>

        {question.type === "open-ended" ? (
          <OpenEndedRenderer
            value={selectedAnswers[0] || ""}
            onChange={(v) => onAnswerChange(v ? [v] : [])}
            disabled={disabled}
            showFeedback={showFeedback}
            expectedAnswers={question.correctAnswers}
          />
        ) : question.type === "multiple-dropdown" ? (
          <div className="divide-y divide-gray-200">
            {(question.subQuestions || []).map((sq) => {
              const selected = getSubAnswer(sq.id);
              const isCorrect = selected === sq.correctOptionId;
              const correctOpt = (sq.options || []).find((o) => o.id === sq.correctOptionId);

              return (
                <div key={sq.id} className="flex items-center justify-between gap-4 py-4">
                  <div className="flex items-center gap-3 flex-1">
                    {sq.imageUrl && (
                      <img
                        src={sq.imageUrl}
                        alt={sq.text}
                        className="w-20 h-20 object-contain flex-shrink-0 rounded border border-gray-200"
                      />
                    )}
                    <p className="text-sm text-gray-800">{sq.text}</p>
                  </div>
                  <div className="flex-shrink-0 w-56">
                    <select
                      value={selected}
                      onChange={(e) => handleSubDropdownChange(sq.id, e.target.value)}
                      disabled={disabled || showFeedback}
                      className={`w-full px-3 py-2.5 bg-white border rounded-lg text-gray-900 text-sm focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none ${
                        showFeedback
                          ? selected
                            ? isCorrect
                              ? "border-green-500 bg-green-50"
                              : "border-red-500 bg-red-50"
                            : "border-gray-300"
                          : "border-gray-300"
                      }`}
                    >
                      <option value="">Select</option>
                      {(sq.options || []).map((opt) => (
                        <option key={opt.id} value={opt.id}>{opt.label}</option>
                      ))}
                    </select>
                    {showFeedback && selected && !isCorrect && correctOpt && (
                      <p className="mt-1 text-xs text-green-700">Correct: {correctOpt.label}</p>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        ) : question.type === "dropdown" ? (
          <div>
            <select
              value={selectedAnswers[0] || ""}
              onChange={(e) => onAnswerChange(e.target.value ? [e.target.value] : [])}
              disabled={disabled || showFeedback}
              className={`w-full px-4 py-3 bg-white border rounded-lg text-gray-900 focus:border-blue-500 focus:ring-1 focus:ring-blue-500 outline-none ${
                showFeedback
                  ? selectedAnswers.length > 0 && question.correctAnswers.includes(selectedAnswers[0])
                    ? "border-green-500 bg-green-50"
                    : selectedAnswers.length > 0
                    ? "border-red-500 bg-red-50"
                    : "border-gray-300"
                  : "border-gray-300"
              }`}
            >
              <option value="">Select an answer...</option>
              {question.options.map((option, i) => (
                <option key={option.id} value={option.id}>
                  {LETTERS[i]}. {option.label}
                </option>
              ))}
            </select>
            {showFeedback && (
              <p className="mt-2 text-sm font-medium text-green-700">
                Correct answer: {question.correctAnswers.map((id) => {
                  const idx = question.options.findIndex((o) => o.id === id);
                  const opt = question.options[idx];
                  return opt ? `${LETTERS[idx]}. ${opt.label}` : id;
                }).join(", ")}
              </p>
            )}
          </div>
        ) : (
          <div className={question.options.some((o) => o.imageUrl) ? "grid grid-cols-2 gap-3 sm:grid-cols-3" : "space-y-4"}>
            {question.options.map((option, i) => {
              const isSelected = selectedAnswers.includes(option.id);
              const isMulti = question.type === "multiple-answer";
              const isCorrectOption = question.correctAnswers.includes(option.id);

              let borderColor = "border-gray-400";
              let bgColor = "";
              let radioColor = isSelected ? "border-blue-600 bg-blue-600" : "border-gray-400";

              if (showFeedback) {
                if (isCorrectOption) {
                  borderColor = "border-green-500";
                  bgColor = "bg-green-50";
                  if (isSelected) radioColor = "border-green-600 bg-green-600";
                } else if (isSelected) {
                  borderColor = "border-red-400";
                  bgColor = "bg-red-50";
                  radioColor = "border-red-500 bg-red-500";
                }
              }

              return (
                <button
                  key={option.id}
                  onClick={() =>
                    isMulti
                      ? handleMultiSelect(option.id)
                      : handleSingleSelect(option.id)
                  }
                  disabled={disabled || showFeedback}
                  className={`w-full text-left py-3 px-3 rounded-lg transition-colors ${bgColor} ${
                    showFeedback ? (isCorrectOption || isSelected ? `border ${borderColor}` : "") : ""
                  } ${
                    (disabled || showFeedback) ? "cursor-default" : "cursor-pointer"
                  }`}
                >
                  {option.imageUrl && (
                    <img
                      src={option.imageUrl}
                      alt={option.label}
                      className="w-full max-h-40 object-contain rounded mb-2"
                    />
                  )}
                  <div className="flex items-center gap-3">
                    <div
                      className={`w-6 h-6 flex items-center justify-center border-2 flex-shrink-0 ${
                        isMulti ? "rounded" : "rounded-full"
                      } ${radioColor}`}
                    >
                      {isSelected && !isMulti && (
                        <div className="w-2.5 h-2.5 rounded-full bg-white" />
                      )}
                      {isSelected && isMulti && (
                        <span className="text-xs text-white font-bold">&#10003;</span>
                      )}
                    </div>
                    <span className="text-sm text-gray-800">
                      <span className="font-bold">{LETTERS[i]}.</span>{" "}
                      {option.label}
                    </span>
                    {showFeedback && isCorrectOption && (
                      <span className="ml-auto text-green-600 text-xs font-semibold">Correct</span>
                    )}
                    {showFeedback && isSelected && !isCorrectOption && (
                      <span className="ml-auto text-red-600 text-xs font-semibold">Wrong</span>
                    )}
                  </div>
                </button>
              );
            })}
          </div>
        )}

        {question.type === "multiple-answer" && !showFeedback && (
          <p className="text-xs text-gray-500">Select all that apply</p>
        )}
      </div>
    );
  }

  /* Modern variant */
  return (
    <div className="space-y-5">
      {question.imageUrl && (
        <img
          src={question.imageUrl}
          alt="Question illustration"
          className="max-w-full rounded-lg border border-gray-200"
        />
      )}
      <h2 className="text-base font-semibold text-gray-900 leading-relaxed">
        {question.text}
      </h2>

      {question.type === "open-ended" ? (
        <OpenEndedRenderer
          value={selectedAnswers[0] || ""}
          onChange={(v) => onAnswerChange(v ? [v] : [])}
          disabled={disabled}
          showFeedback={showFeedback}
          expectedAnswers={question.correctAnswers}
        />
      ) : question.type === "multiple-dropdown" ? (
        <div className="divide-y divide-gray-200">
          {(question.subQuestions || []).map((sq) => {
            const selected = getSubAnswer(sq.id);
            const isCorrect = selected === sq.correctOptionId;
            const correctOpt = (sq.options || []).find((o) => o.id === sq.correctOptionId);

            return (
              <div key={sq.id} className="flex items-center justify-between gap-4 py-4">
                <div className="flex items-center gap-3 flex-1">
                  {sq.imageUrl && (
                    <img
                      src={sq.imageUrl}
                      alt={sq.text}
                      className="w-20 h-20 object-contain flex-shrink-0 rounded border border-gray-200"
                    />
                  )}
                  <p className="text-sm text-gray-800">{sq.text}</p>
                </div>
                <div className="flex-shrink-0 w-56">
                  <select
                    value={selected}
                    onChange={(e) => handleSubDropdownChange(sq.id, e.target.value)}
                    disabled={disabled || showFeedback}
                    className={`w-full px-3 py-2.5 bg-white border rounded text-gray-900 text-sm focus:border-[#2b579a] focus:ring-1 focus:ring-[#2b579a] outline-none ${
                      showFeedback
                        ? selected
                          ? isCorrect
                            ? "border-green-500 bg-green-50"
                            : "border-red-500 bg-red-50"
                          : "border-gray-300"
                        : "border-gray-300"
                    }`}
                  >
                    <option value="">Select</option>
                    {(sq.options || []).map((opt) => (
                      <option key={opt.id} value={opt.id}>{opt.label}</option>
                    ))}
                  </select>
                  {showFeedback && selected && !isCorrect && correctOpt && (
                    <p className="mt-1 text-xs text-green-700">Correct: {correctOpt.label}</p>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      ) : question.type === "dropdown" ? (
        <div>
          <select
            value={selectedAnswers[0] || ""}
            onChange={(e) => onAnswerChange(e.target.value ? [e.target.value] : [])}
            disabled={disabled || showFeedback}
            className={`w-full px-4 py-3 bg-white border rounded text-gray-900 focus:border-[#2b579a] focus:ring-1 focus:ring-[#2b579a] outline-none ${
              showFeedback
                ? selectedAnswers.length > 0 && question.correctAnswers.includes(selectedAnswers[0])
                  ? "border-green-500 bg-green-50"
                  : selectedAnswers.length > 0
                  ? "border-red-500 bg-red-50"
                  : "border-gray-300"
                : "border-gray-300"
            }`}
          >
            <option value="">Select an answer...</option>
            {question.options.map((option) => (
              <option key={option.id} value={option.id}>
                {option.label}
              </option>
            ))}
          </select>
          {showFeedback && (
            <p className="mt-2 text-sm font-medium text-green-700">
              Correct answer: {question.correctAnswers.map((id) => {
                const opt = question.options.find((o) => o.id === id);
                return opt ? opt.label : id;
              }).join(", ")}
            </p>
          )}
        </div>
      ) : (
        <div className={question.options.some((o) => o.imageUrl) ? "grid grid-cols-2 gap-3 sm:grid-cols-3" : "space-y-2"}>
          {question.options.map((option) => {
            const isSelected = selectedAnswers.includes(option.id);
            const isMulti = question.type === "multiple-answer";
            const isCorrectOption = question.correctAnswers.includes(option.id);

            let borderStyle = isSelected
              ? "border-[#2b579a] bg-blue-50 text-gray-900"
              : "border-gray-300 bg-white text-gray-700 hover:border-gray-400 hover:bg-gray-50";
            let indicatorStyle = isSelected ? "border-[#2b579a] bg-[#2b579a]" : "border-gray-400";

            if (showFeedback) {
              if (isCorrectOption) {
                borderStyle = "border-green-500 bg-green-50 text-gray-900";
                if (isSelected) indicatorStyle = "border-green-600 bg-green-600";
                else indicatorStyle = "border-green-400";
              } else if (isSelected) {
                borderStyle = "border-red-400 bg-red-50 text-gray-900";
                indicatorStyle = "border-red-500 bg-red-500";
              } else {
                borderStyle = "border-gray-300 bg-white text-gray-700";
              }
            }

            return (
              <button
                key={option.id}
                onClick={() =>
                  isMulti
                    ? handleMultiSelect(option.id)
                    : handleSingleSelect(option.id)
                }
                disabled={disabled || showFeedback}
                className={`w-full text-left px-4 py-3 rounded border transition-colors ${borderStyle} ${
                  (disabled || showFeedback) ? "cursor-default" : "cursor-pointer"
                }`}
              >
                {option.imageUrl && (
                  <img
                    src={option.imageUrl}
                    alt={option.label}
                    className="w-full max-h-40 object-contain rounded mb-2"
                  />
                )}
                <div className="flex items-center gap-3">
                  <div
                    className={`w-5 h-5 flex items-center justify-center border-2 flex-shrink-0 ${
                      isMulti ? "rounded" : "rounded-full"
                    } ${indicatorStyle}`}
                  >
                    {isSelected && <span className="text-xs text-white">&#10003;</span>}
                  </div>
                  <span className="text-sm">{option.label}</span>
                  {showFeedback && isCorrectOption && (
                    <span className="ml-auto text-green-600 text-xs font-semibold">Correct</span>
                  )}
                  {showFeedback && isSelected && !isCorrectOption && (
                    <span className="ml-auto text-red-600 text-xs font-semibold">Wrong</span>
                  )}
                </div>
              </button>
            );
          })}
        </div>
      )}

      {question.type === "multiple-answer" && !showFeedback && (
        <p className="text-xs text-gray-500">Select all that apply</p>
      )}
    </div>
  );
}
