import { useState } from "react";
import { Users, Plus, Trash2, Search, CheckCircle2, AlertCircle } from "lucide-react";
import CmsLayout from "./CmsLayout";
import { PageHeader, SectionCard, Field, TextInput, Select, SaveBar, Badge, Toggle } from "./ui";
import { useSiteSettings } from "@/hooks/useSiteSettings";

type Role = "admin" | "support" | "billing" | "client";
type User = { id: string; name: string; email: string; role: Role; active: boolean; lastLogin: string };

type UsersState = {
  users: User[];
  permissions: {
    admin: string[];
    support: string[];
    billing: string[];
    client: string[];
  };
  defaultRole: Role;
};

const ALL_PERMS = [
  "manage_users", "view_billing", "issue_refunds", "manage_servers", "manage_domains",
  "manage_tickets", "view_audit", "edit_branding", "edit_pricing", "send_notifications",
];

const DEFAULTS: UsersState = {
  users: [
    { id: "u1", name: "Omar Khalifa", email: "omar@doiteasy.net", role: "admin", active: true, lastLogin: "2h ago" },
    { id: "u2", name: "Sara Mansour", email: "sara@doiteasy.net", role: "support", active: true, lastLogin: "15m ago" },
    { id: "u3", name: "Ahmed Al-Rashed", email: "ahmed@doiteasy.net", role: "billing", active: true, lastLogin: "Yesterday" },
    { id: "u4", name: "Fatima Noor", email: "fatima@doiteasy.net", role: "client", active: false, lastLogin: "3w ago" },
  ],
  permissions: {
    admin: ALL_PERMS,
    support: ["manage_tickets", "manage_users", "manage_servers", "manage_domains"],
    billing: ["view_billing", "issue_refunds", "manage_tickets"],
    client: [],
  },
  defaultRole: "client",
};

const ROLES: Role[] = ["admin", "support", "billing", "client"];
const ROLE_COLOR: Record<Role, "green" | "blue" | "yellow" | "slate"> = {
  admin: "green", support: "blue", billing: "yellow", client: "slate",
};

