"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { createUser, deleteUser, getUsers, updateUser, type UserRecord, type UserRole } from "@/lib/api";
import { useAuth } from "@/lib/auth";

const roleLabels: Record<UserRole, string> = {
  store_keeper: "Store Keeper",
  store_manager: "Store Manager",
  super_admin: "Super Admin",
};

const emptyForm = {
  name: "",
  email: "",
  role: "store_keeper" as UserRole,
  password: "",
  active: true,
};

export default function AccessControlPage() {
  const router = useRouter();
  const { user } = useAuth();
  const [users, setUsers] = useState<UserRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [modalOpen, setModalOpen] = useState(false);
  const [editing, setEditing] = useState<UserRecord | null>(null);
  const [form, setForm] = useState(emptyForm);
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);

  const canManageUsers = user?.role === "store_manager" || user?.role === "super_admin";

  useEffect(() => {
    if (user && !canManageUsers) {
      router.replace("/");
      return;
    }
    if (canManageUsers) {
      refresh();
    }
  }, [user, canManageUsers]); // eslint-disable-line react-hooks/exhaustive-deps

  async function refresh() {
    setLoading(true);
    setError(null);
    try {
      setUsers(await getUsers());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load users.");
    } finally {
      setLoading(false);
    }
  }

  const counts = useMemo(() => {
    const active = users.filter((u) => u.active).length;
    const managers = users.filter((u) => u.active && (u.role === "store_manager" || u.role === "super_admin")).length;
    return { active, inactive: users.length - active, managers };
  }, [users]);

  function openCreate() {
    setEditing(null);
    setForm(emptyForm);
    setFormError(null);
    setModalOpen(true);
  }

  function openEdit(record: UserRecord) {
    setEditing(record);
    setForm({
      name: record.name,
      email: record.email,
      role: record.role,
      password: "",
      active: record.active,
    });
    setFormError(null);
    setModalOpen(true);
  }

  function closeModal() {
    setModalOpen(false);
    setFormError(null);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setFormError(null);

    if (!form.name.trim()) {
      setFormError("Name is required.");
      return;
    }
    if (!form.email.trim()) {
      setFormError("Email is required.");
      return;
    }
    if (!editing && !form.password.trim()) {
      setFormError("Password is required for new users.");
      return;
    }

    setSaving(true);
    try {
      if (editing) {
        await updateUser(editing.id, {
          name: form.name.trim(),
          email: form.email.trim(),
          role: form.role,
          active: form.active,
          ...(form.password.trim() ? { password: form.password } : {}),
        });
        setSuccess("User updated successfully.");
      } else {
        await createUser({
          name: form.name.trim(),
          email: form.email.trim(),
          role: form.role,
          password: form.password,
          active: form.active,
        });
        setSuccess("User created successfully.");
      }
      closeModal();
      await refresh();
    } catch (err) {
      setFormError(err instanceof Error ? err.message : "Failed to save user.");
    } finally {
      setSaving(false);
    }
  }

  async function handleDeactivate(record: UserRecord) {
    if (record.id === user?.id) {
      setError("You cannot deactivate your own account.");
      return;
    }
    if (!window.confirm(`Deactivate ${record.name}?`)) return;

    try {
      await deleteUser(record.id);
      setSuccess("User deactivated.");
      await refresh();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to deactivate user.");
    }
  }

  if (!canManageUsers) return null;

  return (
    <>
      <section className="hero">
        <div className="hero-grid">
          <div>
            <h2>Access Control</h2>
            <p>Manage users, roles, and active access for the stock movement workspace.</p>
          </div>
          <div style={{ alignSelf: "center" }}>
            <button className="button" onClick={openCreate}>New User</button>
          </div>
        </div>
      </section>

      <section className="section">
        {success && (
          <div className="snackbar" style={{ background: "var(--brand-soft)", color: "var(--brand)", border: "1px solid rgba(59,91,219,0.2)", marginBottom: 18 }}>
            {success}
            <button className="snackbar-close" onClick={() => setSuccess(null)}>✕</button>
          </div>
        )}
        {error && (
          <div className="snackbar snackbar-error" style={{ marginBottom: 18 }}>
            {error}
            <button className="snackbar-close" onClick={() => setError(null)}>✕</button>
          </div>
        )}

        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 14, marginBottom: 18 }}>
          <Summary label="Active Users" value={counts.active} />
          <Summary label="Managers" value={counts.managers} />
          <Summary label="Inactive" value={counts.inactive} />
        </div>

        {loading && <p style={{ color: "var(--muted)" }}>Loading users…</p>}

        {!loading && (
          <div className="card">
            <div className="stock-table-scroll">
              <table className="table stock-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Role</th>
                    <th>Status</th>
                    <th>Created</th>
                    <th style={{ textAlign: "right" }}>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {users.length === 0 && (
                    <tr>
                      <td colSpan={6} style={{ padding: 24, textAlign: "center", color: "var(--muted)" }}>
                        No users found.
                      </td>
                    </tr>
                  )}
                  {users.map((record) => (
                    <tr key={record.id}>
                      <td><strong>{record.name}</strong></td>
                      <td style={{ color: "var(--muted)" }}>{record.email}</td>
                      <td>{roleLabels[record.role]}</td>
                      <td>
                        {record.active ? (
                          <span className="badge ok">Active</span>
                        ) : (
                          <span className="badge warn">Inactive</span>
                        )}
                      </td>
                      <td style={{ color: "var(--muted)" }}>
                        {new Date(record.createdAt).toLocaleDateString("en-AE")}
                      </td>
                      <td>
                        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8 }}>
                          <button className="button secondary" onClick={() => openEdit(record)}>Edit</button>
                          {record.active && (
                            <button
                              className="button secondary"
                              onClick={() => handleDeactivate(record)}
                              disabled={record.id === user?.id}
                              title={record.id === user?.id ? "You cannot deactivate your own account" : "Deactivate user"}
                            >
                              Deactivate
                            </button>
                          )}
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}
      </section>

      {modalOpen && (
        <div className="doc-modal-backdrop" onClick={(e) => { if (e.target === e.currentTarget) closeModal(); }}>
          <div className="doc-modal" style={{ maxWidth: 560 }}>
            <div className="doc-modal-header">
              <div>
                <strong className="doc-modal-title">{editing ? "Edit User" : "New User"}</strong>
                <span className="doc-modal-meta">
                  {editing ? "Update role, status, or credentials" : "Create a login for this workspace"}
                </span>
              </div>
              <button className="doc-modal-close" onClick={closeModal}>✕</button>
            </div>

            <div className="doc-modal-body" style={{ padding: 22 }}>
              {formError && (
                <div className="snackbar snackbar-error" style={{ marginBottom: 18 }}>
                  {formError}
                </div>
              )}

              <form onSubmit={handleSubmit}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                  <div className="form-field">
                    <label className="form-label">Name <span className="form-required">*</span></label>
                    <input className="form-input" value={form.name} onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))} />
                  </div>
                  <div className="form-field">
                    <label className="form-label">Email <span className="form-required">*</span></label>
                    <input className="form-input" type="email" value={form.email} onChange={(e) => setForm((f) => ({ ...f, email: e.target.value }))} />
                  </div>
                  <div className="form-field">
                    <label className="form-label">Role <span className="form-required">*</span></label>
                    <select className="form-input" value={form.role} onChange={(e) => setForm((f) => ({ ...f, role: e.target.value as UserRole }))}>
                      <option value="store_keeper">Store Keeper</option>
                      <option value="store_manager">Store Manager</option>
                      <option value="super_admin">Super Admin</option>
                    </select>
                  </div>
                  <div className="form-field">
                    <label className="form-label">
                      Password
                      {editing ? <span className="form-optional">optional</span> : <span className="form-required">*</span>}
                    </label>
                    <input
                      className="form-input"
                      type="password"
                      value={form.password}
                      onChange={(e) => setForm((f) => ({ ...f, password: e.target.value }))}
                      placeholder={editing ? "Leave blank to keep current" : "Minimum 6 characters"}
                    />
                  </div>
                </div>

                <div className="form-field" style={{ marginTop: 14 }}>
                  <label className="toggle-row">
                    <div
                      className={`toggle-track ${form.active ? "toggle-on" : ""}`}
                      onClick={() => setForm((f) => ({ ...f, active: !f.active }))}
                      role="switch"
                      aria-checked={form.active}
                      tabIndex={0}
                      onKeyDown={(e) => {
                        if (e.key === " ") setForm((f) => ({ ...f, active: !f.active }));
                      }}
                    >
                      <div className="toggle-thumb" />
                    </div>
                    <span className="toggle-label">{form.active ? "Active" : "Inactive"}</span>
                  </label>
                </div>

                <div style={{ display: "flex", justifyContent: "flex-end", gap: 10, marginTop: 20 }}>
                  <button type="button" className="button secondary" onClick={closeModal}>Cancel</button>
                  <button type="submit" className="button" disabled={saving}>
                    {saving ? "Saving…" : editing ? "Save Changes" : "Create User"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function Summary({ label, value }: { label: string; value: number }) {
  return (
    <div className="card" style={{ padding: "16px 18px" }}>
      <p style={{ margin: "0 0 6px", color: "var(--muted)", fontSize: "0.78rem", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 700 }}>
        {label}
      </p>
      <strong style={{ fontSize: "1.5rem", color: "var(--ink)" }}>{value}</strong>
    </div>
  );
}
