"use client";
import CommonError from "@/app/components/CommonError";
import { useAccessForm } from "./_hooks";
import { Project } from "./_api";

// ── Pure UI helpers ───────────────────────────────────────────────────────────

const initials = (name: string) =>
  name
    .split(" ")
    .map((w) => w[0])
    .join("")
    .toUpperCase()
    .slice(0, 2) || "?";

const ROLE_CONFIG: Record<string, { icon: string; badge: string }> = {
  admin: { icon: "fa-shield-halved", badge: "badge-phoenix-danger" },
  member: { icon: "fa-user", badge: "badge-phoenix-primary" },
  developer: { icon: "fa-code", badge: "badge-phoenix-success" },
  guest: { icon: "fa-eye", badge: "badge-phoenix-warning" },
};
const getRoleConfig = (name = "") =>
  ROLE_CONFIG[name.toLowerCase()] ?? {
    icon: "fa-user-tag",
    badge: "badge-phoenix-secondary",
  };

const STEPS = [
  { label: "Users", icon: "fa-users" },
  { label: "Org & Role", icon: "fa-building" },
  { label: "Projects", icon: "fa-folder-tree" },
  { label: "Review", icon: "fa-clipboard-check" },
];

// ── Tree helpers ──────────────────────────────────────────────────────────────

interface TreeNode extends Project {
  children: TreeNode[];
  depth: number;
}

function buildTree(projects: Project[]): TreeNode[] {
  const map = new Map<number, TreeNode>();
  const roots: TreeNode[] = [];

  // Pass 1 — create nodes
  projects.forEach((p) => map.set(p.id, { ...p, children: [], depth: 0 }));

  // Pass 2 — wire parent→child (parent already normalized to number in hook)
  projects.forEach((p) => {
    const node = map.get(p.id)!;
    const parentNode = p.parent != null ? map.get(Number(p.parent)) : null;
    if (parentNode) parentNode.children.push(node);
    else roots.push(node);
  });

  // Pass 3 — DFS depth resolution (order in array doesn't matter)
  function setDepths(nodes: TreeNode[], depth: number) {
    nodes.forEach((n) => {
      n.depth = depth;
      if (n.children.length) setDepths(n.children, depth + 1);
    });
  }
  setDepths(roots, 0);

  return roots;
}

function flattenTree(nodes: TreeNode[]): TreeNode[] {
  const result: TreeNode[] = [];
  nodes.forEach((n) => {
    result.push(n);
    if (n.children.length) result.push(...flattenTree(n.children));
  });
  return result;
}

// ── Shared card button style ──────────────────────────────────────────────────
// FIX: All clickable cards are now <button type="button"> instead of <div onClick>.
// A <div onClick> inside a scrollable container can have its synthetic click
// swallowed or double-fired by React's event delegation when the scroll position
// shifts during the re-render. A real <button> gets a reliable native click event.
const cardBtnStyle: React.CSSProperties = {
  width: "100%",
  background: "none",
  border: "none",
  padding: 0,
  textAlign: "left",
  cursor: "pointer",
};

// ── Main Component ────────────────────────────────────────────────────────────

