"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Plus, Edit, Trash2, BarChart3 } from "lucide-react";

interface SurveyQuestion {
  id: string;
  title: string;
}

interface Survey {
  id: string;
  title: string;
  isActive: boolean;
  questions: SurveyQuestion[];
  courses: Array<{ id: string; title: string }>;
}

export default function AdminSurveys() {
  const router = useRouter();
  const [surveys, setSurveys] = useState<Survey[]>([]);

  const load = () => {
    fetch("/api/surveys", {
      headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
    })
      .then((r) => r.json())
      .then((data) => { if (Array.isArray(data)) setSurveys(data); })
      .catch(() => {});
  };

  useEffect(load, []);

  const handleDelete = async (id: string) => {
    if (!confirm("حذف شود؟")) return;
    const token = localStorage.getItem("auth_token");
    const res = await fetch(`/api/surveys/${id}`, {
      method: "DELETE",
      headers: { Authorization: `Bearer ${token}` },
    });
    if (res.ok) setSurveys((prev) => prev.filter((s) => s.id !== id));
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-gray-900">مدیریت نظرسنجی‌ها</h1>
        <Button className="bg-[#2563EB] hover:bg-[#1D4ED8]" onClick={() => router.push("/dashboard/admin/surveys/new")}>
          <Plus className="h-4 w-4 ml-1" />
          نظرسنجی جدید
        </Button>
      </div>

      {surveys.map((survey) => (
        <div key={survey.id} className="rounded-xl border bg-white p-5 mb-4">
          <div className="flex items-center justify-between mb-3">
            <div>
              <h3 className="font-semibold text-gray-900">{survey.title}</h3>
              <div className="text-sm text-gray-500 mt-1">
                {survey.questions.length} سوال | {survey.courses.length} دوره
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button variant="ghost" size="icon-xs" onClick={() => router.push(`/dashboard/admin/surveys/reports?surveyId=${survey.id}`)}>
                <BarChart3 className="h-3.5 w-3.5 text-[#2563EB]" />
              </Button>
              <Button variant="ghost" size="icon-xs" onClick={() => router.push(`/dashboard/admin/surveys/${survey.id}`)}>
                <Edit className="h-3.5 w-3.5" />
              </Button>
              <Button variant="ghost" size="icon-xs" onClick={() => handleDelete(survey.id)}>
                <Trash2 className="h-3.5 w-3.5 text-red-500" />
              </Button>
              <span className={`text-xs px-2 py-0.5 rounded-full ${survey.isActive ? "bg-green-50 text-green-700" : "bg-gray-100 text-gray-600"}`}>
                {survey.isActive ? "فعال" : "غیرفعال"}
              </span>
            </div>
          </div>
        </div>
      ))}

      {surveys.length === 0 && (
        <div className="text-center py-12 bg-white rounded-xl border">
          <p className="text-gray-500">نظرسنجی‌ای تعریف نشده است</p>
        </div>
      )}
    </div>
  );
}
