"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Download, ChevronDown, ChevronUp, Search, FileText } from "lucide-react";
import * as XLSX from "xlsx";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";

interface SurveyReport {
  id: string;
  title: string;
  courses: { id: string; title: string }[];
  totalResponses: number;
  overallAverage: number;
  satisfactionRate: number;
  questions: QuestionReport[];
}

interface QuestionReport {
  id: string;
  title: string;
  average: number;
  count: number;
  distribution: { value: string; _count: number }[];
  individuals: { userId: string; phone: string; fullName: string | null; courseTitle: string; value: string }[];
}

interface OverallData {
  siteWide: { label: string; totalResponses: number; average: number; satisfactionRate: number; distribution: { value: string; _count: number }[] } | null;
  boards: { id: string; name: string; stats: { totalResponses: number; average: number; satisfactionRate: number; distribution: { value: string; _count: number }[] } }[];
  sports: { id: string; name: string; boardName: string; stats: { totalResponses: number; average: number; satisfactionRate: number; distribution: { value: string; _count: number }[] } }[];
  isSuperAdmin: boolean;
}

export default function SurveyReports() {
  const [tab, setTab] = useState<"surveys" | "overall">("surveys");
  const [reports, setReports] = useState<SurveyReport[]>([]);
  const [overall, setOverall] = useState<OverallData | null>(null);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<string | null>(null);
  const [surveyFilter, setSurveyFilter] = useState("");
  const [courseFilter, setCourseFilter] = useState("");
  const [courses, setCourses] = useState<{ id: string; title: string }[]>([]);

  const token = typeof window !== "undefined" ? localStorage.getItem("auth_token") : null;

  const load = async (initialSurveyId?: string) => {
    setLoading(true);
    const params = new URLSearchParams();
    const sid = initialSurveyId || surveyFilter;
    if (sid) params.set("surveyId", sid);
    if (courseFilter) params.set("courseId", courseFilter);
    try {
      const [reportsRes, surveysRes, overallRes] = await Promise.all([
        fetch(`/api/surveys/reports?${params}`, { headers: { Authorization: `Bearer ${token}` } }),
        fetch("/api/surveys", { headers: { Authorization: `Bearer ${token}` } }),
        fetch("/api/surveys/overall", { headers: { Authorization: `Bearer ${token}` } }),
      ]);
      if (reportsRes.ok) setReports(await reportsRes.json());
      if (overallRes.ok) setOverall(await overallRes.json());
      if (surveysRes.ok) {
        const all: { id: string; title: string; courses: { id: string; title: string }[] }[] = await surveysRes.json();
        const cs: { id: string; title: string }[] = [];
        for (const s of all) for (const c of s.courses || []) if (!cs.find((x) => x.id === c.id)) cs.push(c);
        setCourses(cs);
      }
    } catch {}
    setLoading(false);
  };

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const initialSurveyId = params.get("surveyId") || "";
    setSurveyFilter(initialSurveyId);
    load(initialSurveyId);
  }, []);

  const exportExcel = () => {
    const wb = XLSX.utils.book_new();

    // Sheet 1: Summary
    const summaryRows: Record<string, string | number>[] = reports.map((r) => ({
      "نظرسنجی": r.title,
      "تعداد پاسخ": r.totalResponses,
      "میانگین (از ۵)": r.overallAverage,
      "درصد رضایت": r.satisfactionRate,
      "تعداد دوره‌ها": r.courses.length,
    }));
    if (summaryRows.length === 0) summaryRows.push({ "پیام": "داده‌ای وجود ندارد" });
    let ws = XLSX.utils.json_to_sheet(summaryRows);
    XLSX.utils.book_append_sheet(wb, ws, "خلاصه");

    // Sheet 2: Per-question breakdown
    const detailRows: Record<string, string | number>[] = [];
    for (const r of reports) {
      for (const q of r.questions) {
        detailRows.push({
          "نظرسنجی": r.title,
          "سوال": q.title,
          "تعداد پاسخ": q.count,
          "میانگین": q.average,
          "۱": q.distribution.find((d) => d.value === "1")?._count || 0,
          "۲": q.distribution.find((d) => d.value === "2")?._count || 0,
          "۳": q.distribution.find((d) => d.value === "3")?._count || 0,
          "۴": q.distribution.find((d) => d.value === "4")?._count || 0,
          "۵": q.distribution.find((d) => d.value === "5")?._count || 0,
        });
      }
    }
    if (detailRows.length === 0) detailRows.push({ "پیام": "داده‌ای وجود ندارد" });
    ws = XLSX.utils.json_to_sheet(detailRows);
    XLSX.utils.book_append_sheet(wb, ws, "جزئیات سوالات");

    // Sheet 3: Individual responses
    const indRows: Record<string, string | number>[] = [];
    for (const r of reports) {
      for (const q of r.questions) {
        for (const ind of q.individuals) {
          indRows.push({
            "نظرسنجی": r.title,
            "سوال": q.title,
            "دوره": ind.courseTitle,
            "کاربر": ind.fullName || ind.phone,
            "امتیاز": ind.value,
          });
        }
      }
    }
    if (indRows.length === 0) indRows.push({ "پیام": "داده‌ای وجود ندارد" });
    ws = XLSX.utils.json_to_sheet(indRows);
    XLSX.utils.book_append_sheet(wb, ws, "پاسخ افراد");

    // Column widths
    const cols = [{ wch: 30 }, { wch: 40 }, { wch: 15 }, { wch: 15 }, { wch: 10 }];
    for (let i = 0; i < wb.SheetNames.length; i++) {
      const sheet = wb.Sheets[wb.SheetNames[i]];
      sheet["!cols"] = cols;
    }

    XLSX.writeFile(wb, `survey-report-${Date.now()}.xlsx`);
  };

  const exportPDF = async () => {
    // Load Persian font
    const fontRes = await fetch("/fonts/Vazirmatn-Regular.ttf");
    const fontBlob = await fontRes.blob();
    const fontBase64 = await new Promise<string>((resolve) => {
      const reader = new FileReader();
      reader.onload = () => {
        const result = reader.result as string;
        resolve(result.split(",")[1]); // strip data: URL prefix
      };
      reader.readAsDataURL(fontBlob);
    });

    const doc = new jsPDF("p", "mm", "a4");
    doc.addFileToVFS("Vazirmatn-Regular.ttf", fontBase64);
    doc.addFont("Vazirmatn-Regular.ttf", "Vazir", "normal");
    doc.addFont("Vazirmatn-Regular.ttf", "Vazir", "bold");

    const pageW = 190;
    const margin = 10;
    let y = margin;

    const vazir = (size: number, style?: "normal" | "bold") => {
      doc.setFont("Vazir", style || "normal");
      doc.setFontSize(size);
    };

    const writeHeader = () => {
      doc.setFillColor(37, 99, 235);
      doc.rect(0, 0, 210, 35, "F");
      doc.setTextColor(255, 255, 255);
      vazir(18);
      doc.text("گزارش نظرسنجی", 105, 15, { align: "center" });
      vazir(10);
      doc.text(new Date().toLocaleDateString("fa-IR"), 105, 25, { align: "center" });
      doc.setTextColor(0, 0, 0);
      y = 45;
    };

    const writeFooter = () => {
      const pageCount = doc.getNumberOfPages();
      for (let i = 1; i <= pageCount; i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(150, 150, 150);
        doc.text(`صفحه ${i} از ${pageCount}`, 105, 290, { align: "center" });
      }
      doc.setTextColor(0, 0, 0);
    };

    writeHeader();

    for (const r of reports) {
      if (y > 230) { doc.addPage(); y = margin; writeHeader(); }

      // Survey title
      doc.setTextColor(37, 99, 235);
      vazir(14);
      doc.text(r.title, margin, y);
      y += 8;

      // Stats boxes
      doc.setTextColor(0, 0, 0);
      const boxW = (pageW - 15) / 4;
      const stats = [
        { label: "تعداد پاسخ", value: String(r.totalResponses), color: [37, 99, 235] },
        { label: "میانگین (از ۵)", value: String(r.overallAverage), color: [22, 163, 74] },
        { label: "رضایت", value: `%${r.satisfactionRate}`, color: [217, 119, 6] },
        { label: "دوره‌ها", value: String(r.courses.length), color: [147, 51, 234] },
      ];
      let bx = margin;
      for (const s of stats) {
        doc.setFillColor(s.color[0], s.color[1], s.color[2]);
        doc.roundedRect(bx, y, boxW, 18, 2, 2, "F");
        doc.setTextColor(255, 255, 255);
        vazir(11);
        doc.text(s.value, bx + boxW / 2, y + 7, { align: "center" });
        vazir(6);
        doc.text(s.label, bx + boxW / 2, y + 14, { align: "center" });
        bx += boxW + 5;
      }
      y += 28;
      doc.setTextColor(0, 0, 0);

      // Questions
      for (const q of r.questions) {
        if (y > 250) { doc.addPage(); y = margin; writeHeader(); }

        doc.setFillColor(245, 247, 250);
        doc.rect(margin, y, pageW, 8, "F");
        vazir(10);
        doc.text(`سوال: ${q.title}`, margin + 2, y + 6);
        vazir(8);
        doc.setTextColor(100, 100, 100);
        doc.text(`${q.count} پاسخ | میانگین: ${q.average}`, margin + pageW, y + 6, { align: "left" });
        y += 12;
        doc.setTextColor(0, 0, 0);

        // Distribution table
        const distRows = [["", "1", "2", "3", "4", "5"]];
        const distCounts = [1, 2, 3, 4, 5].map((v) =>
          q.distribution.find((d) => d.value === String(v))?._count || 0
        );
        const distPcts = distCounts.map((c) => `${q.count > 0 ? Math.round((c / q.count) * 100) : 0}%`);
        distRows.push(["تعداد", ...distCounts.map(String)]);
        distRows.push(["درصد", ...distPcts]);

        autoTable(doc, {
          body: distRows.slice(1),
          columns: distRows[0].map((h) => ({ header: h, dataKey: h })),
          startY: y,
          styles: { font: "Vazir", fontSize: 8, halign: "center" },
          headStyles: { fillColor: [37, 99, 235], textColor: [255, 255, 255] },
          tableWidth: 80,
          margin: { left: margin },
        });
        y = (doc as any).lastAutoTable.finalY + 6;

        // Individual responses
        if (q.individuals.length > 0) {
          if (y > 250) { doc.addPage(); y = margin; writeHeader(); }

          const indRows = q.individuals.map((ind) => [
            ind.fullName || ind.phone,
            ind.courseTitle,
            ind.value,
          ]);
          autoTable(doc, {
            head: [["کاربر", "دوره", "امتیاز"]],
            body: indRows,
            startY: y,
            styles: { font: "Vazir", fontSize: 7 },
            headStyles: { fillColor: [100, 100, 100] },
            tableWidth: pageW,
            margin: { left: margin },
          });
          y = (doc as any).lastAutoTable.finalY + 8;
        } else {
          vazir(8);
          doc.setTextColor(150, 150, 150);
          doc.text("بدون پاسخ فردی", margin, y);
          y += 6;
          doc.setTextColor(0, 0, 0);
        }
      }

      y += 10;
    }

    writeFooter();
    doc.save(`survey-report-${Date.now()}.pdf`);
  };

  const exportOverallPDF = async () => {
    if (!overall) return;
    const fontRes = await fetch("/fonts/Vazirmatn-Regular.ttf");
    const fontBlob = await fontRes.blob();
    const fontBase64 = await new Promise<string>((resolve) => {
      const reader = new FileReader();
      reader.onload = () => resolve((reader.result as string).split(",")[1]);
      reader.readAsDataURL(fontBlob);
    });

    const doc = new jsPDF("p", "mm", "a4");
    doc.addFileToVFS("Vazirmatn-Regular.ttf", fontBase64);
    doc.addFont("Vazirmatn-Regular.ttf", "Vazir", "normal");
    doc.addFont("Vazirmatn-Regular.ttf", "Vazir", "bold");

    const pageW = 190;
    const margin = 10;
    let y = margin;

    const vazir = (size: number, style?: "normal" | "bold") => {
      doc.setFont("Vazir", style || "normal");
      doc.setFontSize(size);
    };

    const writeHeader = () => {
      doc.setFillColor(37, 99, 235);
      doc.rect(0, 0, 210, 35, "F");
      doc.setTextColor(255, 255, 255);
      vazir(18);
      doc.text("گزارش کلی نظرسنجی", 105, 15, { align: "center" });
      vazir(10);
      doc.text(new Date().toLocaleDateString("fa-IR"), 105, 25, { align: "center" });
      doc.setTextColor(0, 0, 0);
      y = 45;
    };

    const writeFooter = () => {
      for (let i = 1; i <= doc.getNumberOfPages(); i++) {
        doc.setPage(i);
        doc.setFontSize(8);
        doc.setTextColor(150, 150, 150);
        doc.text(`صفحه ${i} از ${doc.getNumberOfPages()}`, 105, 290, { align: "center" });
      }
      doc.setTextColor(0, 0, 0);
    };

    writeHeader();

    // Site-wide
    if (overall.siteWide) {
      if (y > 230) { doc.addPage(); y = margin; writeHeader(); }
      doc.setTextColor(37, 99, 235);
      vazir(14);
      doc.text("کل سامانه", margin, y);
      y += 8;
      doc.setTextColor(0, 0, 0);

      const boxW = (pageW - 10) / 3;
      let bx = margin;
      for (const s of [
        { label: "تعداد پاسخ", value: String(overall.siteWide.totalResponses), color: [37, 99, 235] },
        { label: "میانگین (از ۵)", value: String(overall.siteWide.average), color: [22, 163, 74] },
        { label: "رضایت", value: `%${overall.siteWide.satisfactionRate}`, color: [217, 119, 6] },
      ]) {
        doc.setFillColor(s.color[0], s.color[1], s.color[2]);
        doc.roundedRect(bx, y, boxW, 18, 2, 2, "F");
        doc.setTextColor(255, 255, 255);
        vazir(11);
        doc.text(s.value, bx + boxW / 2, y + 7, { align: "center" });
        vazir(6);
        doc.text(s.label, bx + boxW / 2, y + 14, { align: "center" });
        bx += boxW + 5;
      }
      y += 28;
    }

    // Boards
    if (overall.boards.length > 0) {
      if (y > 240) { doc.addPage(); y = margin; writeHeader(); }
      doc.setTextColor(37, 99, 235);
      vazir(14);
      doc.text("بر اساس هیئت", margin, y);
      y += 10;
      doc.setTextColor(0, 0, 0);

      const boardRows = overall.boards.map((b) => [b.name, String(b.stats.totalResponses), String(b.stats.average), `%${b.stats.satisfactionRate}`]);
      autoTable(doc, {
        head: [["هیئت", "پاسخ", "میانگین", "رضایت"]],
        body: boardRows,
        startY: y,
        styles: { font: "Vazir", fontSize: 8, halign: "center" },
        headStyles: { fillColor: [37, 99, 235], textColor: [255, 255, 255] },
        tableWidth: pageW,
        margin: { left: margin },
      });
      y = (doc as any).lastAutoTable.finalY + 10;
    }

    // Sports
    if (overall.sports.length > 0) {
      if (y > 240) { doc.addPage(); y = margin; writeHeader(); }
      doc.setTextColor(37, 99, 235);
      vazir(14);
      doc.text("بر اساس رشته ورزشی", margin, y);
      y += 10;
      doc.setTextColor(0, 0, 0);

      const sportRows = overall.sports.map((s) => [s.name, s.boardName, String(s.stats.totalResponses), String(s.stats.average), `%${s.stats.satisfactionRate}`]);
      autoTable(doc, {
        head: [["رشته", "هیئت", "پاسخ", "میانگین", "رضایت"]],
        body: sportRows,
        startY: y,
        styles: { font: "Vazir", fontSize: 8, halign: "center" },
        headStyles: { fillColor: [37, 99, 235], textColor: [255, 255, 255] },
        tableWidth: pageW,
        margin: { left: margin },
      });
      y = (doc as any).lastAutoTable.finalY + 10;
    }

    writeFooter();
    doc.save(`overall-survey-report-${Date.now()}.pdf`);
  };

  const exportOverallExcel = () => {
    if (!overall) return;
    const wb = XLSX.utils.book_new();

    // Sheet 1: Site-wide
    if (overall.siteWide) {
      const siteRows = [{
        "بخش": "کل سامانه",
        "تعداد پاسخ": overall.siteWide.totalResponses,
        "میانگین": overall.siteWide.average,
        "درصد رضایت": overall.siteWide.satisfactionRate,
      }];
      let ws = XLSX.utils.json_to_sheet(siteRows);
      XLSX.utils.book_append_sheet(wb, ws, "کل سامانه");
    }

    // Sheet 2: Boards
    if (overall.boards.length > 0) {
      const boardRows = overall.boards.map((b) => ({
        "هیئت": b.name,
        "تعداد پاسخ": b.stats.totalResponses,
        "میانگین": b.stats.average,
        "درصد رضایت": b.stats.satisfactionRate,
        "۱": b.stats.distribution.find((d) => d.value === "1")?._count || 0,
        "۲": b.stats.distribution.find((d) => d.value === "2")?._count || 0,
        "۳": b.stats.distribution.find((d) => d.value === "3")?._count || 0,
        "۴": b.stats.distribution.find((d) => d.value === "4")?._count || 0,
        "۵": b.stats.distribution.find((d) => d.value === "5")?._count || 0,
      }));
      let ws = XLSX.utils.json_to_sheet(boardRows);
      XLSX.utils.book_append_sheet(wb, ws, "هیئت‌ها");
    }

    // Sheet 3: Sports
    if (overall.sports.length > 0) {
      const sportRows = overall.sports.map((s) => ({
        "رشته": s.name,
        "هیئت": s.boardName,
        "تعداد پاسخ": s.stats.totalResponses,
        "میانگین": s.stats.average,
        "درصد رضایت": s.stats.satisfactionRate,
        "۱": s.stats.distribution.find((d) => d.value === "1")?._count || 0,
        "۲": s.stats.distribution.find((d) => d.value === "2")?._count || 0,
        "۳": s.stats.distribution.find((d) => d.value === "3")?._count || 0,
        "۴": s.stats.distribution.find((d) => d.value === "4")?._count || 0,
        "۵": s.stats.distribution.find((d) => d.value === "5")?._count || 0,
      }));
      let ws = XLSX.utils.json_to_sheet(sportRows);
      XLSX.utils.book_append_sheet(wb, ws, "رشته‌ها");
    }

    XLSX.writeFile(wb, `overall-survey-report-${Date.now()}.xlsx`);
  };

  const colors = ["bg-red-500", "bg-orange-500", "bg-amber-400", "bg-lime-500", "bg-green-500"];
  const ratingLabels = ["خیلی کم", "کم", "متوسط", "زیاد", "خیلی زیاد"];

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">گزارش نظرسنجی‌ها</h1>
        <div className="flex gap-2">
          {tab === "surveys" ? (
            <>
              <Button className="bg-green-600 hover:bg-green-700" onClick={exportPDF}>
                <FileText className="h-4 w-4 ml-1" />
                خروجی PDF
              </Button>
              <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={exportExcel}>
                <Download className="h-4 w-4 ml-1" />
                خروجی Excel
              </Button>
            </>
          ) : (
            <>
              <Button className="bg-green-600 hover:bg-green-700" onClick={exportOverallPDF}>
                <FileText className="h-4 w-4 ml-1" />
                خروجی PDF
              </Button>
              <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={exportOverallExcel}>
                <Download className="h-4 w-4 ml-1" />
                خروجی Excel
              </Button>
            </>
          )}
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-1 mb-6 bg-gray-100 p-1 rounded-lg w-fit">
        <button
          onClick={() => setTab("surveys")}
          className={`px-4 py-2 text-sm rounded-md transition-colors ${tab === "surveys" ? "bg-white text-gray-900 shadow-sm font-medium" : "text-gray-500 hover:text-gray-700"}`}
        >
          گزارش نظرسنجی‌ها
        </button>
        <button
          onClick={() => setTab("overall")}
          className={`px-4 py-2 text-sm rounded-md transition-colors ${tab === "overall" ? "bg-white text-gray-900 shadow-sm font-medium" : "text-gray-500 hover:text-gray-700"}`}
        >
          گزارش کلی
        </button>
      </div>

      {/* Filters (only for surveys tab) */}
      {tab === "surveys" && (
        <div className="flex gap-3 mb-6 flex-wrap">
          <select
            className="px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]"
            value={surveyFilter}
            onChange={(e) => setSurveyFilter(e.target.value)}
          >
            <option value="">همه نظرسنجی‌ها</option>
            {reports.map((r) => (
              <option key={r.id} value={r.id}>{r.title}</option>
            ))}
          </select>
          <select
            className="px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]"
            value={courseFilter}
            onChange={(e) => setCourseFilter(e.target.value)}
          >
            <option value="">همه دوره‌ها</option>
            {courses.map((c) => (
              <option key={c.id} value={c.id}>{c.title}</option>
            ))}
          </select>
          <Button variant="outline" onClick={() => load()}><Search className="h-4 w-4 ml-1" />اعمال فیلتر</Button>
        </div>
      )}

      {tab === "surveys" ? (
        loading ? (
          <p className="text-gray-500 text-center py-12">در حال بارگذاری...</p>
        ) : reports.length === 0 ? (
          <p className="text-gray-500 text-center py-12">هیچ داده‌ای یافت نشد</p>
        ) : (
          <div className="space-y-6">
            {reports.map((report) => (
              <div key={report.id} className="bg-white rounded-xl border overflow-hidden">
                {/* Header */}
                <div className="p-6 border-b">
                  <h2 className="text-lg font-bold text-gray-900 mb-4">{report.title}</h2>
                  <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                    <div className="bg-blue-50 rounded-lg p-4 text-center">
                      <div className="text-2xl font-bold text-[#2563EB]">{report.totalResponses}</div>
                      <div className="text-xs text-gray-600 mt-1">تعداد پاسخ</div>
                    </div>
                    <div className="bg-green-50 rounded-lg p-4 text-center">
                      <div className="text-2xl font-bold text-green-700">{report.overallAverage}</div>
                      <div className="text-xs text-gray-600 mt-1">میانگین (از ۵)</div>
                    </div>
                    <div className="bg-amber-50 rounded-lg p-4 text-center">
                      <div className="text-2xl font-bold text-amber-700">%{report.satisfactionRate}</div>
                      <div className="text-xs text-gray-600 mt-1">درصد رضایت</div>
                    </div>
                    <div className="bg-purple-50 rounded-lg p-4 text-center">
                      <div className="text-2xl font-bold text-purple-700">{report.courses.length}</div>
                      <div className="text-xs text-gray-600 mt-1">دوره‌ها</div>
                    </div>
                  </div>

                  {/* Overall distribution bar chart */}
                  {(() => {
                    const dist: Record<string, number> = {};
                    let total = 0;
                    for (const q of report.questions) {
                      for (const d of q.distribution) {
                        dist[d.value] = (dist[d.value] || 0) + d._count;
                        total += d._count;
                      }
                    }
                    return (
                      <div className="mt-6">
                        <h3 className="text-sm font-medium text-gray-700 mb-3">توزیع کل امتیازات</h3>
                        <div className="flex items-end gap-2 h-40">
                          {[1, 2, 3, 4, 5].map((v) => {
                            const count = dist[String(v)] || 0;
                            const pct = total > 0 ? (count / total) * 100 : 0;
                            return (
                              <div key={v} className="flex-1 flex flex-col items-center h-full justify-end">
                                <span className="text-xs font-bold text-gray-700 mb-1">{count}</span>
                                <div className="w-full rounded-t-md relative" style={{ height: `${pct}%`, minHeight: count > 0 ? "4px" : "0" }}>
                                  <div className={`absolute inset-0 rounded-t-md ${colors[v - 1]} opacity-80`} />
                                  <div className={`absolute inset-0 rounded-t-md ${colors[v - 1]} opacity-40 blur-sm`} />
                                </div>
                                <span className="text-xs text-gray-500 mt-1.5">{v}</span>
                                <span className="text-[10px] text-gray-400">{Math.round(pct)}%</span>
                              </div>
                            );
                          })}
                        </div>
                        <div className="flex justify-between mt-2">
                          {ratingLabels.map((l, i) => (
                            <span key={i} className="text-[10px] text-gray-400 text-center flex-1">{l}</span>
                          ))}
                        </div>
                      </div>
                    );
                  })()}
                </div>

                {/* Per-question breakdown */}
                <div className="p-6 space-y-4">
                  {report.questions.map((q) => (
                    <div key={q.id}>
                      <button
                        onClick={() => setExpanded(expanded === q.id ? null : q.id)}
                        className="flex items-center justify-between w-full text-right"
                      >
                        <div className="flex items-center gap-3">
                          <span className="font-medium text-gray-900">{q.title}</span>
                          <span className="text-xs text-gray-500">({q.count} پاسخ)</span>
                        </div>
                        <div className="flex items-center gap-3">
                          <span className="text-sm font-bold text-[#2563EB]">{q.average}</span>
                          {expanded === q.id ? <ChevronUp className="h-4 w-4 text-gray-400" /> : <ChevronDown className="h-4 w-4 text-gray-400" />}
                        </div>
                      </button>

                      <div className="mt-2 flex gap-1">
                        {[1, 2, 3, 4, 5].map((v) => {
                          const item = q.distribution.find((d) => d.value === String(v));
                          const pct = q.count > 0 ? ((item?._count || 0) / q.count) * 100 : 0;
                          return (
                            <div key={v} className="flex-1">
                              <div className="h-6 bg-gray-100 rounded overflow-hidden">
                                <div className={`h-full ${colors[v - 1]} transition-all`} style={{ width: `${pct}%` }} />
                              </div>
                              <div className="text-center text-xs text-gray-500 mt-0.5">{v}: {item?._count || 0}</div>
                            </div>
                          );
                        })}
                      </div>

                      {expanded === q.id && (
                        <div className="mt-3 bg-gray-50 rounded-lg p-3">
                          {q.individuals.length === 0 ? (
                            <p className="text-xs text-gray-500">بدون پاسخ</p>
                          ) : (
                            <table className="w-full text-xs">
                              <thead>
                                <tr className="text-gray-600 border-b">
                                  <th className="text-right p-2 font-medium">کاربر</th>
                                  <th className="text-right p-2 font-medium">دوره</th>
                                  <th className="text-center p-2 font-medium">امتیاز</th>
                                </tr>
                              </thead>
                              <tbody>
                                {q.individuals.map((ind, i) => (
                                  <tr key={i} className="border-b last:border-0">
                                    <td className="p-2 text-gray-900">{ind.fullName || ind.phone}</td>
                                    <td className="p-2 text-gray-500">{ind.courseTitle}</td>
                                    <td className="p-2 text-center font-bold">{ind.value}</td>
                                  </tr>
                                ))}
                              </tbody>
                            </table>
                          )}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )
      ) : (
        /* Overall Report Tab */
        loading ? (
          <p className="text-gray-500 text-center py-12">در حال بارگذاری...</p>
        ) : overall ? (
          <div className="space-y-6">
            {/* Site-wide (only SUPER_ADMIN) */}
            {overall.siteWide && (
              <div className="bg-white rounded-xl border p-6">
                <h2 className="text-lg font-bold text-gray-900 mb-4">{overall.siteWide.label}</h2>
                <div className="grid grid-cols-3 gap-4 mb-6">
                  <div className="bg-blue-50 rounded-lg p-4 text-center">
                    <div className="text-2xl font-bold text-[#2563EB]">{overall.siteWide.totalResponses}</div>
                    <div className="text-xs text-gray-600 mt-1">تعداد پاسخ</div>
                  </div>
                  <div className="bg-green-50 rounded-lg p-4 text-center">
                    <div className="text-2xl font-bold text-green-700">{overall.siteWide.average}</div>
                    <div className="text-xs text-gray-600 mt-1">میانگین (از ۵)</div>
                  </div>
                  <div className="bg-amber-50 rounded-lg p-4 text-center">
                    <div className="text-2xl font-bold text-amber-700">%{overall.siteWide.satisfactionRate}</div>
                    <div className="text-xs text-gray-600 mt-1">درصد رضایت</div>
                  </div>
                </div>
                <div className="mt-4">
                  <h3 className="text-sm font-medium text-gray-700 mb-3">توزیع امتیازات</h3>
                  <div className="flex gap-1">
                    {[1, 2, 3, 4, 5].map((v) => {
                      const item = overall.siteWide!.distribution.find((d) => d.value === String(v));
                      const pct = overall.siteWide!.totalResponses > 0 ? ((item?._count || 0) / overall.siteWide!.totalResponses) * 100 : 0;
                      return (
                        <div key={v} className="flex-1">
                          <div className="h-6 bg-gray-100 rounded overflow-hidden">
                            <div className={`h-full ${colors[v - 1]} transition-all`} style={{ width: `${pct}%` }} />
                          </div>
                          <div className="text-center text-xs text-gray-500 mt-0.5">{v}: {item?._count || 0}</div>
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>
            )}

            {/* By Board */}
            <div className="bg-white rounded-xl border p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-4">بر اساس هیئت</h2>
              {overall.boards.length === 0 ? (
                <p className="text-gray-500 text-center py-4">هیئتی یافت نشد</p>
              ) : (
                <div className="grid gap-4 md:grid-cols-2">
                  {overall.boards.map((board) => (
                    <div key={board.id} className="border rounded-lg p-4">
                      <h3 className="font-semibold text-gray-900 mb-3">{board.name}</h3>
                      <div className="grid grid-cols-3 gap-2 mb-3">
                        <div className="text-center">
                          <div className="text-lg font-bold text-[#2563EB]">{board.stats.totalResponses}</div>
                          <div className="text-[10px] text-gray-500">پاسخ</div>
                        </div>
                        <div className="text-center">
                          <div className="text-lg font-bold text-green-700">{board.stats.average}</div>
                          <div className="text-[10px] text-gray-500">میانگین</div>
                        </div>
                        <div className="text-center">
                          <div className="text-lg font-bold text-amber-700">%{board.stats.satisfactionRate}</div>
                          <div className="text-[10px] text-gray-500">رضایت</div>
                        </div>
                      </div>
                      <div className="flex gap-0.5">
                        {[1, 2, 3, 4, 5].map((v) => {
                          const item = board.stats.distribution.find((d) => d.value === String(v));
                          const pct = board.stats.totalResponses > 0 ? ((item?._count || 0) / board.stats.totalResponses) * 100 : 0;
                          return <div key={v} className="flex-1 h-1.5 bg-gray-100 rounded"><div className={`h-full rounded ${colors[v - 1]}`} style={{ width: `${pct}%` }} /></div>;
                        })}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>

            {/* By Sport */}
            <div className="bg-white rounded-xl border p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-4">بر اساس رشته ورزشی</h2>
              {overall.sports.length === 0 ? (
                <p className="text-gray-500 text-center py-4">رشته‌ای یافت نشد</p>
              ) : (
                <div className="overflow-x-auto">
                  <table className="w-full text-sm">
                    <thead className="bg-gray-50 text-gray-600">
                      <tr>
                        <th className="text-right p-3 font-medium">رشته</th>
                        <th className="text-right p-3 font-medium">هیئت</th>
                        <th className="text-center p-3 font-medium">پاسخ</th>
                        <th className="text-center p-3 font-medium">میانگین</th>
                        <th className="text-center p-3 font-medium">رضایت</th>
                        <th className="text-center p-3 font-medium">توزیع</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y">
                      {overall.sports.map((sport) => (
                        <tr key={sport.id}>
                          <td className="p-3 font-medium text-gray-900">{sport.name}</td>
                          <td className="p-3 text-gray-500">{sport.boardName}</td>
                          <td className="p-3 text-center text-gray-700">{sport.stats.totalResponses}</td>
                          <td className="p-3 text-center font-bold text-green-700">{sport.stats.average}</td>
                          <td className="p-3 text-center font-bold text-amber-700">%{sport.stats.satisfactionRate}</td>
                          <td className="p-3">
                            <div className="flex gap-0.5 max-w-[150px] mx-auto">
                              {[1, 2, 3, 4, 5].map((v) => {
                                const item = sport.stats.distribution.find((d) => d.value === String(v));
                                const pct = sport.stats.totalResponses > 0 ? ((item?._count || 0) / sport.stats.totalResponses) * 100 : 0;
                                return <div key={v} className="flex-1 h-1.5 bg-gray-100 rounded"><div className={`h-full rounded ${colors[v - 1]}`} style={{ width: `${pct}%` }} /></div>;
                              })}
                            </div>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          </div>
        ) : (
          <p className="text-gray-500 text-center py-12">خطا در بارگذاری داده‌ها</p>
        )
      )}
    </div>
  );
}
