"use client";

import { useEffect, useState, Fragment } from "react";
import { Button } from "@/components/ui/button";
import { Plus, Edit, X, Loader2, Trash2 } from "lucide-react";

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

interface CoachUser {
  id: string;
  phone: string;
  role: string;
  isActive: boolean;
  profile?: { fullName?: string };
  _count?: { courseCoaches: number; coachSports: number };
  coachSports?: Array<{ sport: { name: string }; isVerified: boolean }>;
}

export default function AdminCoaches() {
  const [coaches, setCoaches] = useState<CoachUser[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [editTarget, setEditTarget] = useState<CoachUser | null>(null);
  const [phone, setPhone] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [expandedCoachId, setExpandedCoachId] = useState<string | null>(null);
  const [coachCourses, setCoachCourses] = useState<CoachCourse[]>([]);
  const [loadingCourses, setLoadingCourses] = useState(false);

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

  const load = () => {
    fetch("/api/users", {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => r.json())
      .then((all: CoachUser[]) => setCoaches(all.filter((u) => ["COACH", "JUDGE"].includes(u.role))))
      .catch(() => {});
  };

  useEffect(load, []);

  const handleCreate = async () => {
    setError("");
    if (!phone.trim()) { setError("شماره موبایل را وارد کنید"); return; }

    setLoading(true);
    try {
      const res = await fetch("/api/coaches", {
        method: "POST",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ phone: phone.trim() }),
      });
      const data = await res.json();
      if (!res.ok) {
        setError(data.error || "خطا");
      } else {
        setShowModal(false);
        setPhone("");
        load();
      }
    } catch {
      setError("خطا در ارتباط با سرور");
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = (coach: CoachUser) => {
    setEditTarget({ ...coach });
  };

  const handleSaveEdit = async () => {
    if (!editTarget) return;
    setError("");
    setLoading(true);
    try {
      const res = await fetch(`/api/coaches/${editTarget.id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
        body: JSON.stringify({ isActive: editTarget.isActive }),
      });
      if (!res.ok) { const d = await res.json(); setError(d.error || "خطا"); return; }
      setEditTarget(null);
      load();
    } catch {
      setError("خطا در ارتباط با سرور");
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("آیا از حذف این مربی اطمینان دارید؟")) return;
    await fetch(`/api/coaches/${id}`, { method: "DELETE", headers: { Authorization: `Bearer ${token}` } });
    load();
  };

  const toggleCoachCourses = async (coachId: string) => {
    if (expandedCoachId === coachId) {
      setExpandedCoachId(null);
      setCoachCourses([]);
      return;
    }
    setExpandedCoachId(coachId);
    setLoadingCourses(true);
    try {
      const res = await fetch(`/api/courses?coachId=${coachId}&status=ALL`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setCoachCourses(data.map((c: { id: string; title: string }) => ({ id: c.id, title: c.title })));
      }
    } catch {
      setCoachCourses([]);
    } finally {
      setLoadingCourses(false);
    }
  };

  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={() => setShowModal(true)}>
          <Plus className="h-4 w-4 ml-1" />
          مربی جدید
        </Button>
      </div>

      <div className="rounded-xl border bg-white overflow-hidden">
        <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-right p-3 font-medium">وضعیت</th>
              <th className="text-right p-3 font-medium">دوره‌ها</th>
              <th className="text-left p-3 font-medium">عملیات</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {coaches.map((c) => (
              <Fragment key={c.id}>
                <tr>
                  <td className="p-3 font-medium text-gray-900">
                    {c.profile ? c.profile.fullName || "---" : "---"}
                  </td>
                  <td className="p-3 text-gray-500" dir="ltr">{c.phone}</td>
                  <td className="p-3">
                    <span className={`text-xs ${c.isActive ? "text-green-600" : "text-red-600"}`}>
                      {c.isActive ? "فعال" : "غیرفعال"}
                    </span>
                  </td>
                  <td className="p-3 text-gray-500">
                    <button
                      onClick={() => toggleCoachCourses(c.id)}
                      className="text-[#2563EB] hover:underline font-medium cursor-pointer"
                    >
                      {c._count?.courseCoaches || 0}
                    </button>
                  </td>
                  <td className="p-3 text-left">
                    <div className="flex items-center justify-end gap-1">
                      <Button variant="ghost" size="icon-xs" onClick={() => handleEdit(c)}>
                        <Edit className="h-3.5 w-3.5" />
                      </Button>
                      <Button variant="ghost" size="icon-xs" onClick={() => handleDelete(c.id)}>
                        <Trash2 className="h-3.5 w-3.5 text-red-500" />
                      </Button>
                    </div>
                  </td>
                </tr>
                {expandedCoachId === c.id && (
                  <tr>
                    <td colSpan={5} className="bg-gray-50 px-6 py-3">
                      {loadingCourses ? (
                        <span className="text-sm text-gray-400">در حال بارگذاری...</span>
                      ) : coachCourses.length === 0 ? (
                        <span className="text-sm text-gray-400">دوره‌ای یافت نشد</span>
                      ) : (
                        <div className="flex flex-wrap gap-2">
                          {coachCourses.map((course) => (
                            <span key={course.id} className="text-xs bg-blue-50 text-[#2563EB] px-2.5 py-1 rounded-full">
                              {course.title}
                            </span>
                          ))}
                        </div>
                      )}
                    </td>
                  </tr>
                )}
              </Fragment>
            ))}
          </tbody>
        </table>
      </div>

      {/* Create Modal */}
      {showModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white rounded-xl p-6 w-full max-w-sm mx-4 shadow-xl">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900">ایجاد مربی جدید</h2>
              <button onClick={() => { setShowModal(false); setError(""); setPhone(""); }}>
                <X className="h-5 w-5 text-gray-400 hover:text-gray-600" />
              </button>
            </div>
            <p className="text-sm text-gray-500 mb-4">
              شماره موبایل کاربری که نقش مربی بگیرد را وارد کنید.
            </p>
            <input
              className="w-full px-3 py-2.5 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]/20 focus:border-[#2563EB] mb-3"
              placeholder="مثال: 09120000001"
              value={phone}
              onChange={(e) => setPhone(e.target.value)}
              dir="ltr"
            />
            {error && <p className="text-sm text-red-600 mb-3">{error}</p>}
            <div className="flex gap-3">
              <Button className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1" onClick={handleCreate} disabled={loading}>
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "ایجاد مربی"}
              </Button>
              <Button variant="outline" className="flex-1" onClick={() => { setShowModal(false); setError(""); setPhone(""); }}>
                انصراف
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Modal */}
      {editTarget && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40">
          <div className="bg-white rounded-xl p-6 w-full max-w-sm mx-4 shadow-xl">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900">ویرایش مربی</h2>
              <button onClick={() => { setEditTarget(null); setError(""); }}>
                <X className="h-5 w-5 text-gray-400 hover:text-gray-600" />
              </button>
            </div>
            <p className="text-sm text-gray-500 mb-3">{editTarget.phone}</p>
            <label className="flex items-center gap-3 cursor-pointer mb-4">
              <input
                type="checkbox"
                className="w-4 h-4 rounded border-gray-300 text-[#2563EB] focus:ring-[#2563EB]/20"
                checked={editTarget.isActive}
                onChange={(e) => setEditTarget({ ...editTarget, isActive: e.target.checked })}
              />
              <span className="text-sm text-gray-700">فعال</span>
            </label>
            {error && <p className="text-sm text-red-600 mb-3">{error}</p>}
            <div className="flex gap-3">
              <Button className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1" onClick={handleSaveEdit} disabled={loading}>
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "ذخیره"}
              </Button>
              <Button variant="outline" className="flex-1" onClick={() => { setEditTarget(null); setError(""); }}>
                انصراف
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
