"use client";
import { useState, useEffect } from "react";
import DashboardLayout from "@/components/layout/DashboardLayout";
import { getApiUrl } from "@/lib/api";

interface User {
  id: number;
  username: string;
  fullName: string;
  email: string;
  team: string;
  role: string;
  active: boolean;
}

const ROLES = ["SUPER_ADMIN", "SERVICE_ENGINEER", "SALES_EXECUTIVE", "MAIN_SECRETARY", "SALES_SECRETARY"];
const TEAMS = ["SERVICE", "SALES", "ADMIN"];

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [form, setForm] = useState({ username: "", password: "", fullName: "", email: "", team: "SERVICE", role: "SERVICE_ENGINEER" });
  const [error, setError] = useState("");
  const [saving, setSaving] = useState(false);

  const fetchUsers = async () => {
    try {
      const res = await fetch(getApiUrl("/api/admin/users"));
      const data = await res.json();
      setUsers(data);
    } catch { setError("Failed to load users"); }
    finally { setLoading(false); }
  };

  useEffect(() => { fetchUsers(); }, []);

  const createUser = async () => {
    if (!form.username || !form.password || !form.fullName) { setError("Username, password, full name required"); return; }
    setSaving(true); setError("");
    try {
      const res = await fetch(getApiUrl("/api/admin/users"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!res.ok) { const t = await res.text(); setError(t); return; }
      setShowModal(false);
      setForm({ username: "", password: "", fullName: "", email: "", team: "SERVICE", role: "SERVICE_ENGINEER" });
      fetchUsers();
    } catch { setError("Failed to create user"); }
    finally { setSaving(false); }
  };

  const toggleActive = async (id: number) => {
    await fetch(getApiUrl(`/api/admin/users/${id}/toggle-active`), { method: "PUT" });
    fetchUsers();
  };

  const deleteUser = async (id: number) => {
    if (!confirm("Delete this user?")) return;
    await fetch(getApiUrl(`/api/admin/users/${id}`), { method: "DELETE" });
    fetchUsers();
  };

  const roleColor = (role: string) => {
    if (role === "SUPER_ADMIN") return "bg-red-100 text-red-700";
    if (role.includes("ENGINEER")) return "bg-blue-100 text-blue-700";
    if (role.includes("SALES")) return "bg-green-100 text-green-700";
    if (role.includes("SECRETARY")) return "bg-purple-100 text-purple-700";
    return "bg-gray-100 text-gray-700";
  };

  return (
    <DashboardLayout>
      <div className="p-6">
        <div className="flex justify-between items-center mb-6">
          <div>
            <h1 className="text-2xl font-bold text-gray-900">User Management</h1>
            <p className="text-gray-500 text-sm mt-1">Create and manage employee login accounts</p>
          </div>
          <button onClick={() => setShowModal(true)} className="bg-[#1296E8] text-white px-4 py-2 rounded-xl font-medium hover:bg-blue-600 transition">+ Add User</button>
        </div>

        {error && <div className="bg-red-50 text-red-600 px-4 py-2 rounded-xl mb-4 text-sm">{error}</div>}

        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
          {loading ? (
            <div className="p-8 text-center text-gray-400">Loading...</div>
          ) : users.length === 0 ? (
            <div className="p-8 text-center text-gray-400">No users yet. Add one above.</div>
          ) : (
            <table className="w-full">
              <thead className="bg-gray-50 border-b border-gray-100">
                <tr>
                  {["Full Name","Username","Team","Role","Status","Actions"].map(h => (
                    <th key={h} className="text-left px-4 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-50">
                {users.map(u => (
                  <tr key={u.id} className="hover:bg-gray-50 transition">
                    <td className="px-4 py-3">
                      <div className="font-medium text-gray-900">{u.fullName}</div>
                      <div className="text-xs text-gray-400">{u.email}</div>
                    </td>
                    <td className="px-4 py-3 text-gray-600 font-mono text-sm">{u.username}</td>
                    <td className="px-4 py-3">
                      <span className="bg-gray-100 text-gray-700 px-2 py-1 rounded-lg text-xs font-medium">{u.team}</span>
                    </td>
                    <td className="px-4 py-3">
                      <span className={`px-2 py-1 rounded-lg text-xs font-medium ${roleColor(u.role)}`}>{u.role.replace(/_/g, " ")}</span>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => toggleActive(u.id)} className={`px-2 py-1 rounded-lg text-xs font-medium ${u.active ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-500"}`}>
                        {u.active ? "Active" : "Inactive"}
                      </button>
                    </td>
                    <td className="px-4 py-3">
                      <button onClick={() => deleteUser(u.id)} className="text-red-500 hover:text-red-700 text-sm font-medium">Delete</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>

        {showModal && (
          <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
            <div className="bg-white rounded-2xl shadow-xl w-full max-w-md p-6">
              <h2 className="text-xl font-bold text-gray-900 mb-4">Create User Account</h2>
              {error && <div className="bg-red-50 text-red-600 px-3 py-2 rounded-lg mb-3 text-sm">{error}</div>}
              <div className="space-y-3">
                <input className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm" placeholder="Full Name *" value={form.fullName} onChange={e => setForm({...form, fullName: e.target.value})} />
                <input className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm" placeholder="Username *" value={form.username} onChange={e => setForm({...form, username: e.target.value})} />
                <input className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm" placeholder="Password *" type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} />
                <input className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm" placeholder="Email (optional)" value={form.email} onChange={e => setForm({...form, email: e.target.value})} />
                <select className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm" value={form.team} onChange={e => setForm({...form, team: e.target.value})}>
                  {TEAMS.map(t => <option key={t}>{t}</option>)}
                </select>
                <select className="w-full border border-gray-200 rounded-xl px-3 py-2 text-sm" value={form.role} onChange={e => setForm({...form, role: e.target.value})}>
                  {ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, " ")}</option>)}
                </select>
              </div>
              <div className="flex gap-3 mt-5">
                <button onClick={() => { setShowModal(false); setError(""); }} className="flex-1 border border-gray-200 text-gray-600 rounded-xl py-2 text-sm hover:bg-gray-50">Cancel</button>
                <button onClick={createUser} disabled={saving} className="flex-1 bg-[#1296E8] text-white rounded-xl py-2 text-sm font-medium hover:bg-blue-600 disabled:opacity-50">{saving ? "Creating..." : "Create User"}</button>
              </div>
            </div>
          </div>
        )}
      </div>
    </DashboardLayout>
  );
}
