"use client";

import { useEffect, useState } from "react";
import { ClipboardCheck, ChevronLeft, ChevronRight, Star } from "lucide-react";

interface SurveyAnswer {
  id: string;
  value: string;
  createdAt: string;
  question: {
    title: string;
    template: { id: string; title: string };
  };
  course: { id: string; title: string };
}

interface SurveyGroup {
  templateId: string;
  templateTitle: string;
  answers: SurveyAnswer[];
}

const ratingLabels: Record<string, string> = {
  "1": "خیلی بد",
  "2": "بد",
  "3": "متوسط",
  "4": "خوب",
  "5": "عالی",
};

export default function AthleteSurveys() {
  const [groups, setGroups] = useState<SurveyGroup[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeIndex, setActiveIndex] = useState(0);
  const [expandedId, setExpandedId] = useState<string | null>(null);

  useEffect(() => {
    fetch("/api/surveys?my=true", {
      headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
    })
      .then((r) => r.json())
      .then((data: SurveyAnswer[]) => {
        const map = new Map<string, SurveyGroup>();
        for (const a of data) {
          const tid = a.question.template.id;
          if (!map.has(tid)) {
            map.set(tid, { templateId: tid, templateTitle: a.question.template.title, answers: [] });
          }
          map.get(tid)!.answers.push(a);
        }
        setGroups(Array.from(map.values()));
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const scroll = (dir: "next" | "prev") => {
    if (dir === "next") setActiveIndex((i) => Math.min(i + 1, groups.length - 1));
    else setActiveIndex((i) => Math.max(i - 1, 0));
  };

  if (loading) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-gray-900 mb-6">نظرسنجی‌ها</h1>
        <div className="rounded-xl border bg-white p-6 text-center text-gray-500 py-12">
          در حال بارگذاری...
        </div>
      </div>
    );
  }

  if (groups.length === 0) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-gray-900 mb-6">نظرسنجی‌ها</h1>
        <div className="rounded-xl border bg-white p-6 text-center py-12">
          <ClipboardCheck className="h-12 w-12 mx-auto mb-3 text-gray-300" />
          <p className="text-gray-500">هنوز نظرسنجی تکمیل نکرده‌اید</p>
        </div>
      </div>
    );
  }

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-6">نظرسنجی‌ها</h1>

      {/* Carousel */}
      <div className="relative mb-8">
        <div className="flex items-center gap-3">
          <button
            onClick={() => scroll("prev")}
            disabled={activeIndex === 0}
            className="shrink-0 w-10 h-10 rounded-full border bg-white flex items-center justify-center hover:bg-gray-50 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronRight className="h-5 w-5 text-gray-600" />
          </button>

          <div className="flex-1 overflow-hidden">
            <div
              className="flex gap-3 transition-transform duration-300"
              style={{ transform: `translateX(${activeIndex * 260}px)` }}
            >
              {groups.map((g, i) => (
                <button
                  key={g.templateId}
                  onClick={() => { setActiveIndex(i); setExpandedId(expandedId === g.templateId ? null : g.templateId); }}
                  className={`shrink-0 w-[240px] rounded-xl border p-5 text-right transition-all duration-200 ${
                    expandedId === g.templateId
                      ? "bg-[#2563EB] text-white border-[#2563EB] shadow-lg shadow-blue-500/20"
                      : "bg-white hover:border-[#2563EB]/30 hover:shadow-md"
                  }`}
                >
                  <ClipboardCheck className={`h-8 w-8 mb-3 ${expandedId === g.templateId ? "text-white/80" : "text-[#2563EB]"}`} />
                  <div className={`font-semibold text-sm mb-1 ${expandedId === g.templateId ? "text-white" : "text-gray-900"}`}>
                    {g.templateTitle}
                  </div>
                  <div className={`text-xs ${expandedId === g.templateId ? "text-blue-100" : "text-gray-500"}`}>
                    {g.answers.length} پاسخ
                  </div>
                </button>
              ))}
            </div>
          </div>

          <button
            onClick={() => scroll("next")}
            disabled={activeIndex === groups.length - 1}
            className="shrink-0 w-10 h-10 rounded-full border bg-white flex items-center justify-center hover:bg-gray-50 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
          >
            <ChevronLeft className="h-5 w-5 text-gray-600" />
          </button>
        </div>

        {/* Dots */}
        {groups.length > 1 && (
          <div className="flex justify-center gap-1.5 mt-4">
            {groups.map((_, i) => (
              <button
                key={i}
                onClick={() => setActiveIndex(i)}
                className={`w-2 h-2 rounded-full transition-colors ${
                  i === activeIndex ? "bg-[#2563EB]" : "bg-gray-300"
                }`}
              />
            ))}
          </div>
        )}
      </div>

      {/* Expanded answers */}
      {expandedId && (() => {
        const group = groups.find((g) => g.templateId === expandedId);
        if (!group) return null;

        const courseMap = new Map<string, { courseTitle: string; answers: SurveyAnswer[] }>();
        for (const a of group.answers) {
          const cid = a.course.id;
          if (!courseMap.has(cid)) {
            courseMap.set(cid, { courseTitle: a.course.title, answers: [] });
          }
          courseMap.get(cid)!.answers.push(a);
        }

        return (
          <div className="rounded-xl border bg-white overflow-hidden">
            <div className="p-6 border-b bg-gray-50">
              <h2 className="font-bold text-gray-900 text-lg">{group.templateTitle}</h2>
              <p className="text-sm text-gray-500 mt-1">{group.answers.length} پاسخ در {courseMap.size} دوره</p>
            </div>

            <div className="divide-y">
              {Array.from(courseMap.values()).map((courseGroup) => (
                <div key={courseGroup.courseTitle} className="p-6">
                  <h3 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full bg-[#2563EB]" />
                    {courseGroup.courseTitle}
                  </h3>
                  <div className="grid gap-3">
                    {courseGroup.answers.map((a) => {
                      const num = parseInt(a.value);
                      const isRating = num >= 1 && num <= 5;
                      return (
                        <div key={a.id} className="flex items-start gap-4 p-4 rounded-lg bg-gray-50">
                          <div className="flex-1">
                            <div className="text-sm font-medium text-gray-900 mb-1">{a.question.title}</div>
                            <div className="text-sm text-gray-600">
                              پاسخ: <span className="font-medium text-gray-900">{a.value}</span>
                              {isRating && (
                                <span className="text-xs text-gray-400 mr-2">({ratingLabels[a.value]})</span>
                              )}
                            </div>
                          </div>
                          {isRating && (
                            <div className="flex gap-0.5 shrink-0">
                              {[1, 2, 3, 4, 5].map((s) => (
                                <Star
                                  key={s}
                                  className={`h-4 w-4 ${s <= num ? "fill-amber-400 text-amber-400" : "text-gray-200"}`}
                                />
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          </div>
        );
      })()}
    </div>
  );
}
