"use client";

import { useEffect, useState } from "react";
import { Loader2, Users } from "lucide-react";

const RATING_LABELS = ["عالی", "خوب", "متوسط", "بد", "خیلی بد"];
const RATING_VALUES = ["5", "4", "3", "2", "1"];

interface SurveyStats {
  id: string;
  title: string;
  courses: Array<{ id: string; title: string }>;
  questions: Array<{
    id: string;
    title: string;
    answers: Array<{ value: string; _count: number }>;
  }>;
}

export default function SurveyCharts() {
  const [surveys, setSurveys] = useState<SurveyStats[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      const token = localStorage.getItem("auth_token");
      const res = await fetch("/api/surveys/charts", {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) setSurveys(await res.json());
      setLoading(false);
    })();
  }, []);

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

  if (surveys.length === 0) {
    return (
      <div>
        <h1 className="text-2xl font-bold text-gray-900 mb-6">نمودار نظرسنجی‌ها</h1>
        <div className="text-center py-12 bg-white rounded-xl border text-gray-500">
          داده‌ای برای نمایش وجود ندارد
        </div>
      </div>
    );
  }

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

      <div className="space-y-8">
        {surveys.map((survey) => {
          const allTotal = survey.questions.reduce((s, q) => s + q.answers.reduce((a, b) => a + b._count, 0), 0);
          const allScore = survey.questions.reduce((s, q) =>
            s + q.answers.reduce((a, b) => a + Number(b.value) * b._count, 0), 0);
          const avg = allTotal > 0 ? (allScore / allTotal).toFixed(1) : "—";

          return (
            <div key={survey.id} className="border rounded-xl p-6 bg-white">
              <div className="flex items-center justify-between mb-1">
                <h2 className="text-lg font-semibold text-gray-900">{survey.title}</h2>
                <div className="flex items-center gap-4 text-sm">
                  <span className="text-gray-500 flex items-center gap-1">
                    <Users className="h-4 w-4" />
                    {allTotal}
                  </span>
                  <span className="text-gray-900 font-bold text-lg">{avg}</span>
                  <span className="text-gray-400 text-xs">از ۵</span>
                </div>
              </div>
              <p className="text-xs text-gray-400 mb-6">
                {survey.courses.map((c) => c.title).join("، ") || "بدون دوره"}
              </p>

              <div className="space-y-8">
                {survey.questions.map((q) => {
                  const total = q.answers.reduce((sum, a) => sum + a._count, 0);
                  const maxCount = Math.max(...RATING_VALUES.map((v) => q.answers.find((a) => a.value === v)?._count || 0), 1);
                  const qScore = q.answers.reduce((s, a) => s + Number(a.value) * a._count, 0);
                  const qAvg = total > 0 ? (qScore / total).toFixed(1) : "—";

                  return (
                    <div key={q.id}>
                      <div className="flex items-center justify-between mb-4">
                        <p className="text-sm font-medium text-gray-700">{q.title}</p>
                        <span className="text-xs text-gray-400">{qAvg} میانگین</span>
                      </div>

                      {/* Vertical bars */}
                      <div className="flex items-end gap-2" dir="ltr">
                        {RATING_VALUES.map((val, i) => {
                          const a = q.answers.find((x) => x.value === val);
                          const count = a?._count || 0;
                          const barHeight = (count / maxCount) * 160;

                          const colors = [
                            "from-emerald-400 to-emerald-600",
                            "from-lime-400 to-lime-600",
                            "from-amber-300 to-amber-500",
                            "from-orange-400 to-orange-600",
                            "from-red-400 to-red-600",
                          ];

                          return (
                            <div key={val} className="flex-1 flex flex-col items-center gap-1">
                              <span className="text-xs font-semibold text-gray-700">{count}</span>
                              <div className="w-full flex justify-center" style={{ height: 160 }}>
                                <div
                                  className="w-8 md:w-10 rounded-md bg-gradient-to-t self-end transition-all"
                                  style={{ height: Math.max(barHeight, count > 0 ? 4 : 0) }}
                                >
                                  <div className={`w-full h-full rounded-md bg-gradient-to-t ${colors[i]}`} />
                                </div>
                              </div>
                              <span className="text-[10px] text-gray-400 mt-1">{RATING_LABELS[i]}</span>
                            </div>
                          );
                        })}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
