import React, { ReactNode, useState } from "react";
import Swal from 'sweetalert2';
import UserDrawer from "../offcanvas/users/UserDrawer";
import { Role, User, Permissions, MODULES, ACTIONS } from "../utils/user";
import ConfirmationModal from "../components/ConfirmationModal";
import IconUser from "../components/Icon/IconUser";
import IconTrashLines from "../components/Icon/IconTrashLines";
import IconShield from "../components/Icon/IconShield";
import IconSearch from "../components/Icon/IconSearch";
import IconPlus from "../components/Icon/IconPlus";
import IconTrash from "../components/Icon/IconTrash";
import IconPencilPaper from "../components/Icon/IconPencilPaper";
import IconLock from "../components/Icon/IconLock";
import Tabs from "../components/Tabs";
import IconChecks from "../components/Icon/IconChecks";
import DynamicTable from "../components/DynamicTable";
import Button from "../components/Buttons";
import Toolbar from "../components/Toolbar";
import { userRoleApi } from "../api/userRoleApi";
import { useEffect } from "react";
import Modal from "../components/Modal";
const COLORS = {
  cream: "#FBF6ED",
  card: "#FFFFFF",
  line: "#ECE2D2",
  ink: "#3B2F28",
  sub: "#9C8C7C",
  burgundy: "#7A2E1D",
  gold: "#C9974A",
  goldSoft: "#F6E9D2",
};

type Module = typeof MODULES[number];

type Action = typeof ACTIONS[number];

type TabItem = {
  label: string;
  icon?: ReactNode;
  content: ReactNode;
  disabled?: boolean;
};

const makeFullPerms = (): Permissions =>
  MODULES.reduce((acc, m) => {
    acc[m] = { View: true, Add: true, Edit: true, Delete: true };
    return acc;
  }, {} as Permissions);

const makePerms = (
  fullModules: readonly Module[],
  addEditModules: readonly Module[] = []
): Permissions =>
  MODULES.reduce((acc, m) => {
    const view = fullModules.includes(m);
    const addEdit = addEditModules.includes(m);
    acc[m] = { View: view, Add: addEdit, Edit: addEdit, Delete: false };
    return acc;
  }, {} as Permissions);

const INITIAL_ROLES: Role[] = [
  {
    id: "r1",
    name: "Administrator",
    description: "Full access across every module",
    permissions: makeFullPerms(),
  },
  {
    id: "r2",
    name: "Store Manager",
    description: "Runs day-to-day store operations",
    permissions: makePerms(
      MODULES,
      ["Dashboard", "Inventory", "Orders & Billing", "Shipments", "Customers"]
    ),
  },
  {
    id: "r3",
    name: "Sales Associate",
    description: "Front-desk billing and customer care",
    permissions: makePerms(
      ["Dashboard", "Inventory", "Orders & Billing", "Customers"],
      ["Orders & Billing"]
    ),
  },
];

const INITIAL_USERS: User[] = [
  { id: "u1", name: "Meera Pillai", mobile: "+91 98765 43210", email: "meera.pillai@shasjewelry.com", role: "Administrator", active: true },
  { id: "u2", name: "Arjun Nair", mobile: "+91 90123 45678", email: "arjun.nair@shasjewelry.com", role: "Store Manager", active: true },
  { id: "u3", name: "Divya Suresh", mobile: "+91 88990 11223", email: "divya.suresh@shasjewelry.com", role: "Sales Associate", active: false },
];

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


/* ── Toggle ─────────────────────────────────────────────── */
interface ToggleProps { checked: boolean; onChange: () => void; disabled?: boolean; }
const Toggle: React.FC<ToggleProps> = ({ checked, onChange, disabled = false }) => (
  <button type="button" onClick={disabled ? undefined : onChange} aria-pressed={checked}
    disabled={disabled}
    style={{
      width: 38, height: 22, borderRadius: 999, border: "none", cursor: disabled ? "not-allowed" : "pointer",
      background: checked ? COLORS.burgundy : "#E3D9CB", position: "relative",
      transition: "background .2s ease", flexShrink: 0,
      opacity: disabled ? 0.6 : 1
    }}>
    <span style={{
      position: "absolute", top: 2, left: checked ? 18 : 2, width: 18, height: 18,
      borderRadius: "50%", background: "#fff", transition: "left .2s ease",
      boxShadow: "0 1px 2px rgba(0,0,0,.25)"
    }} />
  </button>
);