export default function CmsUsers() {
  const { value: state, setValue: setState, save, loading, saving } = useSiteSettings<UsersState>("users_roles", DEFAULTS);
  const [search, setSearch] = useState("");
  const [toast, setToast] = useState<{ ok: boolean; msg: string } | null>(null);

  const notify = (ok: boolean, msg: string) => {
    setToast({ ok, msg });
    setTimeout(() => setToast(null), 3500);
  };

  const handleSave = async () => {
    const r = await save();
    if (r.ok) notify(true, "Users & permissions saved.");
    else notify(false, r.error || "Save failed.");
  };

  const addUser = () => {
    const id = Date.now().toString();
    setState({ ...state, users: [...state.users, { id, name: "New User", email: "user@example.com", role: state.defaultRole, active: true, lastLogin: "—" }] });
  };
  const removeUser = (id: string) => setState({ ...state, users: state.users.filter((u) => u.id !== id) });
  const editUser = (id: string, patch: Partial<User>) =>
    setState({ ...state, users: state.users.map((u) => (u.id === id ? { ...u, ...patch } : u)) });

  const togglePerm = (role: Role, perm: string) => {
    const has = state.permissions[role].includes(perm);
    setState({
      ...state,
      permissions: {
        ...state.permissions,
        [role]: has ? state.permissions[role].filter((p) => p !== perm) : [...state.permissions[role], perm],
      },
    });
  };

  const filtered = state.users.filter((u) =>
    (u.name + u.email + u.role).toLowerCase().includes(search.toLowerCase())
  );

  return (
    <CmsLayout>
      <PageHeader
        icon={<Users className="w-6 h-6" />}
        title="Users & Roles"
        description="Manage admin accounts, assign roles, and configure permissions."
      />

      {loading && (
        <div className="mb-4 p-3 rounded-lg bg-blue-50 border border-blue-200 text-sm text-blue-800">Loading users…</div>
      )}
      {toast && (
        <div className={`mb-4 p-3 rounded-lg text-sm flex items-center gap-2 ${toast.ok ? "bg-emerald-50 border border-emerald-200 text-emerald-800" : "bg-red-50 border border-red-200 text-red-800"}`}>
          {toast.ok ? <CheckCircle2 className="w-4 h-4" /> : <AlertCircle className="w-4 h-4" />}
          {toast.msg}
        </div>
      )}

      <SectionCard
        title="Users"
        description={`${state.users.length} total accounts`}
        actions={
          <button onClick={addUser} className="px-3 py-1.5 rounded-lg bg-[#0b6e3e] text-white text-xs font-semibold inline-flex items-center gap-1 hover:bg-[#0a8048]">
            <Plus className="w-3.5 h-3.5" /> Add User
          </button>
        }
      >
        <div className="relative mb-3">
          <Search className="w-4 h-4 absolute left-3 top-3 text-slate-400" />
          <TextInput placeholder="Search by name, email or role…" value={search} onChange={(e) => setSearch(e.target.value)} className="!pl-9" />
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-slate-500 border-b border-slate-200">
                <th className="py-2 pr-3">Name</th>
                <th className="py-2 pr-3">Email</th>
                <th className="py-2 pr-3">Role</th>
                <th className="py-2 pr-3">Status</th>
                <th className="py-2 pr-3">Last Login</th>
                <th className="py-2 pr-3 text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map((u) => (
                <tr key={u.id} className="border-b border-slate-100 hover:bg-slate-50">
                  <td className="py-2.5 pr-3">
                    <TextInput value={u.name} onChange={(e) => editUser(u.id, { name: e.target.value })} className="!py-1.5" />
                  </td>
                  <td className="py-2.5 pr-3">
                    <TextInput value={u.email} onChange={(e) => editUser(u.id, { email: e.target.value })} className="!py-1.5" />
                  </td>
                  <td className="py-2.5 pr-3">
                    <Select value={u.role} onChange={(e) => editUser(u.id, { role: e.target.value as Role })} className="!py-1.5">
                      {ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
                    </Select>
                  </td>
                  <td className="py-2.5 pr-3">
                    <Badge tone={u.active ? "green" : "red"}>{u.active ? "Active" : "Disabled"}</Badge>
                  </td>
                  <td className="py-2.5 pr-3 text-slate-500 text-xs">{u.lastLogin}</td>
                  <td className="py-2.5 pr-3 text-right">
                    <button onClick={() => editUser(u.id, { active: !u.active })} className="px-2.5 py-1 rounded border border-slate-300 text-xs hover:bg-white mr-1">
                      {u.active ? "Disable" : "Enable"}
                    </button>
                    <button onClick={() => removeUser(u.id)} className="p-1.5 rounded text-red-600 hover:bg-red-50"><Trash2 className="w-4 h-4" /></button>
                  </td>
                </tr>
              ))}
              {filtered.length === 0 && (
                <tr><td colSpan={6} className="py-8 text-center text-slate-500">No users match your search.</td></tr>
              )}
            </tbody>
          </table>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Role Permissions Matrix" description="Set which permissions are granted to each role.">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[640px]">
            <thead>
              <tr className="text-left text-xs uppercase tracking-wider text-slate-500 border-b border-slate-200">
                <th className="py-2 pr-3">Permission</th>
                {ROLES.map((r) => (
                  <th key={r} className="py-2 pr-3 text-center">
                    <Badge tone={ROLE_COLOR[r]}>{r}</Badge>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {ALL_PERMS.map((perm) => (
                <tr key={perm} className="border-b border-slate-100">
                  <td className="py-2.5 pr-3 font-semibold text-slate-800 font-mono text-xs">{perm}</td>
                  {ROLES.map((r) => {
                    const has = state.permissions[r].includes(perm);
                    return (
                      <td key={r} className="py-2.5 pr-3 text-center">
                        <button
                          onClick={() => togglePerm(r, perm)}
                          className={`w-6 h-6 rounded-md border ${has ? "bg-[#0b6e3e] border-[#0b6e3e] text-white" : "bg-white border-slate-300"}`}
                          aria-label={`${has ? "Revoke" : "Grant"} ${perm} for ${r}`}
                        >
                          {has && "✓"}
                        </button>
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>

      <div className="h-6" />
      <SectionCard title="Registration Defaults">
        <Field label="Default role for new signups">
          <Select value={state.defaultRole} onChange={(e) => setState({ ...state, defaultRole: e.target.value as Role })}>
            <option value="client">client</option>
            <option value="support">support</option>
            <option value="billing">billing</option>
          </Select>
        </Field>
        <Toggle label="Show this role section in signup flow" checked={true} onChange={() => undefined} description="Controlled globally by Registration policy." />
      </SectionCard>

      <SaveBar onSave={handleSave} onReset={() => setState(DEFAULTS)} saving={saving} />
    </CmsLayout>
  );
}