"use client";

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Users, BookOpen, UserCheck, Award, BarChart3, TrendingUp } from "lucide-react";
import { useAuth } from "@/lib/stores/auth-store";

interface DashboardData {
  users: { total: number; active: number; athletes: number; coaches: number; judges: number; admins: number };
  courses: { total: number; active: number; registrations: number; completed: number };
  revenue: number;
  satisfaction: { rate: number; totalResponses: number };
  growth: { date: string; count: number }[];
  coachPerformance: { id: string; name: string; courses: number; students: number }[];
  judgePerformance: { id: string; name: string; competitions: number }[];
}

export default function AdminReports() {
  const { logout } = useAuth();
  const router = useRouter();
  const [data, setData] = useState<DashboardData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetch("/api/dashboard", {
      headers: { Authorization: `Bearer ${localStorage.getItem("auth_token")}` },
    })
      .then(async (r) => {
        const body = await r.json();
        if (!r.ok || !body.users) throw new Error();
        setData(body);
      })
      .catch(() => setError(true))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <p className="text-gray-500 text-center py-12">در حال بارگذاری...</p>;
  if (error || !data) return (
    <div className="text-center py-12">
      <p className="text-red-600 mb-4">خطا در دریافت اطلاعات</p>
      <button onClick={() => { logout(); router.push("/auth"); }} className="text-sm text-[#2563EB] underline">ورود مجدد</button>
    </div>
  );

  const maxGrowth = Math.max(...data.growth.map((g) => g.count), 1);

  const persianMonth = (iso: string) => {
    const d = new Date(iso);
    return d.toLocaleDateString("fa-IR", { year: "numeric", month: "2-digit" });
  };

  return (
    <div>
      <h1 className="text-2xl font-bold text-gray-900 mb-2">گزارش‌ها و آمار</h1>
      <p className="text-gray-600 mb-8">آمار کلی سامانه مربیگری ورزشی</p>

      {/* Summary Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-blue-50 flex items-center justify-center"><Users className="h-5 w-5 text-blue-600" /></div>
            <span className="text-sm text-gray-500">کاربران فعال</span>
          </div>
          <div className="text-2xl font-bold text-gray-900">{data.users.active.toLocaleString()}</div>
          <div className="text-xs text-gray-400 mt-1">از {data.users.total} کاربر کل</div>
        </div>

        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-green-50 flex items-center justify-center"><BookOpen className="h-5 w-5 text-green-600" /></div>
            <span className="text-sm text-gray-500">دوره‌های فعال</span>
          </div>
          <div className="text-2xl font-bold text-gray-900">{data.courses.active}</div>
          <div className="text-xs text-gray-400 mt-1">{data.courses.registrations} ثبت‌نام، {data.courses.completed} تکمیل شده</div>
        </div>

        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-amber-50 flex items-center justify-center"><Award className="h-5 w-5 text-amber-600" /></div>
            <span className="text-sm text-gray-500">رضایت سامانه</span>
          </div>
          <div className="text-2xl font-bold text-gray-900">%{data.satisfaction.rate}</div>
          <div className="text-xs text-gray-400 mt-1">{data.satisfaction.totalResponses} پاسخ</div>
        </div>

        <div className="bg-white rounded-xl border p-5">
          <div className="flex items-center gap-3 mb-3">
            <div className="w-10 h-10 rounded-lg bg-purple-50 flex items-center justify-center"><TrendingUp className="h-5 w-5 text-purple-600" /></div>
            <span className="text-sm text-gray-500">درآمد</span>
          </div>
          <div className="text-2xl font-bold text-gray-900">{data.revenue.toLocaleString()}</div>
          <div className="text-xs text-gray-400 mt-1">ریال</div>
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-6 mb-8">
        {/* User Growth Chart */}
        <div className="bg-white rounded-xl border p-5">
          <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <BarChart3 className="h-5 w-5 text-[#2563EB]" />
            رشد کاربران (۶ ماه اخیر)
          </h2>
          {data.growth.length === 0 ? (
            <p className="text-gray-500 text-center py-8 text-sm">داده‌ای وجود ندارد</p>
          ) : (
            <div className="space-y-2">
              {data.growth.map((g) => (
                <div key={g.date} className="flex items-center gap-3">
                  <span className="text-xs text-gray-500 w-16 shrink-0">{persianMonth(g.date)}</span>
                  <div className="flex-1 h-6 bg-gray-100 rounded overflow-hidden">
                    <div
                      className="h-full bg-gradient-to-l from-[#2563EB] to-[#60A5FA] rounded transition-all"
                      style={{ width: `${(g.count / maxGrowth) * 100}%` }}
                    />
                  </div>
                  <span className="text-xs font-bold text-gray-700 w-8 text-left">{g.count}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* User Distribution */}
        <div className="bg-white rounded-xl border p-5">
          <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
            <Users className="h-5 w-5 text-[#2563EB]" />
            توزیع کاربران
          </h2>
          <div className="space-y-3">
            {[
              { label: "ورزشکاران", value: data.users.athletes, color: "bg-blue-500" },
              { label: "مربیان", value: data.users.coaches, color: "bg-green-500" },
              { label: "داوران", value: data.users.judges, color: "bg-amber-500" },
              { label: "مدیران", value: data.users.admins, color: "bg-purple-500" },
            ].map((item) => {
              const pct = data.users.total > 0 ? (item.value / data.users.total) * 100 : 0;
  const persianMonth = (iso: string) => {
    const d = new Date(iso);
    return d.toLocaleDateString("fa-IR", { year: "numeric", month: "2-digit" });
  };

  return (
                <div key={item.label}>
                  <div className="flex items-center justify-between text-sm mb-1">
                    <span className="text-gray-700">{item.label}</span>
                    <span className="text-gray-500">{item.value} کاربر ({pct.toFixed(1)}%)</span>
                  </div>
                  <div className="h-3 bg-gray-100 rounded overflow-hidden">
                    <div className={`h-full ${item.color} rounded transition-all`} style={{ width: `${pct}%` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Coach Performance */}
      <div className="bg-white rounded-xl border p-5 mb-6">
        <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
          <UserCheck className="h-5 w-5 text-[#2563EB]" />
          گزارش عملکرد مربیان
        </h2>
        {data.coachPerformance.length === 0 ? (
          <p className="text-gray-500 text-center py-4 text-sm">مربی‌ای ثبت نشده است</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-gray-600">
                  <th className="text-right p-3 font-medium">مربی</th>
                  <th className="text-right p-3 font-medium">تعداد دوره‌ها</th>
                  <th className="text-right p-3 font-medium">مجموع هنرجویان</th>
                </tr>
              </thead>
              <tbody>
                {data.coachPerformance.map((c) => (
                  <tr key={c.id} className="border-b last:border-0 hover:bg-gray-50/50">
                    <td className="p-3 font-medium text-gray-900">{c.name}</td>
                    <td className="p-3 text-gray-600">{c.courses}</td>
                    <td className="p-3 text-gray-600">{c.students}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Judge Performance */}
      <div className="bg-white rounded-xl border p-5">
        <h2 className="font-semibold text-gray-900 mb-4 flex items-center gap-2">
          <Award className="h-5 w-5 text-[#2563EB]" />
          گزارش عملکرد داوران
        </h2>
        {data.judgePerformance.length === 0 ? (
          <p className="text-gray-500 text-center py-4 text-sm">داوری ثبت نشده است</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b text-gray-600">
                  <th className="text-right p-3 font-medium">داور</th>
                  <th className="text-right p-3 font-medium">تعداد مسابقات</th>
                </tr>
              </thead>
              <tbody>
                {data.judgePerformance.map((j) => (
                  <tr key={j.id} className="border-b last:border-0 hover:bg-gray-50/50">
                    <td className="p-3 font-medium text-gray-900">{j.name}</td>
                    <td className="p-3 text-gray-600">{j.competitions}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
