"use client";

import { useEffect, useState } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ArrowLeft, Loader2 } from "lucide-react";

const RATING_OPTIONS = [
  { value: "1", label: "خیلی بد" },
  { value: "2", label: "بد" },
  { value: "3", label: "متوسط" },
  { value: "4", label: "خوب" },
  { value: "5", label: "عالی" },
];

const QUESTIONS_PER_STEP = 3;

interface Question {
  id: string;
  title: string;
  sortOrder: number;
}

interface SurveyTemplate {
  id: string;
  title: string;
  questions: Question[];
}

interface CourseInfo {
  id: string;
  title: string;
  status: string;
  surveyTemplateId: string | null;
}

export default function CourseSurvey() {
  const { slug } = useParams<{ slug: string }>();
  const router = useRouter();
  const [course, setCourse] = useState<CourseInfo | null>(null);
  const [survey, setSurvey] = useState<SurveyTemplate | null>(null);
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [answers, setAnswers] = useState<Record<string, string>>({});
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);
  const [error, setError] = useState("");
  const [accessError, setAccessError] = useState("");

  useEffect(() => {
    (async () => {
      const token = localStorage.getItem("auth_token");
      if (!token) {
        setAccessError("برای شرکت در نظرسنجی باید وارد شوید");
        setLoading(false);
        return;
      }

      const res = await fetch(`/api/courses/${slug}`);
      if (res.ok) {
        const c: CourseInfo & { surveyTemplate?: SurveyTemplate } = await res.json();
        setCourse(c);

        if (c.status !== "COMPLETED") {
          setAccessError("این دوره هنوز به اتمام نرسیده است. پس از اتمام دوره توسط مدیر می‌توانید در نظرسنجی شرکت کنید");
          setLoading(false);
          return;
        }

        const regRes = await fetch(`/api/registrations?courseId=${c.id}`, {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (regRes.ok) {
          const registrations = await regRes.json();
          const completed = registrations.find(
            (r: { status: string }) => r.status === "COMPLETED"
          );
          if (!completed) {
            setAccessError("فقط پس از اتمام دوره می‌توانید در نظرسنجی شرکت کنید");
            setLoading(false);
            return;
          }
        }

        const existingRes = await fetch(`/api/surveys/check?courseId=${c.id}`, {
          headers: { Authorization: `Bearer ${token}` },
        });
        if (existingRes.ok) {
          const existing = await existingRes.json();
          if (existing.submitted) {
            setAccessError("شما قبلاً در این نظرسنجی شرکت کرده‌اید");
            setLoading(false);
            return;
          }
        }

        if (c.surveyTemplateId) {
          const sRes = await fetch(`/api/surveys/${c.surveyTemplateId}`);
          if (sRes.ok) setSurvey(await sRes.json());
        }
      }
      setLoading(false);
    })();
  }, [slug]);

  const questions = survey?.questions || [];
  const totalSteps = Math.ceil(questions.length / QUESTIONS_PER_STEP);
  const stepQuestions = questions.slice(step * QUESTIONS_PER_STEP, (step + 1) * QUESTIONS_PER_STEP);

  const setAnswer = (qId: string, value: string) => {
    setAnswers((prev) => ({ ...prev, [qId]: value }));
  };

  const handleSubmit = async () => {
    const unanswered = questions.filter((q) => !answers[q.id]);
    if (unanswered.length > 0) {
      setError("لطفاً به همه سوالات پاسخ دهید");
      return;
    }

    setSubmitting(true);
    setError("");
    const token = localStorage.getItem("auth_token");
    try {
      const res = await fetch("/api/surveys/submit", {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ answers, courseId: course!.id }),
      });
      if (res.ok) {
        setDone(true);
      } else {
        const data = await res.json();
        setError(data.error || "خطا در ثبت نظرسنجی");
      }
    } catch {
      setError("خطا در ارتباط با سرور");
    } finally {
      setSubmitting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[50vh]">
        <Loader2 className="h-6 w-6 animate-spin text-gray-400" />
      </div>
    );
  }

  if (accessError) {
    return (
      <div className="max-w-lg mx-auto text-center py-12">
        <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <svg className="w-8 h-8 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <h2 className="text-xl font-bold text-gray-900 mb-2">دسترسی غیرمجاز</h2>
        <p className="text-gray-500 mb-6">{accessError}</p>
        <Button className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white" onClick={() => router.push("/auth")}>
          ورود به سامانه
        </Button>
      </div>
    );
  }

  if (!course) {
    return (
      <div className="text-center py-12 text-gray-500 max-w-lg mx-auto">
        دوره یافت نشد
      </div>
    );
  }

  if (!survey) {
    return (
      <div className="text-center py-12 text-gray-500 max-w-lg mx-auto">
        این دوره نظرسنجی ندارد
      </div>
    );
  }

  if (done) {
    return (
      <div className="max-w-lg mx-auto text-center py-12">
        <div className="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
          <svg className="w-8 h-8 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
          </svg>
        </div>
        <h2 className="text-xl font-bold text-gray-900 mb-2">نظرسنجی با موفقیت ثبت شد</h2>
        <p className="text-gray-500 mb-6">پاسخ‌های شما با موفقیت ارسال شد</p>
        <Button className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white" onClick={() => router.push(`/courses/${slug}`)}>
          بازگشت به دوره
        </Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto py-8 px-4">
      <button
        onClick={() => router.push(`/courses/${slug}`)}
        className="flex items-center gap-1 text-sm text-gray-500 hover:text-gray-900 mb-6 transition-colors"
      >
        <ArrowLeft className="h-4 w-4" />
        بازگشت به دوره
      </button>

      <div className="text-center mb-8">
        <h1 className="text-2xl font-bold text-gray-900">{survey.title}</h1>
        <p className="text-sm text-gray-500 mt-1">دوره: {course.title}</p>
      </div>

      {/* Progress bar */}
      <div className="flex items-center gap-2 mb-8">
        {Array.from({ length: totalSteps }).map((_, i) => (
          <div
            key={i}
            className={`flex-1 h-2 rounded-full transition-colors ${
              i <= step ? "bg-[#2563EB]" : "bg-gray-200"
            }`}
          />
        ))}
      </div>

      <div className="border rounded-xl p-6 bg-white">
        <div className="text-xs text-gray-400 mb-4">
          مرحله {step + 1} از {totalSteps}
        </div>

        <div className="space-y-6">
          {stepQuestions.map((q) => (
            <div key={q.id}>
              <p className="font-medium text-gray-900 mb-3">{q.title}</p>
              <div className="flex gap-1.5">
                {RATING_OPTIONS.map((opt) => {
                  const isSelected = answers[q.id] === opt.value;
                  return (
                    <button
                      key={opt.value}
                      type="button"
                      onClick={() => setAnswer(q.id, opt.value)}
                      className={`flex-1 py-2.5 px-1 rounded-lg text-xs font-medium border transition-all ${
                        isSelected
                          ? "bg-[#2563EB] text-white border-[#2563EB] shadow-sm"
                          : "bg-white text-gray-600 border-gray-200 hover:border-[#2563EB]/40 hover:bg-blue-50/50"
                      }`}
                    >
                      {opt.label}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
      </div>

      {error && (
        <div className="text-sm text-red-600 bg-red-50 p-3 rounded-lg mt-4">{error}</div>
      )}

      <div className="flex gap-3 mt-6">
        {step > 0 && (
          <Button variant="outline" className="flex-1" onClick={() => setStep(step - 1)}>
            قبلی
          </Button>
        )}
        {step < totalSteps - 1 ? (
          <Button
            className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1"
            onClick={() => setStep(step + 1)}
          >
            بعدی
          </Button>
        ) : (
          <Button
            className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1"
            onClick={handleSubmit}
            disabled={submitting}
          >
            {submitting ? <Loader2 className="h-4 w-4 animate-spin" /> : "ثبت نظرسنجی"}
          </Button>
        )}
      </div>
    </div>
  );
}