/* ── Role pill ───────────────────────────────────────────── */
const ROLE_PALETTE: Record<string, { bg: string; fg: string }> = {
  Administrator: { bg: "#F6E9D2", fg: COLORS.burgundy },
  "Store Manager": { bg: "#EAF1EC", fg: "#3E6B53" },
  "Sales Associate": { bg: "#EFEAF6", fg: "#5B4A8A" },
};

const RolePill: React.FC<{ name: string }> = ({ name }) => {
  const c = ROLE_PALETTE[name] ?? { bg: "#F1ECE4", fg: COLORS.ink };
  return (
    <span style={{
      background: c.bg, color: c.fg, fontSize: 12, fontWeight: 600,
      padding: "4px 12px", borderRadius: 999, letterSpacing: 0.2
    }}>
      {name}
    </span>
  );
};


const goldBtn: React.CSSProperties = {
  background: `linear-gradient(90deg, ${COLORS.gold} 0%, #b9803a 100%)`,
  color: "#fff", border: "none", borderRadius: 10, padding: "10px 22px",
  fontSize: 14, fontWeight: 600, cursor: "pointer",
};
const iconBtn: React.CSSProperties = {
  width: 32, height: 32, borderRadius: 8, border: `1px solid ${COLORS.line}`,
  background: "#fff", color: COLORS.ink, display: "flex", alignItems: "center",
  justifyContent: "center", cursor: "pointer",
};

/* ── Permission matrix ───────────────────────────────────── */
interface PermissionMatrixProps { role: Role; onChange: (r: Role) => void; }

