"use client";

import { useState, useRef, FormEvent, useCallback } from "react";
import { useRouter, useParams } from "next/navigation";
import {
  ArrowLeft,
  ClipboardList,
  Clock,
  Plus,
  Upload,
  Trash2,
  CheckCircle,
  FileEdit,
  Send,
  ChevronDown,
  FileText,
  X,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import {
  useExamDetail,
  useUpdateExam,
  useDeleteExam,
  useAddQuestion,
  useDeleteQuestion,
  useBulkUpload,
} from "@/lib/api/hooks/useExam";
import { ApiRequestError } from "@/lib/api";
import type { QuestionType, ExamQuestion } from "@/types/api";

// ── Question card ────────────────────────────────────────────

function QuestionCard({
  question,
  index,
  isDraft,
  onDelete,
}: {
  question: ExamQuestion;
  index: number;
  isDraft: boolean;
  onDelete: () => void;
}) {
  const optionLabels = ["A", "B", "C", "D"];
  const options = [question.optionA, question.optionB, question.optionC, question.optionD].filter(Boolean);

  return (
    <div className="p-4 sm:p-5 bg-gray-800/40 rounded-lg border border-gray-700">
      <div className="flex items-start justify-between gap-3 mb-3">
        <div className="min-w-0">
          <div className="flex items-center gap-2 mb-1 flex-wrap">
            <span className="text-xs font-bold text-gray-400">Q{index + 1}</span>
            <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${
              question.type === "MULTIPLE_CHOICE"
                ? "bg-blue-500/20 text-blue-400 border border-blue-500"
                : "bg-purple-500/20 text-purple-400 border border-purple-500"
            }`}>
              {question.type === "MULTIPLE_CHOICE" ? "MCQ" : "T/F"}
            </span>
            <span className="text-xs text-gray-500">{question.marks} {question.marks === 1 ? "mark" : "marks"}</span>
          </div>
          <p className="text-white text-sm font-medium">{question.question}</p>
        </div>
        {isDraft && (
          <Button size="sm" variant="danger" onClick={onDelete} className="shrink-0">
            <Trash2 className="size-4" />
          </Button>
        )}
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-3">
        {options.map((opt, i) => (
          <div
            key={i}
            className={`px-3 py-2 rounded-lg text-sm ${
              question.correctAnswer === i + 1
                ? "bg-green-500/20 text-green-400 border border-green-500"
                : "bg-gray-800 text-gray-400 border border-gray-700"
            }`}
          >
            <span className="font-bold mr-2">{optionLabels[i]}.</span>
            {opt}
          </div>
        ))}
      </div>

      {question.description && (
        <p className="mt-3 text-xs text-gray-500 italic">
          {question.description}
        </p>
      )}
    </div>
  );
}

// ── Add Question Form ────────────────────────────────────────

function AddQuestionForm({
  examId,
  onSuccess,
}: {
  examId: string;
  onSuccess: () => void;
}) {
  const addQuestion = useAddQuestion();
  const [questionText, setQuestionText] = useState("");
  const [type, setType] = useState<QuestionType>("MULTIPLE_CHOICE");
  const [optionA, setOptionA] = useState("");
  const [optionB, setOptionB] = useState("");
  const [optionC, setOptionC] = useState("");
  const [optionD, setOptionD] = useState("");
  const [correctAnswer, setCorrectAnswer] = useState(1);
  const [marks, setMarks] = useState("1");
  const [description, setDescription] = useState("");
  const [error, setError] = useState("");

  function resetForm() {
    setQuestionText("");
    setType("MULTIPLE_CHOICE");
    setOptionA("");
    setOptionB("");
    setOptionC("");
    setOptionD("");
    setCorrectAnswer(1);
    setMarks("1");
    setDescription("");
    setError("");
  }

  function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError("");

    if (!questionText.trim()) { setError("Question text is required"); return; }
    if (!optionA.trim()) { setError("Option A is required"); return; }
    if (!optionB.trim()) { setError("Option B is required"); return; }
    if (type === "MULTIPLE_CHOICE") {
      if (!optionC.trim()) { setError("Option C is required for multiple choice"); return; }
      if (!optionD.trim()) { setError("Option D is required for multiple choice"); return; }
    }

    addQuestion.mutate(
      {
        examId,
        data: {
          question: questionText.trim(),
          type,
          optionA: optionA.trim(),
          optionB: optionB.trim(),
          optionC: type === "MULTIPLE_CHOICE" ? optionC.trim() : undefined,
          optionD: type === "MULTIPLE_CHOICE" ? optionD.trim() : undefined,
          correctAnswer,
          marks: Number(marks) || 1,
          description: description.trim() || undefined,
        },
      },
      {
        onSuccess: () => {
          resetForm();
          onSuccess();
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) setError(err.message);
          else setError("Something went wrong.");
        },
      }
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {/* Question text */}
      <div className="space-y-2">
        <Label className="text-gray-300">Question</Label>
        <textarea
          value={questionText}
          onChange={(e) => { setQuestionText(e.target.value); setError(""); }}
          placeholder="Enter your question..."
          rows={2}
          className="w-full px-4 py-3 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm placeholder:text-gray-500 focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
        />
      </div>

      {/* Type + Marks row */}
      <div className="grid grid-cols-2 gap-4">
        <div className="space-y-2">
          <Label className="text-gray-300">Type</Label>
          <div className="relative">
            <select
              value={type}
              onChange={(e) => {
                const t = e.target.value as QuestionType;
                setType(t);
                if (t === "TRUE_FALSE") {
                  setOptionA("True");
                  setOptionB("False");
                  setOptionC("");
                  setOptionD("");
                  if (correctAnswer > 2) setCorrectAnswer(1);
                }
              }}
              className="w-full appearance-none px-4 py-3 pr-10 bg-gray-800 border border-gray-700 rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="MULTIPLE_CHOICE">Multiple Choice</option>
              <option value="TRUE_FALSE">True / False</option>
            </select>
            <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 size-4 text-gray-400 pointer-events-none" />
          </div>
        </div>
        <div className="space-y-2">
          <Label className="text-gray-300">Marks</Label>
          <Input
            type="number"
            min={1}
            value={marks}
            onChange={(e) => setMarks(e.target.value)}
            className="bg-gray-800 border-gray-700 text-white"
          />
        </div>
      </div>

      {/* Options */}
      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
        <div className="space-y-2">
          <Label className="text-gray-300">Option A</Label>
          <Input
            value={optionA}
            onChange={(e) => { setOptionA(e.target.value); setError(""); }}
            placeholder={type === "TRUE_FALSE" ? "True" : "Option A"}
            disabled={type === "TRUE_FALSE"}
            className="bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
          />
        </div>
        <div className="space-y-2">
          <Label className="text-gray-300">Option B</Label>
          <Input
            value={optionB}
            onChange={(e) => { setOptionB(e.target.value); setError(""); }}
            placeholder={type === "TRUE_FALSE" ? "False" : "Option B"}
            disabled={type === "TRUE_FALSE"}
            className="bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
          />
        </div>
        {type === "MULTIPLE_CHOICE" && (
          <>
            <div className="space-y-2">
              <Label className="text-gray-300">Option C</Label>
              <Input
                value={optionC}
                onChange={(e) => { setOptionC(e.target.value); setError(""); }}
                placeholder="Option C"
                className="bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
              />
            </div>
            <div className="space-y-2">
              <Label className="text-gray-300">Option D</Label>
              <Input
                value={optionD}
                onChange={(e) => { setOptionD(e.target.value); setError(""); }}
                placeholder="Option D"
                className="bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
              />
            </div>
          </>
        )}
      </div>

      {/* Correct Answer */}
      <div className="space-y-2">
        <Label className="text-gray-300">Correct Answer</Label>
        <div className="flex gap-2">
          {(type === "MULTIPLE_CHOICE" ? ["A", "B", "C", "D"] : ["A", "B"]).map((label, i) => (
            <button
              key={label}
              type="button"
              onClick={() => setCorrectAnswer(i + 1)}
              className={`px-4 py-2 rounded-lg text-sm font-semibold transition-colors ${
                correctAnswer === i + 1
                  ? "bg-green-600 text-white"
                  : "bg-gray-800 text-gray-400 border border-gray-700 hover:border-gray-500"
              }`}
            >
              {label}
            </button>
          ))}
        </div>
      </div>

      {/* Description (optional) */}
      <div className="space-y-2">
        <Label className="text-gray-300">
          Explanation <span className="text-gray-500 font-normal">(optional)</span>
        </Label>
        <Input
          value={description}
          onChange={(e) => setDescription(e.target.value)}
          placeholder="Why is this the correct answer?"
          className="bg-gray-800 border-gray-700 text-white placeholder:text-gray-500"
        />
      </div>

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

      <Button type="submit" disabled={addQuestion.isPending} className="bg-green-600 hover:bg-green-700 text-white">
        {addQuestion.isPending ? "Adding..." : "Add Question"}
      </Button>
    </form>
  );
}

// ── CSV Upload ───────────────────────────────────────────────

function CsvUploadSection({ examId }: { examId: string }) {
  const bulkUpload = useBulkUpload();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [dragOver, setDragOver] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState("");

  const handleFile = useCallback((file: File) => {
    setError("");
    setSuccess("");
    if (!file.name.endsWith(".csv")) {
      setError("Only CSV files are allowed");
      return;
    }
    if (file.size > 5 * 1024 * 1024) {
      setError("File must be under 5MB");
      return;
    }
    setSelectedFile(file);
  }, []);

  function handleUpload() {
    if (!selectedFile) return;
    setError("");
    setSuccess("");

    bulkUpload.mutate(
      { examId, file: selectedFile },
      {
        onSuccess: (res) => {
          setSuccess(res.message);
          setSelectedFile(null);
          if (fileInputRef.current) fileInputRef.current.value = "";
        },
        onError: (err) => {
          if (err instanceof ApiRequestError) setError(err.message);
          else setError("Upload failed. Please try again.");
        },
      }
    );
  }

  return (
    <div className="space-y-4">
      <div
        onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
        onDragLeave={() => setDragOver(false)}
        onDrop={(e) => {
          e.preventDefault();
          setDragOver(false);
          const file = e.dataTransfer.files[0];
          if (file) handleFile(file);
        }}
        onClick={() => fileInputRef.current?.click()}
        className={`p-6 rounded-lg border-2 border-dashed text-center cursor-pointer transition-colors ${
          dragOver
            ? "border-blue-500 bg-blue-500/10"
            : "border-gray-700 bg-gray-800/30 hover:border-gray-500"
        }`}
      >
        <Upload className="size-8 text-gray-500 mx-auto mb-3" />
        <p className="text-gray-400 text-sm mb-1">
          Drag & drop your CSV file here, or click to browse
        </p>
        <p className="text-gray-500 text-xs">Max 5MB. CSV format only.</p>
        <input
          ref={fileInputRef}
          type="file"
          accept=".csv"
          className="hidden"
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) handleFile(file);
          }}
        />
      </div>

      {selectedFile && (
        <div className="flex items-center justify-between p-3 bg-gray-800 rounded-lg border border-gray-700">
          <div className="flex items-center gap-3 min-w-0">
            <FileText className="size-5 text-blue-400 shrink-0" />
            <div className="min-w-0">
              <p className="text-white text-sm font-medium truncate">{selectedFile.name}</p>
              <p className="text-gray-500 text-xs">{(selectedFile.size / 1024).toFixed(1)} KB</p>
            </div>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <Button
              size="sm"
              variant="secondary"
              onClick={() => {
                setSelectedFile(null);
                if (fileInputRef.current) fileInputRef.current.value = "";
              }}
            >
              <X className="size-4" />
            </Button>
            <Button
              size="sm"
              className="bg-green-600 hover:bg-green-700 text-white"
              onClick={handleUpload}
              disabled={bulkUpload.isPending}
            >
              {bulkUpload.isPending ? "Uploading..." : "Upload"}
            </Button>
          </div>
        </div>
      )}

      {error && <p className="text-red-400 text-sm">{error}</p>}
      {success && <p className="text-green-400 text-sm">{success}</p>}

      <div className="p-3 bg-gray-800/50 rounded-lg border border-gray-700">
        <p className="text-gray-400 text-xs font-semibold mb-1">CSV Format:</p>
        <code className="text-gray-500 text-xs leading-relaxed block">
          Question,Type,Option A,Option B,Option C,Option D,Correct Answer (1-4),Marks,Description
        </code>
      </div>
    </div>
  );
}

// ── Main Page ────────────────────────────────────────────────

export default function ExamDetailPage() {
  const router = useRouter();
  const params = useParams();
  const examId = params.examId as string;

  const { data, isLoading } = useExamDetail(examId);
  const updateExam = useUpdateExam();
  const deleteExam = useDeleteExam();

  const deleteQuestion = useDeleteQuestion();

  const [activeTab, setActiveTab] = useState<"questions" | "add" | "upload">("questions");
  const [publishError, setPublishError] = useState("");

  const exam = data?.exam;
  const questions = data?.questions ?? [];
  const isDraft = exam?.status === "DRAFT";

  function handlePublishToggle() {
    if (!exam) return;
    setPublishError("");

    const newStatus = isDraft ? "PUBLISHED" : "DRAFT";
    updateExam.mutate(
      { examId, data: { status: newStatus } },
      {
        onError: (err) => {
          if (err instanceof ApiRequestError) setPublishError(err.message);
          else setPublishError("Something went wrong.");
        },
      }
    );
  }

  function handleDelete() {
    if (!exam) return;
    if (!confirm(`Are you sure you want to delete "${exam.title}"? This cannot be undone.`)) return;
    deleteExam.mutate(examId, {
      onSuccess: () => router.push("/admin/course"),
    });
  }

  function handleDeleteQuestion(questionId: string) {
    if (!confirm("Delete this question?")) return;
    deleteQuestion.mutate({ examId, questionId });
  }

  if (isLoading) {
    return (
      <div className="flex justify-center py-20">
        <Spinner className="size-8 text-blue-500" />
      </div>
    );
  }

  if (!exam) {
    return (
      <div className="text-center py-20">
        <ClipboardList className="size-12 text-gray-600 mx-auto mb-4" />
        <p className="text-gray-400 text-lg">Exam not found</p>
        <Button
          className="mt-4 bg-gray-800 hover:bg-gray-700 text-white"
          onClick={() => router.push("/admin/course")}
        >
          <ArrowLeft className="size-4 mr-2" />
          Back to Course
        </Button>
      </div>
    );
  }

  return (
    <div className="space-y-6 sm:space-y-8">
      {/* Back + Header */}
      <div>
        <button
          onClick={() => router.push("/admin/course")}
          className="flex items-center gap-1.5 text-gray-400 hover:text-white text-sm mb-4 transition-colors"
        >
          <ArrowLeft className="size-4" />
          Back to Course
        </button>
        <div className="flex flex-col sm:flex-row sm:items-start justify-between gap-4">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold text-white">{exam.title}</h1>
            <p className="text-gray-400 text-sm mt-1">
              {exam.course}
              {exam.cohort && (
                <span className="text-cyan-400"> — {exam.cohort.batch} ({exam.cohort.month} {exam.cohort.year})</span>
              )}
            </p>
          </div>
          <div className="flex items-center gap-2 shrink-0 flex-wrap">
            <span className={`px-2.5 py-1 rounded-full text-xs font-semibold ${
              isDraft
                ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500"
                : "bg-green-500/20 text-green-400 border border-green-500"
            }`}>
              {isDraft ? <FileEdit className="size-3 inline mr-1" /> : <CheckCircle className="size-3 inline mr-1" />}
              {exam.status}
            </span>
            <span className="px-2.5 py-1 rounded-full text-xs font-semibold bg-blue-500/20 text-blue-400 border border-blue-500">
              {exam.type}
            </span>
          </div>
        </div>
      </div>

      {/* Exam Info Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: "Questions", value: exam.totalQuestions, icon: ClipboardList },
          { label: "Total Marks", value: exam.totalMarks, icon: CheckCircle },
          { label: "Duration", value: `${exam.duration} min`, icon: Clock },
          { label: "Created", value: exam.createdAt, icon: FileEdit },
        ].map((item) => (
          <div key={item.label} className="p-3 sm:p-4 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
            <item.icon className="size-4 text-gray-400 mb-2" />
            <p className="text-xs text-gray-400">{item.label}</p>
            <p className="text-lg font-bold text-white">{item.value}</p>
          </div>
        ))}
      </div>

      {/* Actions */}
      <div className="flex flex-wrap gap-3">
        <Button
          onClick={handlePublishToggle}
          disabled={updateExam.isPending}
          className={isDraft ? "bg-green-600 hover:bg-green-700 text-white" : "bg-yellow-600 hover:bg-yellow-700 text-white"}
        >
          {isDraft ? (
            <>
              <Send className="size-4 mr-2" />
              {updateExam.isPending ? "Publishing..." : "Publish Exam"}
            </>
          ) : (
            <>
              <FileEdit className="size-4 mr-2" />
              {updateExam.isPending ? "Unpublishing..." : "Unpublish"}
            </>
          )}
        </Button>
        {isDraft && (
          <Button
            variant="danger"
            onClick={handleDelete}
            disabled={deleteExam.isPending}
          >
            <Trash2 className="size-4 mr-2" />
            {deleteExam.isPending ? "Deleting..." : "Delete Exam"}
          </Button>
        )}
      </div>
      {publishError && <p className="text-red-400 text-sm">{publishError}</p>}

      {/* Tabs */}
      <div className="flex gap-2 border-b border-gray-800 pb-0">
        {(
          [
            { key: "questions", label: `Questions (${questions.length})`, icon: ClipboardList },
            ...(isDraft ? [
              { key: "add", label: "Add Question", icon: Plus },
              { key: "upload", label: "CSV Upload", icon: Upload },
            ] : []),
          ] as { key: "questions" | "add" | "upload"; label: string; icon: typeof ClipboardList }[]
        ).map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className={`flex items-center gap-1.5 px-4 py-3 text-sm font-medium border-b-2 -mb-px transition-colors ${
              activeTab === tab.key
                ? "border-blue-500 text-blue-400"
                : "border-transparent text-gray-400 hover:text-white"
            }`}
          >
            <tab.icon className="size-4" />
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div className="p-5 sm:p-6 bg-gradient-to-br from-gray-900 to-black border border-gray-800 rounded-xl">
        {/* Questions list */}
        {activeTab === "questions" && (
          questions.length === 0 ? (
            <div className="text-center py-10">
              <ClipboardList className="size-10 text-gray-600 mx-auto mb-3" />
              <p className="text-gray-400">No questions yet</p>
              {isDraft && (
                <p className="text-gray-500 text-sm mt-1">
                  Add questions manually or upload a CSV file.
                </p>
              )}
            </div>
          ) : (
            <div className="space-y-3">
              {questions.map((q, i) => (
                <QuestionCard
                  key={q.id}
                  question={q}
                  index={i}
                  isDraft={isDraft}
                  onDelete={() => handleDeleteQuestion(q.id)}
                />
              ))}
            </div>
          )
        )}

        {/* Add question form */}
        {activeTab === "add" && isDraft && (
          <AddQuestionForm
            examId={examId}
            onSuccess={() => setActiveTab("questions")}
          />
        )}

        {/* CSV upload */}
        {activeTab === "upload" && isDraft && (
          <CsvUploadSection examId={examId} />
        )}
      </div>
    </div>
  );
}
