"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { cn } from "@/lib/utils";
import {
  Clock, Volume2, VolumeX, Mic, MicOff, CheckCircle,
  Code as CodeIcon, Star, Square, Play, Pause,
  Upload, X as XIcon, FileText, Image as ImageIcon,
} from "lucide-react";
import type { QuestionBuilderItem } from "@/types";
import type { AnswerValue } from "@/types";
import { ImageAnnotator } from "./image-annotator";

interface QuestionPlayerProps {
  question: QuestionBuilderItem;
  onAnswer: (answer: AnswerValue) => void;
  previewMode?: boolean;
  currentAnswer?: AnswerValue;
}

export function QuestionPlayer({
  question,
  onAnswer,
  previewMode = false,
  currentAnswer,
}: QuestionPlayerProps) {
  const [localAnswer, setLocalAnswer] = useState<AnswerValue>(currentAnswer || {});
  const [timeLeft, setTimeLeft] = useState(question.timeLimit || null);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  // TTS state
  const [isSpeaking, setIsSpeaking] = useState(false);
  const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);

  // Voice recording state
  const [isRecording, setIsRecording] = useState(false);
  const [isPlayingBack, setIsPlayingBack] = useState(false);
  const [isTranscribing, setIsTranscribing] = useState(false);
  const [recordingSeconds, setRecordingSeconds] = useState(0);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const audioChunksRef = useRef<Blob[]>([]);
  const audioBlobRef = useRef<Blob | null>(null);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const recordingTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);

  useEffect(() => {
    setLocalAnswer(currentAnswer || {});
    // Stop TTS on question change
    if (window.speechSynthesis?.speaking) {
      window.speechSynthesis.cancel();
      setIsSpeaking(false);
    }
  }, [question.id]);

  // Timer
  useEffect(() => {
    if (!question.timeLimit) return;
    setTimeLeft(question.timeLimit);
    intervalRef.current = setInterval(() => {
      setTimeLeft((prev) => {
        if (prev === null || prev <= 1) {
          if (intervalRef.current) clearInterval(intervalRef.current);
          if (!previewMode) onAnswer(localAnswer);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, [question.id, question.timeLimit]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (window.speechSynthesis?.speaking) window.speechSynthesis.cancel();
      if (recordingTimerRef.current) clearInterval(recordingTimerRef.current);
      if (audioRef.current) {
        audioRef.current.pause();
        audioRef.current = null;
      }
    };
  }, []);

  // --- TTS ---
  const handleSpeak = () => {
    if (!("speechSynthesis" in window)) return;
    if (isSpeaking) {
      window.speechSynthesis.cancel();
      setIsSpeaking(false);
      return;
    }
    const text = [
      String(question.title || ""),
      question.description ? String(question.description) : "",
    ]
      .filter(Boolean)
      .join(". ");
    const utterance = new SpeechSynthesisUtterance(text);
    utterance.rate = 0.95;
    utterance.onend = () => setIsSpeaking(false);
    utterance.onerror = () => setIsSpeaking(false);
    utteranceRef.current = utterance;
    setIsSpeaking(true);
    window.speechSynthesis.speak(utterance);
  };

  // --- Voice Recording ---
  const startRecording = async () => {
    try {
      const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
      const recorder = new MediaRecorder(stream);
      mediaRecorderRef.current = recorder;
      audioChunksRef.current = [];

      recorder.ondataavailable = (e) => {
        if (e.data.size > 0) audioChunksRef.current.push(e.data);
      };

      recorder.onstop = async () => {
        const blob = new Blob(audioChunksRef.current, { type: "audio/webm" });
        audioBlobRef.current = blob;
        const url = URL.createObjectURL(blob);
        audioRef.current = new Audio(url);
        audioRef.current.onended = () => setIsPlayingBack(false);

        // Optimistically update with the audio URL first
        const withAudio = { ...localAnswer, mediaUrl: url };
        setLocalAnswer(withAudio);
        if (!previewMode) onAnswer(withAudio);

        stream.getTracks().forEach((t) => t.stop());

        // Transcribe in background via Whisper
        setIsTranscribing(true);
        try {
          const fd = new FormData();
          fd.append("audio", new File([blob], "recording.webm", { type: "audio/webm" }));
          const res = await fetch("/api/ai/transcribe", { method: "POST", body: fd });
          if (res.ok) {
            const { transcript } = await res.json();
            if (transcript) {
              const withTranscript = { ...withAudio, mediaTranscript: transcript };
              setLocalAnswer(withTranscript);
              if (!previewMode) onAnswer(withTranscript as any);
            }
          }
        } catch {
          // Transcription is best-effort; the recording is still saved
        } finally {
          setIsTranscribing(false);
        }
      };

      recorder.start(250);
      setIsRecording(true);
      setRecordingSeconds(0);
      recordingTimerRef.current = setInterval(() => {
        setRecordingSeconds((s) => s + 1);
      }, 1000);
    } catch {
      // Permission denied or not available
    }
  };

  const stopRecording = () => {
    mediaRecorderRef.current?.stop();
    setIsRecording(false);
    if (recordingTimerRef.current) clearInterval(recordingTimerRef.current);
  };

  const togglePlayback = () => {
    if (!audioRef.current) return;
    if (isPlayingBack) {
      audioRef.current.pause();
      setIsPlayingBack(false);
    } else {
      audioRef.current.currentTime = 0;
      audioRef.current.play();
      setIsPlayingBack(true);
    }
  };

  const formatSeconds = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;

  // --- Handlers ---
  const handleTextChange = (value: string) => {
    const updated = { ...localAnswer, textValue: value };
    setLocalAnswer(updated);
    if (!previewMode) onAnswer(updated);
  };

  const handleOptionToggle = (optionId: string) => {
    const isMultiple = question.type === "MULTIPLE_CHOICE";
    let arrayValue: string[];
    if (isMultiple) {
      const current = localAnswer.arrayValue || [];
      arrayValue = current.includes(optionId)
        ? current.filter((id) => id !== optionId)
        : [...current, optionId];
    } else {
      arrayValue = [optionId];
    }
    const updated = { ...localAnswer, arrayValue };
    setLocalAnswer(updated);
    if (!previewMode) onAnswer(updated);
  };

  const handleNumericChange = (value: number) => {
    const updated = { ...localAnswer, numericValue: value };
    setLocalAnswer(updated);
    if (!previewMode) onAnswer(updated);
  };

  const renderQuestion = () => {
    switch (question.type) {
      case "MULTIPLE_CHOICE":
      case "SINGLE_CHOICE":
        return (
          <div className="space-y-3">
            {(question.options || []).map((option) => {
              const isSelected = (localAnswer.arrayValue || []).includes(option.id);
              return (
                <motion.button
                  key={option.id}
                  whileHover={{ x: 2 }}
                  whileTap={{ scale: 0.98 }}
                  onClick={() => handleOptionToggle(option.id)}
                  className={cn(
                    "w-full flex items-center gap-3 p-4 rounded-2xl border-2 text-left transition-all duration-200",
                    isSelected
                      ? "border-primary bg-primary/10 text-foreground"
                      : "border-border/50 hover:border-primary/40 hover:bg-accent/30",
                  )}
                >
                  <div
                    className={cn(
                      "h-5 w-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all",
                      question.type === "SINGLE_CHOICE" ? "rounded-full" : "rounded-md",
                      isSelected ? "border-primary bg-primary" : "border-muted-foreground/40",
                    )}
                  >
                    {isSelected && <CheckCircle className="h-3 w-3 text-white" />}
                  </div>
                  <span className="text-sm font-medium">{option.text}</span>
                </motion.button>
              );
            })}
          </div>
        );

      case "TEXT_SHORT":
      case "TEXT_LONG":
      case "ESSAY": {
        const rows = question.type === "TEXT_SHORT" ? 3 : question.type === "TEXT_LONG" ? 5 : 8;
        return (
          <Textarea
            value={localAnswer.textValue || ""}
            onChange={(e) => handleTextChange(e.target.value)}
            placeholder={String(question.placeholder || "Type your response here...")}
            rows={rows}
            className="w-full resize-none text-sm focus-visible:ring-primary"
          />
        );
      }

      case "RATING_SCALE": {
        const min = Number(question.minValue ?? 1);
        const max = Number(question.maxValue ?? 5);
        const stars = Array.from({ length: max - min + 1 }, (_, i) => i + min);
        return (
          <div className="flex items-center gap-2 flex-wrap">
            {stars.map((val) => {
              const isSelected = (localAnswer.numericValue || 0) >= val;
              return (
                <motion.button
                  key={val}
                  whileHover={{ scale: 1.2 }}
                  whileTap={{ scale: 0.9 }}
                  onClick={() => handleNumericChange(val)}
                  className={cn(
                    "transition-colors",
                    isSelected ? "text-amber-400" : "text-muted-foreground/30 hover:text-amber-300",
                  )}
                >
                  <Star className="h-8 w-8 fill-current" />
                </motion.button>
              );
            })}
            {localAnswer.numericValue && (
              <span className="text-sm text-muted-foreground ml-2">
                {localAnswer.numericValue}/{max}
              </span>
            )}
          </div>
        );
      }

      case "SLIDER":
        return (
          <div className="space-y-4">
            <label className="sr-only" htmlFor={`slider-${question.id}`}>
              {String(question.title)}
            </label>
            <input
              id={`slider-${question.id}`}
              type="range"
              min={Number(question.minValue ?? 0)}
              max={Number(question.maxValue ?? 100)}
              value={localAnswer.numericValue ?? Number(question.minValue ?? 0)}
              onChange={(e) => handleNumericChange(Number(e.target.value))}
              className="w-full accent-violet-500 cursor-pointer"
            />
            <div className="flex justify-between text-xs text-muted-foreground">
              <span>{Number(question.minValue ?? 0)}</span>
              <span className="font-semibold text-foreground text-base">
                {localAnswer.numericValue ?? Number(question.minValue ?? 0)}
              </span>
              <span>{Number(question.maxValue ?? 100)}</span>
            </div>
          </div>
        );

      case "CODE_EDITOR":
        return (
          <div className="rounded-xl border border-border overflow-hidden">
            <div className="flex items-center gap-2 px-3 py-2 bg-muted/50 border-b border-border">
              <CodeIcon className="h-3.5 w-3.5 text-muted-foreground" />
              <span className="text-xs text-muted-foreground font-mono">
                {String(question.codeLanguage || "javascript")}
              </span>
            </div>
            <Textarea
              value={localAnswer.codeValue || String(question.codeSnippet || "")}
              onChange={(e) => {
                const updated = { ...localAnswer, codeValue: e.target.value };
                setLocalAnswer(updated);
                if (!previewMode) onAnswer(updated);
              }}
              placeholder="// Write your code here..."
              rows={10}
              className="font-mono text-sm border-0 rounded-none focus-visible:ring-0"
            />
          </div>
        );

      case "VOICE_RECORDING":
        return (
          <div className="flex flex-col items-center gap-5 py-6">
            {/* Recording button */}
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={isRecording ? stopRecording : startRecording}
              className={cn(
                "h-20 w-20 rounded-full flex items-center justify-center transition-all duration-300 shadow-lg",
                isRecording
                  ? "bg-red-500 shadow-red-500/40 animate-pulse"
                  : "bg-violet-500 hover:bg-violet-600 shadow-violet-500/40",
              )}
            >
              {isRecording ? (
                <Square className="h-8 w-8 text-white fill-white" />
              ) : (
                <Mic className="h-8 w-8 text-white" />
              )}
            </motion.button>

            <div className="text-center">
              {isRecording ? (
                <p className="text-sm font-medium text-red-400">
                  Recording... {formatSeconds(recordingSeconds)}
                </p>
              ) : localAnswer.mediaUrl ? (
                <p className="text-sm text-muted-foreground">Recording ready &mdash; tap mic to re-record</p>
              ) : (
                <p className="text-sm text-muted-foreground">Tap the mic to start recording</p>
              )}
            </div>

            {/* Playback controls */}
            {localAnswer.mediaUrl && !isRecording && (
              <motion.div
                initial={{ opacity: 0, y: 6 }}
                animate={{ opacity: 1, y: 0 }}
                className="w-full max-w-xs space-y-2"
              >
                <div className="flex items-center gap-3 px-4 py-2.5 rounded-xl bg-muted/60 border border-border/50">
                  <button
                    type="button"
                    onClick={togglePlayback}
                    className="flex items-center gap-2 text-sm font-medium text-violet-400 hover:text-violet-300 transition-colors"
                  >
                    {isPlayingBack ? (
                      <><Pause className="h-4 w-4" /> Pause</>
                    ) : (
                      <><Play className="h-4 w-4" /> Play back</>
                    )}
                  </button>
                  <div className="flex items-center gap-1.5 text-xs text-green-400 ml-auto">
                    <CheckCircle className="h-3.5 w-3.5" />
                    Saved
                  </div>
                </div>
                {isTranscribing && (
                  <p className="text-xs text-muted-foreground flex items-center gap-1.5 px-1">
                    <span className="inline-block h-3 w-3 rounded-full border border-violet-400 border-t-transparent animate-spin" />
                    Transcribing…
                  </p>
                )}
                {!isTranscribing && (localAnswer as any).mediaTranscript && (
                  <div className="px-3 py-2 rounded-xl bg-muted/40 border border-border/40 text-xs text-muted-foreground leading-relaxed">
                    <span className="font-medium text-foreground block mb-1">Transcript</span>
                    {(localAnswer as any).mediaTranscript}
                  </div>
                )}
              </motion.div>
            )}
          </div>
        );

      case "FILE_UPLOAD":
        return (
          <FileUploadInput
            value={localAnswer.fileUrls || []}
            onChange={(urls) => {
              const updated = { ...localAnswer, fileUrls: urls };
              setLocalAnswer(updated);
              if (!previewMode) onAnswer(updated);
            }}
          />
        );

      case "RLHF_TASK":
      case "COMPARATIVE_RANKING":
        return (
          <div className="space-y-4">
            <p className="text-sm text-muted-foreground">
              Rank the following responses from best to worst by clicking to select your preference:
            </p>
            {(question.options || []).map((option, i) => {
              const isSelected = (localAnswer.arrayValue || [])[0] === option.id;
              return (
                <button
                  type="button"
                  key={option.id}
                  onClick={() => {
                    const updated = { ...localAnswer, arrayValue: [option.id] };
                    setLocalAnswer(updated);
                    if (!previewMode) onAnswer(updated);
                  }}
                  className={cn(
                    "w-full text-left p-4 rounded-2xl border-2 transition-all",
                    isSelected ? "border-primary bg-primary/10" : "border-border/50 hover:border-primary/30",
                  )}
                >
                  <div className="flex items-start gap-3">
                    <div
                      className={cn(
                        "h-6 w-6 rounded-full border-2 flex items-center justify-center shrink-0 text-xs font-bold",
                        isSelected
                          ? "border-primary bg-primary text-white"
                          : "border-muted-foreground/40 text-muted-foreground",
                      )}
                    >
                      {String.fromCharCode(65 + i)}
                    </div>
                    <p className="text-sm">{option.text}</p>
                  </div>
                </button>
              );
            })}
          </div>
        );

      case "ANNOTATION_TASK":
      case "IMAGE_BASED": {
        const imageUrl = question.imageUrl as string | undefined;
        if (!imageUrl) {
          return (
            <div className="rounded-xl border-2 border-dashed border-border/50 p-10 text-center">
              <p className="text-sm text-muted-foreground">No image provided for this question.</p>
            </div>
          );
        }
        return (
          <ImageAnnotator
            imageUrl={imageUrl}
            value={(localAnswer.jsonValue as any[]) || []}
            onChange={(annotations) => {
              const updated = { ...localAnswer, jsonValue: annotations };
              setLocalAnswer(updated);
              if (!previewMode) onAnswer(updated);
            }}
          />
        );
      }

      default:
        return (
          <Textarea
            value={localAnswer.textValue || ""}
            onChange={(e) => handleTextChange(e.target.value)}
            placeholder="Type your response..."
            rows={4}
          />
        );
    }
  };

  return (
    <div className="space-y-6">
      {/* Question header */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <Badge variant="secondary" className="text-xs">
            {question.type.replace(/_/g, " ")}
          </Badge>
          <div className="flex items-center gap-2">
            {/* TTS button */}
            {"speechSynthesis" in (typeof window !== "undefined" ? window : {}) && (
              <button
                type="button"
                onClick={handleSpeak}
                title={isSpeaking ? "Stop reading" : "Read question aloud"}
                className={cn(
                  "flex items-center gap-1 px-2 py-1 rounded-lg text-xs transition-all border",
                  isSpeaking
                    ? "bg-violet-500/20 text-violet-400 border-violet-500/40 animate-pulse"
                    : "text-muted-foreground border-border/40 hover:text-foreground hover:border-border",
                )}
              >
                {isSpeaking ? <VolumeX className="h-3.5 w-3.5" /> : <Volume2 className="h-3.5 w-3.5" />}
                {isSpeaking ? "Stop" : "Listen"}
              </button>
            )}
            {question.isRequired && (
              <span className="text-xs text-red-400">Required</span>
            )}
            {timeLeft !== null && (
              <div
                className={cn(
                  "flex items-center gap-1 text-sm font-mono font-semibold px-2 py-0.5 rounded-lg",
                  timeLeft < 10 ? "text-red-400 bg-red-500/10" : "text-muted-foreground bg-muted",
                )}
              >
                <Clock className="h-3.5 w-3.5" />
                {timeLeft}s
              </div>
            )}
          </div>
        </div>

        <h2 className="text-xl font-semibold leading-relaxed mb-2">{question.title}</h2>

        {question.description && (
          <p className="text-muted-foreground text-sm leading-relaxed">
            {question.description}
          </p>
        )}
      </div>

      {/* Timer bar */}
      {question.timeLimit && timeLeft !== null && (
        <Progress
          value={(timeLeft / question.timeLimit) * 100}
          className="h-1"
          indicatorClassName={cn(
            timeLeft < question.timeLimit * 0.2 ? "bg-red-500" : "bg-violet-500",
          )}
        />
      )}

      {/* Question content */}
      <AnimatePresence mode="wait">
        <motion.div
          key={question.id}
          initial={{ opacity: 0, x: 10 }}
          animate={{ opacity: 1, x: 0 }}
          exit={{ opacity: 0, x: -10 }}
          transition={{ duration: 0.2 }}
        >
          {renderQuestion()}
        </motion.div>
      </AnimatePresence>
    </div>
  );
}

// ─── File Upload sub-component ────────────────────────────────────────────────

function FileUploadInput({
  value,
  onChange,
}: {
  value: string[];
  onChange: (urls: string[]) => void;
}) {
  const [uploading, setUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const handleFiles = async (files: FileList | null) => {
    if (!files || files.length === 0) return;
    setError(null);
    setUploading(true);
    try {
      const fd = new FormData();
      Array.from(files).forEach((f) => fd.append("files", f));

      const res = await fetch("/api/upload", { method: "POST", body: fd });
      const json = await res.json();

      if (!res.ok) {
        setError(json.error || "Upload failed");
        return;
      }

      const newUrls: string[] = json.files.map((f: { url: string }) => f.url);
      onChange([...value, ...newUrls]);
    } catch {
      setError("Upload failed — please try again.");
    } finally {
      setUploading(false);
    }
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    handleFiles(e.dataTransfer.files);
  };

  const isImage = (url: string) => url.startsWith("data:image/");

  return (
    <div className="space-y-3">
      {/* Drop zone */}
      <div
        onDrop={handleDrop}
        onDragOver={(e) => e.preventDefault()}
        onClick={() => inputRef.current?.click()}
        className={cn(
          "border-2 border-dashed rounded-2xl p-8 text-center cursor-pointer transition-colors",
          uploading
            ? "border-primary/40 bg-primary/5"
            : "border-border/50 hover:border-primary/40 hover:bg-accent/20",
        )}
      >
        <input
          ref={inputRef}
          type="file"
          multiple
          className="sr-only"
          aria-label="Upload files"
          onChange={(e) => handleFiles(e.target.files)}
        />
        {uploading ? (
          <div className="flex flex-col items-center gap-2">
            <div className="h-8 w-8 rounded-full border-2 border-primary/30 border-t-primary animate-spin" />
            <p className="text-sm text-muted-foreground">Uploading…</p>
          </div>
        ) : (
          <>
            <Upload className="h-8 w-8 text-muted-foreground/40 mx-auto mb-3" />
            <p className="text-sm font-medium mb-1">Drop files here or click to upload</p>
            <p className="text-xs text-muted-foreground">Max 10 MB per file</p>
          </>
        )}
      </div>

      {error && <p className="text-xs text-red-400">{error}</p>}

      {/* Uploaded file list */}
      {value.length > 0 && (
        <div className="space-y-2">
          {value.map((url, i) => (
            <div
              key={i}
              className="flex items-center gap-3 p-2.5 rounded-xl border border-border/50 bg-muted/30"
            >
              {isImage(url) ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img src={url} alt={`upload-${i}`} className="h-10 w-10 rounded-lg object-cover shrink-0" />
              ) : (
                <div className="h-10 w-10 rounded-lg bg-muted flex items-center justify-center shrink-0">
                  <FileText className="h-5 w-5 text-muted-foreground" />
                </div>
              )}
              <div className="flex-1 min-w-0">
                <p className="text-xs font-medium truncate">File {i + 1}</p>
                <p className="text-[10px] text-muted-foreground flex items-center gap-1">
                  <CheckCircle className="h-3 w-3 text-green-400" /> Uploaded
                </p>
              </div>
              <button
                type="button"
                onClick={() => onChange(value.filter((_, j) => j !== i))}
                aria-label="Remove file"
                className="text-muted-foreground hover:text-red-400 transition-colors shrink-0"
              >
                <XIcon className="h-4 w-4" />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