export default function Form({ onSuccess }: { onSuccess: () => void }) {
  const {
    step,
    submitting,
    message,
    messageType,
    dropdownLoading,
    userSearch,
    setUserSearch,
    orgSearch,
    setOrgSearch,
    projectSearch,
    setProjectSearch,
    selectedUsers,
    organization,
    setOrganization,
    role,
    setRole,
    selectedProjects,
    description,
    setDescription,
    userTypeList,
    filteredUsers,
    filteredOrgs,
    filteredProjects,
    leafProjectIds,
    selectedUsersData,
    selectedOrgData,
    selectedRoleData,
    selectedProjectsData,
    goTo,
    canGoToStep,
    toggleUser,
    clearUsers,
    toggleProject,
    getDescendantIds,
    handleSubmit,
    resetForm,
  } = useAccessForm(onSuccess);

  const flatProjects = flattenTree(buildTree(filteredProjects));

  return (
    <>
      <CommonError message={message} type={messageType} />
      <div className="card shadow-none border border-translucent">


        <div className="card-body p-4">
          {/* ── STEP 1 — Select Users ── */}
          {step === 1 && (
            <div>
              <div className="d-flex align-items-center gap-3 mb-4 pb-3 border-bottom border-translucent">
                <span
                  className="d-flex align-items-center justify-content-center rounded-3 bg-primary bg-opacity-10 text-primary flex-shrink-0"
                  style={{ width: 44, height: 44 }}
                >
                  <span className="fas fa-users fs-28" />
                </span>

                <div>
                  <h5 className="mb-0 fw-bold text-theme">Select Users</h5>
                  <p className="mb-0   text-info">
                    Choose one or more users to grant access
                  </p>
                </div>

                {/* FIX: no conditional mount/unmount */}
                <span
                  className={[
                    "ms-auto badge bg-primary",
                    selectedUsers.length ? "" : "d-none",
                  ].join(" ")}
                >
                  {selectedUsers.length} selected
                </span>
              </div>

              {/* SEARCH */}
              <div className="d-flex gap-2 mb-3">
                <div className="search-box flex-grow-1">
                  <div className="position-relative">
                    <input
                      className="form-control search-input"
                      type="text"
                      autoComplete="off"
                      placeholder="Search by name or email…"
                      value={userSearch}
                      onChange={(e) => setUserSearch(e.target.value)}
                    />
                    {/* <span className="fas fa-search search-box-icon" /> */}
                  </div>
                </div>
              </div>

              {/* LIST */}
              {dropdownLoading ? (
                <div className="text-center py-5">
                  <span className="spinner-border spinner-border-sm text-primary" />
                </div>
              ) : (
                <div
                  className="row g-2"
                  style={{ maxHeight: 320, overflowY: "auto" }}
                >
                  {filteredUsers.length === 0 ? (
                    <div className="col-12 text-center py-5 text-body-tertiary">
                      <span className="fas fa-user-slash fa-2x mb-2 d-block opacity-50" />
                      <span className="fs-9">No users found</span>
                    </div>
                  ) : (
                    filteredUsers.map((u) => {
                      const name =
                        [u.first_name, u.last_name].filter(Boolean).join(" ") ||
                        u.email;

                      const uid = String(u.id);
                      const sel = selectedUsers.includes(uid);

                      return (
                        <div key={u.id} className="col-12 col-sm-6 col-xl-4">
                          <button
                            type="button"
                            style={cardBtnStyle}
                            onClick={() => toggleUser(uid)}
                          >
                            <div
                              className={[
                                "d-flex align-items-center gap-3 p-3 rounded-3 border h-100",
                                sel
                                  ? "border-primary bg-primary bg-opacity-10"
                                  : "border-translucent bg-body-highlight",
                              ].join(" ")}
                            >
                              <div
                                className={[
                                  "rounded-circle d-flex align-items-center justify-content-center fw-bold flex-shrink-0",
                                  sel
                                    ? "bg-primary text-white"
                                    : "bg-body-secondary text-theme",
                                ].join(" ")}
                                style={{ width: 38, height: 38, fontSize: 12 }}
                              >
                                {initials(name)}
                              </div>

                              <div className="overflow-hidden flex-grow-1">
                                <div className="text-info">
                                  <b>{name}</b>
                                </div>
                                <div className="text-theme">
                                  <b>{u.email}</b>
                                </div>
                              </div>

                              <span
                                className={[
                                  "fas flex-shrink-0",
                                  sel
                                    ? "fa-circle-check text-primary"
                                    : "fa-circle text-body-tertiary opacity-25",
                                ].join(" ")}
                              />
                            </div>
                          </button>
                        </div>
                      );
                    })
                  )}
                </div>
              )}

              {/* FOOTER */}
              <div className="d-flex justify-content-between align-items-center mt-4 pt-3 border-top border-translucent">
                <span className="fs-9 text-theme">
                  <span className={selectedUsers.length ? "" : "d-none"}>
                    <span className="fas fa-circle-check text-success me-1" />
                    {selectedUsers.length} user(s) selected
                  </span>

                  <span className={selectedUsers.length ? "d-none" : ""}>
                    Select at least one user
                  </span>
                </span>

                <button
                  className="btn btn-primary btn-sm px-4"
                  disabled={selectedUsers.length === 0}
                  onClick={() => goTo(2)}
                >
                  Continue <span className="fas fa-arrow-right ms-2" />
                </button>
              </div>
            </div>
          )}

          {/* ── STEP 2 — Organisation & Role ── */}
          {step === 2 && (
            <div>
              <div className="d-flex align-items-center gap-3 mb-4 pb-3 border-bottom border-translucent">
                <span
                  className="d-flex align-items-center justify-content-center rounded-3 bg-warning bg-opacity-10 text-warning flex-shrink-0"
                  style={{ width: 44, height: 44 }}
                >
                  <span className="fas fa-building fs-28" />
                </span>
                <div>
                  <h5 className="mb-0 fw-bold text-theme">
                    Organisation &amp; Role
                  </h5>
                  <p className="mb-0 text-info ">
                    Set the access level and organisation
                  </p>
                </div>
              </div>

              <div className="mb-4">
                <label className="form-label fw-semibold fs-9 text-white text-uppercase">
                  Access Role
                </label>
                <div className="row g-2">
                  {dropdownLoading ? (
                    <div className="col-12 text-center py-3">
                      <span className="spinner-border spinner-border-sm text-primary" />
                    </div>
                  ) : (
                    userTypeList.map((r) => {
                      const sel = String(r.id) === String(role);
                      const cfg = getRoleConfig(r.name);
                      return (
                        <div key={r.id} className="col-6 col-md-3">
                          <button
                            type="button"
                            style={cardBtnStyle}
                            onClick={() => setRole(String(r.id))}
                          >
                            <div
                              className={[
                                "text-center py-4 px-3 rounded-3 border h-100",
                                sel
                                  ? "border-primary bg-primary bg-opacity-10"
                                  : "border-translucent bg-body-highlight",
                              ].join(" ")}
                              style={{ transition: "all .15s" }}
                            >
                              <span
                                className={[
                                  `fas ${cfg.icon} fa-xl mb-2 d-block`,
                                  sel ? "text-primary" : "text-body-tertiary",
                                ].join(" ")}
                              />
                              <div
                                className={`fw-semibold fs-9 mt-3 ${sel ? "text-primary" : "text-body"}`}
                              >
                                {r.name}
                              </div>
                              {sel && (
                                <span className={`badge ${cfg.badge} mt-1`}>
                                  Selected
                                </span>
                              )}
                            </div>
                          </button>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>

              <div className="mb-2">
                <label className="form-label fw-semibold fs-9 text-white text-uppercase">
                  Organisation
                </label>
                {/* FIX: type="text" — same removeChild reason as above */}
                <div className="search-box mb-3">
                  <div className="position-relative">
                    <input
                      className="form-control search-input"
                      type="text"
                      autoComplete="off"
                      placeholder="Search organisations…"
                      value={orgSearch}
                      onChange={(e) => setOrgSearch(e.target.value)}
                    />
                    {/* <span className="fas fa-search search-box-icon" /> */}
                  </div>
                </div>
                <div
                  className="row g-2"
                  style={{ maxHeight: 220, overflowY: "auto" }}
                >
                  {dropdownLoading ? (
                    <div className="col-12 text-center py-3">
                      <span className="spinner-border spinner-border-sm text-primary" />
                    </div>
                  ) : filteredOrgs.length === 0 ? (
                    <div className="col-12 text-center py-4 text-body-tertiary fs-9">
                      No organisations found
                    </div>
                  ) : (
                    filteredOrgs.map((o) => {
                      const sel = String(o.id) === String(organization);
                      return (
                        <div key={o.id} className="col-12 col-sm-6 col-md-4">
                          <button
                            type="button"
                            style={cardBtnStyle}
                            onClick={() => setOrganization(String(o.id))}
                          >
                            <div
                              className={[
                                "d-flex align-items-center gap-3 p-3 rounded-3 border",
                                sel
                                  ? "border-primary bg-primary bg-opacity-10"
                                  : "border-translucent bg-body-highlight",
                              ].join(" ")}
                              style={{ transition: "all .15s" }}
                            >
                              <span
                                className={`fas fa-building ${sel ? "text-primary" : "text-body-tertiary"}`}
                              />
                              <span className="fw-semibold fs-9 flex-grow-1 text-theme">
                                {o.name}
                              </span>
                              <span
                                className={[
                                  "fas",
                                  sel
                                    ? "fa-circle-check text-primary"
                                    : "fa-circle opacity-25 text-body-tertiary",
                                ].join(" ")}
                              />
                            </div>
                          </button>
                        </div>
                      );
                    })
                  )}
                </div>
              </div>

              <div className="d-flex justify-content-between align-items-center mt-4 pt-3 border-top border-translucent">
                <button
                  className="btn btn-primary btn-sm"
                  onClick={() => goTo(1)}
                >
                  <span className="fas fa-arrow-left me-2" />
                  Back
                </button>
                <button
                  className="btn btn-primary btn-sm px-4"
                  disabled={!organization || !role}
                  onClick={() => goTo(3)}
                >
                  Continue <span className="fas fa-arrow-right ms-2" />
                </button>
              </div>
            </div>
          )}

          {/* ── STEP 3 — Projects ── */}
          {step === 3 && (
            <div>
              <div className="d-flex align-items-center gap-3 mb-4 pb-3 border-bottom border-translucent">
                <span
                  className="d-flex align-items-center justify-content-center rounded-3 bg-success bg-opacity-10 text-success flex-shrink-0"
                  style={{ width: 44, height: 44 }}
                >
                  <span className="fas fa-folder-tree fs-28" />
                </span>
                <div>
                  <h5 className="mb-0 fw-bold text-theme">Select Projects</h5>
                  <p className="mb-0 text-info">
                    Selecting a parent automatically includes all children
                  </p>
                </div>
                {selectedProjects.length > 0 && (
                  <span className="ms-auto badge bg-success">
                    {selectedProjects.length} selected
                  </span>
                )}
              </div>

              {/* FIX: type="text" */}
              <div className="search-box mb-3">
                <div className="position-relative">
                  <input
                    className="form-control search-input"
                    type="text"
                    autoComplete="off"
                    placeholder="Search projects…"
                    value={projectSearch}
                    onChange={(e) => setProjectSearch(e.target.value)}
                  />
                  {/* <span className="fas fa-search search-box-icon" /> */}
                </div>
              </div>

              <div
                className="rounded-3 border border-translucent"
                style={{ maxHeight: 320, overflowY: "auto" }}
              >
                {dropdownLoading ? (
                  <div className="text-center py-5">
                    <span className="spinner-border spinner-border-sm text-primary" />
                  </div>
                ) : flatProjects.length === 0 ? (
                  <div className="text-center py-5 text-body-tertiary fs-9">
                    No projects found
                  </div>
                ) : (
                  flatProjects.map((p, idx) => {
                    const descendants = getDescendantIds(p.id);
                    // FIX: leaf nodes — [].every() is vacuously true, so an
                    // unselected leaf always appeared checked. Check self directly.
                    const isLeaf = p.children.length === 0;
                    const selfSel = selectedProjects.includes(String(p.id));
                    const allDescSel = isLeaf
                      ? selfSel
                      : descendants.every((id) =>
                          selectedProjects.includes(id),
                        );
                    const someDescSel =
                      !allDescSel &&
                      descendants.some((id) => selectedProjects.includes(id));
                    const hasKids = p.children.length > 0;

                    return (
                      <button
                        key={p.id}
                        type="button"
                        onClick={() => toggleProject(String(p.id))}
                        style={{
                          display: "flex",
                          width: "100%",
                          alignItems: "center",
                          gap: 8,
                          paddingLeft: `${p.depth * 24 + 12}px`,
                          paddingRight: 12,
                          paddingTop: 8,
                          paddingBottom: 8,
                          background: allDescSel
                            ? "rgba(var(--phoenix-success-rgb),.10)"
                            : someDescSel
                              ? "rgba(var(--phoenix-success-rgb),.05)"
                              : "none",
                          border: "none",
                          borderBottom:
                            idx < flatProjects.length - 1
                              ? "1px solid var(--phoenix-border-color-translucent)"
                              : "none",
                          cursor: "pointer",
                          transition: "background .1s",
                          textAlign: "left",
                          color: "rgb(0 232 255)",
                        }}
                      >
                        {p.depth > 0 && (
                          <span
                            className="text-body-quaternary flex-shrink-0 "
                            style={{ fontSize: 11, userSelect: "none" }}
                          >
                            └
                          </span>
                        )}
                        <span
                          className={[
                            "fas flex-shrink-0 fs-9",
                            hasKids
                              ? allDescSel
                                ? "fa-folder-open text-success"
                                : "fa-folder text-info"
                              : allDescSel
                                ? "fa-file-code text-success"
                                : "fa-file-code text-info",
                          ].join(" ")}
                        />
                        <span
                          className="d-inline-flex align-items-center justify-content-center rounded-1 border flex-shrink-0 "
                          style={{
                            width: 16,
                            height: 16,
                            background:
                              allDescSel || someDescSel
                                ? "var(--phoenix-primary)"
                                : "var(--phoenix-body-bg)",
                            borderColor:
                              allDescSel || someDescSel
                                ? "var(--phoenix-primary)"
                                : "var(--phoenix-border-color)",
                          }}
                        >
                          {allDescSel && (
                            <span
                              className="fas fa-check text-white"
                              style={{ fontSize: 8 }}
                            />
                          )}
                          {someDescSel && !allDescSel && (
                            <span
                              className="fas fa-minus text-white"
                              style={{ fontSize: 8 }}
                            />
                          )}
                        </span>
                        <span
                          className={`fw-semibold fs-9 flex-grow-1 ${allDescSel ? "text-success" : ""}`}
                        >
                          {p.name}
                        </span>
                      </button>
                    );
                  })
                )}
              </div>

              <div className="mt-4">
                <label className="form-label fw-semibold fs-9">
                  Description{" "}
                  <span className="text-body-tertiary fw-normal">
                    (optional)
                  </span>
                </label>
                <textarea
                  className="form-control fs-9"
                  rows={2}
                  placeholder="Add context…"
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                />
              </div>

              <div className="d-flex justify-content-between align-items-center mt-4 pt-3 border-top border-translucent">
                <button
                  className="btn btn-primary btn-sm"
                  onClick={() => goTo(2)}
                >
                  <span className="fas fa-arrow-left me-2" />
                  Back
                </button>
                <button
                  className="btn btn-primary btn-sm px-4"
                  disabled={selectedProjects.length === 0}
                  onClick={() => goTo(4)}
                >
                  Review <span className="fas fa-arrow-right ms-2" />
                </button>
              </div>
            </div>
          )}

          {/* ── STEP 4 — Review & Confirm ── */}
          {step === 4 && (
            <div>
              <div className="d-flex align-items-center gap-3 mb-4 pb-3 border-bottom border-translucent">
                <span
                  className="d-flex align-items-center justify-content-center rounded-3 bg-info bg-opacity-10 text-info flex-shrink-0"
                  style={{ width: 44, height: 44 }}
                >
                  <span className="fas fa-clipboard-check fs-28" />
                </span>
                <div>
                  <h5 className="mb-0 fw-bold text-theme ">
                    Review &amp; Confirm
                  </h5>
                  <p className="mb-0 text-info">
                    Check details before granting access
                  </p>
                </div>
              </div>

              <div className="row g-3 mb-4">
                <div className="col-12 col-md-6">
                  <div className="h-100 rounded-3 border border-translucent overflow-hidden">
                    <div className="px-3 py-2 bg-body-secondary border-bottom border-translucent d-flex align-items-center gap-2">
                      <span className="fas fa-users text-primary fs-28" />
                      <span className="fw-semibold fs-9">Users</span>
                      <span className="badge bg-primary ms-auto">
                        {selectedUsers.length}
                      </span>
                    </div>
                    <div className="p-3 d-flex flex-wrap gap-2">
                      {selectedUsersData.map((u) => {
                        const name =
                          [u.first_name, u.last_name]
                            .filter(Boolean)
                            .join(" ") || u.email;
                        return (
                          <div
                            key={u.id}
                            className="d-flex align-items-center gap-2 bg-body-secondary rounded-pill px-2 py-1"
                          >
                            <span
                              className="rounded-circle bg-primary text-white fw-bold d-flex align-items-center justify-content-center"
                              style={{ width: 22, height: 22, fontSize: 9 }}
                            >
                              {initials(name)}
                            </span>
                            <span className="fs-10 fw-semibold">{name}</span>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                </div>

                <div className="col-12 col-md-6">
                  <div className="h-100 rounded-3 border border-translucent overflow-hidden">
                    <div className="px-3 py-2 bg-body-secondary border-bottom border-translucent d-flex align-items-center gap-2">
                      <span className="fas fa-building text-warning fs-28" />
                      <span className="fw-semibold fs-9">
                        Organisation &amp; Role
                      </span>
                    </div>
                    <div className="p-3">
                      <div className="d-flex align-items-center gap-3 mb-3">
                        <span className="fas fa-building text-body-tertiary" />
                        <div>
                          <div className="fs-10 text-body-tertiary">
                            Organisation
                          </div>
                          <div className="fw-semibold fs-9">
                            {selectedOrgData?.name || "—"}
                          </div>
                        </div>
                      </div>
                      <div className="d-flex align-items-center gap-3">
                        <span
                          className={`fas ${getRoleConfig(selectedRoleData?.name).icon} text-body-tertiary`}
                        />
                        <div>
                          <div className="fs-10 text-body-tertiary">Role</div>
                          {selectedRoleData ? (
                            <span
                              className={`badge ${getRoleConfig(selectedRoleData.name).badge}`}
                            >
                              {selectedRoleData.name}
                            </span>
                          ) : (
                            <span className="fs-9 text-body-tertiary">—</span>
                          )}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

                <div className="col-12">
                  <div className="rounded-3 border border-translucent overflow-hidden">
                    <div className="px-3 py-2 bg-body-secondary border-bottom border-translucent d-flex align-items-center gap-2">
                      <span className="fas fa-folder-tree text-success fs-28" />
                      <span className="fw-semibold fs-9">Projects</span>
                      <span className="badge bg-success ms-auto">
                        {selectedProjects.length}
                      </span>
                    </div>
                    <div className="p-3 d-flex flex-wrap gap-2">
                      {selectedProjectsData.map((p) => (
                        <div
                          key={p.id}
                          className="d-flex align-items-center gap-1 bg-body-secondary rounded-pill px-2 py-1"
                        >
                          <span className="fas fa-folder-open text-success fs-10" />
                          <span className="fs-10 fw-semibold">{p.name}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>

              <div className="d-flex align-items-center gap-3 rounded-3 border border-info border-opacity-50 bg-info bg-opacity-10 px-3 py-3 mb-4">
                <span className="fas fa-circle-info text-info fa-lg flex-shrink-0" />
                <div>
                  <div className="fw-semibold fs-9 text-info">
                    {selectedUsers.length * leafProjectIds.length} access{" "}
                    {selectedUsers.length * leafProjectIds.length === 1
                      ? "entry"
                      : "entries"}{" "}
                    will be created
                  </div>
                  <div className="fs-10 text-body-tertiary">
                    {selectedUsers.length} user(s) × {leafProjectIds.length}{" "}
                    project(s)
                  </div>
                </div>
              </div>

              <div className="d-flex justify-content-between align-items-center pt-3 border-top border-translucent">
                <button
                  className="btn btn-primary btn-sm"
                  onClick={() => goTo(3)}
                >
                  <span className="fas fa-arrow-left me-2" />
                  Back
                </button>
                <div className="d-flex gap-2">
                  <button className="btn btn-danger btn-sm" onClick={resetForm}>
                    <span className="fas fa-rotate-left me-1" />
                    Reset
                  </button>
                  <button
                    className="btn btn-primary btn-sm px-4"
                    onClick={handleSubmit}
                    disabled={
                      submitting ||
                      selectedUsers.length === 0 ||
                      !organization ||
                      !role ||
                      selectedProjects.length === 0
                    }
                  >
                    {submitting ? (
                      <>
                        <span className="spinner-border spinner-border-sm me-2" />
                        Granting…
                      </>
                    ) : (
                      <>
                        <span className="fas fa-bolt me-2" />
                        Grant Access (
                        {selectedUsers.length * leafProjectIds.length})
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </>
  );
}
