"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Shield, ShieldOff, Search, Plus, X, Trash2, Loader2, Building2, KeyRound } from "lucide-react";

interface AdminUser {
  id: string;
  phone: string;
  role: string;
  isActive: boolean;
  isVerified: boolean;
  createdAt: string;
  profile?: { fullName?: string };
}

export default function AdminUsers() {
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [search, setSearch] = useState("");
  const [showCreate, setShowCreate] = useState(false);
  const [editTarget, setEditTarget] = useState<AdminUser | null>(null);
  const [boardTarget, setBoardTarget] = useState<AdminUser | null>(null);
  const [passwordTarget, setPasswordTarget] = useState<AdminUser | null>(null);
  const [newPassword, setNewPassword] = useState("");
  const [adminPassword, setAdminPassword] = useState("");
  const [allBoards, setAllBoards] = useState<{ id: string; name: string }[]>([]);
  const [selectedBoardIds, setSelectedBoardIds] = useState<string[]>([]);
  const [newPhone, setNewPhone] = useState("");
  const [newRole, setNewRole] = useState("ATHLETE");
  const [createPassword, setCreatePassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

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

  const load = () => {
    fetch("/api/users", {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => {
        if (!r.ok) throw new Error();
        return r.json();
      })
      .then((data) => { if (Array.isArray(data)) setUsers(data); })
      .catch(() => {});
  };

  useEffect(load, []);

  const filtered = users.filter((u) =>
    u.phone.includes(search) || u.profile?.fullName?.includes(search)
  );

  const toggleActive = async (targetId: string, current: boolean) => {
    await fetch("/api/users", {
      method: "PATCH",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({ targetId, isActive: !current }),
    });
    load();
  };

  const handleCreate = async () => {
    setError("");
    if (!newPhone.trim()) { setError("شماره موبایل را وارد کنید"); return; }
    setLoading(true);
    const res = await fetch("/api/users", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({ phone: newPhone.trim(), role: newRole, password: createPassword || undefined }),
    });
    const data = await res.json();
    setLoading(false);
    if (!res.ok) { setError(data.error || "خطا"); return; }
    setShowCreate(false);
    setNewPhone("");
    setNewRole("ATHLETE");
    setCreatePassword("");
    load();
  };

  const handleEditRole = async () => {
    if (!editTarget) return;
    setError("");
    setLoading(true);
    const res = await fetch("/api/users", {
      method: "PATCH",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({ targetId: editTarget.id, role: editTarget.role }),
    });
    setLoading(false);
    if (!res.ok) { const d = await res.json(); setError(d.error || "خطا"); return; }
    setEditTarget(null);
    load();
  };

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

  const openBoardModal = async (u: AdminUser) => {
    setBoardTarget(u);
    const [boardsRes, assignedRes] = await Promise.all([
      fetch("/api/boards"),
      fetch(`/api/admin/boards?adminId=${u.id}`, { headers: { Authorization: `Bearer ${token}` } }),
    ]);
    if (boardsRes.ok) {
      const boards = await boardsRes.json();
      setAllBoards(Array.isArray(boards) ? boards : []);
    }
    if (assignedRes.ok) {
      const assigned = await assignedRes.json();
      setSelectedBoardIds((Array.isArray(assigned) ? assigned : []).map((b: { id: string }) => b.id));
    }
  };

  const handleAssignBoards = async () => {
    if (!boardTarget) return;
    setLoading(true);
    const res = await fetch("/api/admin/boards", {
      method: "POST",
      headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
      body: JSON.stringify({ adminId: boardTarget.id, boardIds: selectedBoardIds }),
    });
    setLoading(false);
    if (res.ok) {
      setBoardTarget(null);
      setSelectedBoardIds([]);
    }
  };

  const roleLabel = (r: string) =>
    r === "SUPER_ADMIN" ? "مدیر ارشد" : r === "ADMIN" ? "مدیر" : r === "COACH" ? "مربی" : r === "JUDGE" ? "داور" : "ورزشکار";

  const roleColor = (r: string) =>
    r === "SUPER_ADMIN" ? "bg-purple-50 text-purple-700" :
    r === "ADMIN" ? "bg-blue-50 text-blue-700" :
    r === "COACH" ? "bg-green-50 text-green-700" :
    r === "JUDGE" ? "bg-amber-50 text-amber-700" :
    "bg-gray-100 text-gray-600";

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

      <div className="relative mb-4">
        <Search className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
        <input
          placeholder="جستجوی کاربر..."
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full px-3 pr-10 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-[#2563EB]"
        />
      </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-right p-3 font-medium">تاریخ ثبت‌نام</th>
              <th className="text-left p-3 font-medium">عملیات</th>
            </tr>
          </thead>
          <tbody className="divide-y">
            {filtered.map((u) => (
              <tr key={u.id}>
                <td className="p-3">
                  {u.profile ? u.profile.fullName || "---" : "---"}
                </td>
                <td className="p-3 text-gray-500" dir="ltr">{u.phone}</td>
                <td className="p-3">
                  <button
                    className={`text-xs px-2 py-0.5 rounded-full cursor-pointer hover:opacity-80 ${roleColor(u.role)}`}
                    onClick={() => setEditTarget(u)}
                  >
                    {roleLabel(u.role)}
                  </button>
                </td>
                <td className="p-3">
                  <span className={`text-xs ${u.isActive ? "text-green-600" : "text-red-600"}`}>
                    {u.isActive ? "فعال" : "مسدود"}
                  </span>
                </td>
                <td className="p-3 text-gray-500">
                  {new Date(u.createdAt).toLocaleDateString("fa-IR")}
                </td>
                <td className="p-3 text-left">
                  <div className="flex items-center justify-end gap-1">
                    {u.role === "ADMIN" && (
                      <Button variant="ghost" size="icon-xs" onClick={() => openBoardModal(u)} title="مدیریت هیئت‌ها">
                        <Building2 className="h-3.5 w-3.5 text-[#2563EB]" />
                      </Button>
                    )}
                    <Button variant="ghost" size="icon-xs" onClick={() => { setPasswordTarget(u); setNewPassword(""); setAdminPassword(""); setError(""); }} title="تغییر رمز عبور">
                      <KeyRound className="h-3.5 w-3.5 text-amber-600" />
                    </Button>
                    <Button variant="ghost" size="icon-xs" onClick={() => toggleActive(u.id, u.isActive)}>
                      {u.isActive ? <Shield className="h-3.5 w-3.5 text-green-600" /> : <ShieldOff className="h-3.5 w-3.5 text-red-600" />}
                    </Button>
                    <Button variant="ghost" size="icon-xs" onClick={() => handleDelete(u.id)}>
                      <Trash2 className="h-3.5 w-3.5 text-red-500" />
                    </Button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Create Modal */}
      {showCreate && (
        <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={() => { setShowCreate(false); setError(""); }}>
                <X className="h-5 w-5 text-gray-400 hover:text-gray-600" />
              </button>
            </div>
            <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="شماره موبایل"
              value={newPhone}
              onChange={(e) => setNewPhone(e.target.value)}
              dir="ltr"
            />
            <select
              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"
              value={newRole}
              onChange={(e) => setNewRole(e.target.value)}
            >
              <option value="ATHLETE">ورزشکار</option>
              <option value="COACH">مربی</option>
              <option value="JUDGE">داور</option>
              <option value="ADMIN">مدیر</option>
            </select>
            <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="رمز عبور (اختیاری — برای تحویل فیزیکی به کاربر)"
              value={createPassword}
              onChange={(e) => setCreatePassword(e.target.value)}
              type="password"
            />
            {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={() => { setShowCreate(false); setError(""); }}>
                انصراف
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Role 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>
            <select
              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"
              value={editTarget.role}
              onChange={(e) => setEditTarget({ ...editTarget, role: e.target.value })}
            >
              <option value="ATHLETE">ورزشکار</option>
              <option value="COACH">مربی</option>
              <option value="JUDGE">داور</option>
              <option value="ADMIN">مدیر</option>
            </select>
            {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={handleEditRole} 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>
      )}

      {/* Password Change Modal */}
      {passwordTarget && (
        <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={() => { setPasswordTarget(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">کاربر: {passwordTarget.phone}</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="رمز عبور جدید (حداقل ۴ کاراکتر)"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              type="password"
            />
            <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="رمز عبور خود را وارد کنید (مدیر)"
              value={adminPassword}
              onChange={(e) => setAdminPassword(e.target.value)}
              type="password"
            />
            {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={async () => {
                  if (!newPassword || newPassword.length < 4) { setError("رمز عبور حداقل ۴ کاراکتر"); return; }
                  if (!adminPassword) { setError("رمز عبور مدیر را وارد کنید"); return; }
                  setLoading(true);
                  setError("");
                  const res = await fetch("/api/users", {
                    method: "PATCH",
                    headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
                    body: JSON.stringify({ targetId: passwordTarget.id, password: newPassword, adminPassword }),
                  });
                  setLoading(false);
                  if (!res.ok) { const d = await res.json(); setError(d.error || "خطا"); return; }
                  setPasswordTarget(null);
                  setNewPassword("");
                  setAdminPassword("");
                }}
                disabled={loading}
              >
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "ذخیره"}
              </Button>
              <Button variant="outline" className="flex-1" onClick={() => { setPasswordTarget(null); setError(""); }}>
                انصراف
              </Button>
            </div>
          </div>
        </div>
      )}

      {/* Board Assignment Modal */}
      {boardTarget && (
        <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-md mx-4 shadow-xl">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-lg font-semibold text-gray-900">مدیریت هیئت‌های {boardTarget.phone}</h2>
              <button onClick={() => { setBoardTarget(null); setSelectedBoardIds([]); }}>
                <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>
            <div className="space-y-2 max-h-64 overflow-y-auto">
              {allBoards.map((board) => (
                <label key={board.id} className="flex items-center gap-3 p-3 rounded-lg border hover:bg-gray-50 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={selectedBoardIds.includes(board.id)}
                    onChange={(e) => {
                      if (e.target.checked) setSelectedBoardIds((prev) => [...prev, board.id]);
                      else setSelectedBoardIds((prev) => prev.filter((id) => id !== board.id));
                    }}
                    className="h-4 w-4 text-[#2563EB] rounded"
                  />
                  <span className="text-sm text-gray-900">{board.name}</span>
                </label>
              ))}
            </div>
            {error && <p className="text-sm text-red-600 mt-3">{error}</p>}
            <div className="flex gap-3 mt-4">
              <Button className="bg-[#2563EB] hover:bg-[#1D4ED8] text-white flex-1" onClick={handleAssignBoards} disabled={loading}>
                {loading ? <Loader2 className="h-4 w-4 animate-spin" /> : "ذخیره"}
              </Button>
              <Button variant="outline" className="flex-1" onClick={() => { setBoardTarget(null); setSelectedBoardIds([]); }}>
                انصراف
              </Button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