const PermissionMatrix: React.FC<PermissionMatrixProps> = ({ role, onChange }) => {
  const togglePerm = (mod: Module, action: Action) => {
    const current = role.permissions[mod][action];
    const updated: Record<Action, boolean> = { ...role.permissions[mod], [action]: !current };
    if (action === "View" && current) {
      updated.Add = updated.Edit = updated.Delete = false;
    }
    onChange({ ...role, permissions: { ...role.permissions, [mod]: updated } });
  };

  return (
    <div style={{ border: `1px solid ${COLORS.line}`, borderRadius: 14, overflow: "hidden" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1fr 1fr", background: COLORS.goldSoft }}>
        <div style={{ padding: "14px 20px", fontSize: 12, fontWeight: 700, color: COLORS.burgundy, letterSpacing: 0.6, textTransform: "uppercase" }}>Module</div>
        {ACTIONS.map((a) => (
          <div key={a} style={{
            padding: "14px 8px", fontSize: 12, fontWeight: 700, color: COLORS.burgundy,
            textAlign: "center", letterSpacing: 0.6, textTransform: "uppercase"
          }}>{a}</div>
        ))}
      </div>

      {MODULES.map((mod, i) => (
        <div key={mod} style={{
          display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 1fr 1fr",
          background: i % 2 ? COLORS.cream : "#fff", borderTop: `1px solid ${COLORS.line}`
        }}>
          <div style={{ padding: "13px 20px", fontSize: 14, color: COLORS.ink, fontWeight: 500 }}>{mod}</div>
          {ACTIONS.map((action) => {
            const checked = role.permissions[mod][action];
            const disabled = action !== "View" && !role.permissions[mod].View;
            return (
              <div key={action} style={{ display: "flex", alignItems: "center", justifyContent: "center" }}>
                <button
                  disabled={disabled}
                  onClick={() => togglePerm(mod, action)}
                  style={{
                    width: 22, height: 22, borderRadius: 6,
                    border: `1.5px solid ${checked ? COLORS.burgundy : COLORS.line}`,
                    background: checked ? COLORS.burgundy : disabled ? "#F4F0E9" : "#fff",
                    color: "#fff", display: "flex", alignItems: "center", justifyContent: "center",
                    cursor: disabled ? "not-allowed" : "pointer",
                    opacity: disabled ? 0.4 : 1, transition: "all .15s ease"
                  }}>
                  {checked && <IconChecks />}
                </button>
              </div>
            );
          })}
        </div>
      ))}
    </div>
  );
};



/* ── Main ────────────────────────────────────────────────── */
export default function Users() {
  const [users, setUsers] = useState<User[]>([]);
  const [roles, setRoles] = useState<Role[]>([]);
  const [search, setSearch] = useState("");
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [editingUser, setEditingUser] = useState<User | null>(null);
  const [activeRoleId, setActiveRoleId] = useState<string>("");
  const [deleteItem, setDeleteItem] = useState<User | null>(null);

  const [roleModalOpen, setRoleModalOpen] = useState(false);
  const [newRoleName, setNewRoleName] = useState("");
  const [newRoleDesc, setNewRoleDesc] = useState("");

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

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

  const fetchUsers = async (q?: string) => {
    try {
      const data = await userRoleApi.getUsers(q);
      setUsers(data);
    } catch (err) {
      console.error(err);
    }
  };

  const fetchRoles = async () => {
    try {
      const data = await userRoleApi.getRoles();
      setRoles(data);
      if (data.length > 0 && !activeRoleId) {
        setActiveRoleId(data[0].id);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const columns = [
    {
      accessor: "name",
      title: "Name",
      render: (u: User) => (
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div
            style={{
              width: 36,
              height: 36,
              borderRadius: "50%",
              background: COLORS.goldSoft,
              color: COLORS.burgundy,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontWeight: 700,
            }}
          >
            {initials(u.name)}
          </div>
          <span style={{ fontWeight: 600 }}>{u.name}</span>
        </div>
      ),
    },
    {
      accessor: "mobile",
      title: "Mobile number",
    },
    {
      accessor: "email",
      title: "Email",
      render: (u: User) => <span style={{ color: COLORS.sub }}>{u.email}</span>,
    },
    {
      accessor: "role",
      title: "Role",
      render: (u: User) => <RolePill name={u.role} />,
    },
    {
      accessor: "active",
      title: "Status",
      render: (u: User) => (
        <Toggle
          checked={u.active}
          disabled={u.email === 'admin@shas.com'}
          onChange={async () => {
             try {
                const updated = await userRoleApi.updateUserStatus(Number(u.id), !u.active);
                setUsers((prev) => prev.map((p) => String(p.id) === String(u.id) ? { ...p, active: updated.active } : p));
                Swal.fire({
                    icon: 'success',
                    title: `Status updated to ${updated.active ? 'Active' : 'Inactive'}`,
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    padding: '10px 20px',
                });
             } catch (err) {
                console.error("Failed to update status", err);
                Swal.fire({
                    icon: 'error',
                    title: 'Failed to update status',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000,
                    padding: '10px 20px',
                });
             }
          }}
        />
      ),
    },
    {
      accessor: "actions",
      title: "Actions",
      render: (u: User) => {
        if (u.email === 'admin@shas.com') {
          return (
            <div style={{ display: "flex", gap: 6, alignItems: "center", justifyContent: "flex-end", color: COLORS.sub, fontSize: 12, paddingRight: 8, userSelect: "none" }}>
              <IconLock className="w-4 h-4 text-[#9C8C7C] opacity-75" />
              <span>System</span>
            </div>
          );
        }
        return (
          <div style={{ display: "flex", gap: 8, justifyContent: "flex-end" }}>
            <button
              onClick={() => {
                setEditingUser(u);
                setDrawerOpen(true);
              }}
              style={iconBtn}
            >
              <IconPencilPaper />
            </button>

            <button
              onClick={() => setDeleteItem(u)}
              style={iconBtn}
            >
              <IconTrash />
            </button>
          </div>
        );
      },
    },
  ];

  const activeRole = roles.find((r) => r.id === activeRoleId) ?? null;

  const filteredUsers = users;

  const saveUser = async (u: User) => {
    try {
      if (editingUser) {
        await userRoleApi.updateUser(Number(u.id), u);
        Swal.fire({
            icon: 'success',
            title: 'User updated successfully',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            padding: '10px 20px',
        });
      } else {
        await userRoleApi.createUser(u);
        Swal.fire({
            icon: 'success',
            title: 'User created successfully',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000,
            padding: '10px 20px',
        });
      }
      fetchUsers(search);
      setDrawerOpen(false);
      setEditingUser(null);
    } catch (err) {
      console.error("Error saving user", err);
      Swal.fire({
          icon: 'error',
          title: 'Failed to save user',
          toast: true,
          position: 'top-end',
          showConfirmButton: false,
          timer: 3000,
          padding: '10px 20px',
      });
    }
  };

  const updateRole = (updated: Role) =>
    setRoles((prev) => prev.map((r) => (r.id === updated.id ? updated : r)));

  const TABS: TabItem[] = [
    {
      label: "Users",
      icon: <IconUser />,
      content: (
        <div className="space-y-5">
          <Toolbar
            search={{
              value: search,
              onChange: (value) => setSearch(value),
              placeholder: "Search user...",
            }}
            action={
              <Button type="button" onClick={() => { setEditingUser(null); setDrawerOpen(true); }} leftIcon={<IconPlus />} children="Add user" />
            }
          />
          <DynamicTable
            data={filteredUsers}
            columns={columns}
            pageSizes={[5, 10, 20]}
            height={500}
          />
        </div>
      ),
    },
    {
      label: "Roles & Permissions",
      icon: <IconShield />,
      content: (
        <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 24, alignItems: "start" }}>
          <div style={{
            background: COLORS.card, borderRadius: 16, border: `1px solid ${COLORS.line}`,
            padding: 12, boxShadow: "0 12px 40px -16px rgba(122,46,29,.12)"
          }}>
            <button onClick={() => setRoleModalOpen(true)}
              style={{
                width: "100%", padding: "12px", borderRadius: 10, border: `1px dashed ${COLORS.burgundy}`,
                background: COLORS.cream, color: COLORS.burgundy, fontWeight: 600,
                display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
                cursor: "pointer", marginBottom: 8
              }}>
              <IconPlus /> Create new role
            </button>
            {roles.map((r) => (
              <button key={r.id} onClick={() => setActiveRoleId(r.id)}
                style={{
                  width: "100%", textAlign: "left", padding: "14px 16px", borderRadius: 10,
                  border: "none", marginBottom: 4,
                  background: r.id === activeRoleId ? COLORS.goldSoft : "transparent",
                  cursor: "pointer"
                }}>
                <div className="font-sans" style={{
                  fontWeight: 700, fontSize: 14,
                  color: r.id === activeRoleId ? COLORS.burgundy : COLORS.ink
                }}>{r.name}</div>
                <div style={{ fontSize: 12, color: COLORS.sub, marginTop: 2 }}>{r.description}</div>
              </button>
            ))}
          </div>

          {activeRole && (
            <div style={{
              background: COLORS.card, borderRadius: 16, border: `1px solid ${COLORS.line}`,
              padding: 24, boxShadow: "0 12px 40px -16px rgba(122,46,29,.12)"
            }}>
              <div style={{ marginBottom: 18 }}>
                <div className="font-sans" style={{ fontSize: 22, color: COLORS.burgundy }}>
                  {activeRole.name}
                </div>
                <div style={{ fontSize: 13, color: COLORS.sub, marginTop: 2 }}>{activeRole.description}</div>
              </div>
              <PermissionMatrix role={activeRole} onChange={(r) => {
                  setRoles(prev => prev.map(old => old.id === r.id ? r : old));
              }} />
              <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 18 }}>
                <button style={goldBtn} onClick={async () => {
                    try {
                        const updated = await userRoleApi.updateRole(Number(activeRole.id), activeRole);
                        setRoles(prev => prev.map(old => old.id === updated.id ? updated : old));
                        Swal.fire({
                            icon: 'success',
                            title: 'Permissions saved successfully',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 3000,
                            padding: '10px 20px',
                        });
                    } catch (err) {
                        console.error('Failed to save permissions', err);
                    }
                }}>Save permissions</button>
              </div>
            </div>
          )}
        </div>
      ),
    },
  ];

  const confirmDelete = async () => {
    if (!deleteItem) return;
    try {
       await userRoleApi.deleteUser(Number(deleteItem.id));
       setUsers((prev) => prev.filter((c) => String(c.id) !== String(deleteItem.id)));
       setDeleteItem(null);
       Swal.fire({
           icon: 'success',
           title: 'User deleted successfully',
           toast: true,
           position: 'top-end',
           showConfirmButton: false,
           timer: 3000,
           padding: '10px 20px',
       });
    } catch (err) {
       console.error("Failed to delete user", err);
       Swal.fire({
           icon: 'error',
           title: 'Failed to delete user',
           toast: true,
           position: 'top-end',
           showConfirmButton: false,
           timer: 3000,
           padding: '10px 20px',
       });
    }
  };

  return (
    <>
      <div style={{ display: "flex", gap: 8, marginBottom: 22, borderBottom: `1px solid ${COLORS.line}` }}>
        <Tabs items={TABS} variant="line" />
      </div>

      <UserDrawer
        open={drawerOpen}
        onClose={() => { setDrawerOpen(false); setEditingUser(null); }}
        onSave={saveUser}
        roles={roles}
        initialUser={editingUser}
      />

      <ConfirmationModal
        isOpen={!!deleteItem}
        onClose={() => setDeleteItem(null)}
        onConfirm={confirmDelete}
        type="danger"
        title="Delete Product"
        message={
          deleteItem && (
            <div className="flex items-center justify-center gap-2">

              <span>
                Are you sure you want to delete user{" "}
                <b>"{deleteItem.name}"</b>?
              </span>
            </div>
          )
        }
        confirmText="Delete"
      />

      <Modal
        open={roleModalOpen}
        onClose={() => { setRoleModalOpen(false); setNewRoleName(""); setNewRoleDesc(""); }}
        title="Create New Role"
        footer={
          <div style={{ display: "flex", gap: 8 }}>
            <button onClick={() => setRoleModalOpen(false)} style={{ padding: "8px 16px", color: COLORS.ink }}>Cancel</button>
            <button
              onClick={async () => {
                if (!newRoleName.trim()) return;
                try {
                  const newRole = await userRoleApi.createRole({
                    name: newRoleName,
                    description: newRoleDesc,
                    permissions: makePerms([]),
                  });
                  setRoles(prev => [...prev, newRole]);
                  setActiveRoleId(newRole.id);
                  setRoleModalOpen(false);
                  setNewRoleName("");
                  setNewRoleDesc("");
                } catch (err) {
                  console.error("Failed to create role", err);
                }
              }}
              style={goldBtn}
            >
              Create Role
            </button>
          </div>
        }
      >
        <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
          <div>
            <label style={{ display: "block", marginBottom: 4, fontSize: 14, fontWeight: 500 }}>Role Name</label>
            <input
              type="text"
              value={newRoleName}
              onChange={(e) => setNewRoleName(e.target.value)}
              className="w-full border border-[#ECE2D2] bg-[#FBF6ED] rounded-[10px] px-[14px] py-[10px] text-[14px] text-[#3B2F28] outline-none box-border focus:border-[#CF8F42] focus:ring-1 focus:ring-[#CF8F42] transition"
              placeholder="e.g. Support Agent"
            />
          </div>
          <div>
            <label style={{ display: "block", marginBottom: 4, fontSize: 14, fontWeight: 500 }}>Description</label>
            <textarea
              value={newRoleDesc}
              onChange={(e) => setNewRoleDesc(e.target.value)}
              className="w-full border border-[#ECE2D2] bg-[#FBF6ED] rounded-[10px] px-[14px] py-[10px] text-[14px] text-[#3B2F28] outline-none box-border focus:border-[#CF8F42] focus:ring-1 focus:ring-[#CF8F42] transition"
              placeholder="Describe what this role can do"
              rows={3}
            />
          </div>
        </div>
      </Modal>

    </>
  );
}