"use client";

import { type ReactNode, useState, useEffect } from "react";
import type { RoleViewModel, PermissionViewModel } from "@/types/view-models";
import { Table, TableRow, TableCell, Button, Badge } from "./ui";
import { t } from "@/lib/i18n";

interface RolePermissionMatrixProps {
  role: RoleViewModel;
  permissions: PermissionViewModel[];
  onSave: (permissionCodes: string[]) => Promise<void>;
}

export function RolePermissionMatrix({
  role,
  permissions,
  onSave,
}: RolePermissionMatrixProps): ReactNode {
  const [selected, setSelected] = useState<Set<string>>(
    new Set(role.permissions.map((p) => p.code)),
  );
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    setSelected(new Set(role.permissions.map((p) => p.code)));
  }, [role]);

  const toggle = (code: string) => {
    setSelected((prev) => {
      const next = new Set(prev);
      if (next.has(code)) {
        next.delete(code);
      } else {
        next.add(code);
      }
      return next;
    });
  };

  const toggleResource = (resource: string) => {
    const resourcePerms = permissions.filter((p) => p.resource === resource);
    const allSelected = resourcePerms.every((p) => selected.has(p.code));
    setSelected((prev) => {
      const next = new Set(prev);
      if (allSelected) {
        resourcePerms.forEach((p) => next.delete(p.code));
      } else {
        resourcePerms.forEach((p) => next.add(p.code));
      }
      return next;
    });
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await onSave(Array.from(selected));
    } finally {
      setSaving(false);
    }
  };

  // 按资源分组
  const resourceGroups = permissions.reduce<
    Record<string, PermissionViewModel[]>
  >((acc, p) => {
    const arr = acc[p.resource] ?? (acc[p.resource] = []);
    arr.push(p);
    return acc;
  }, {});

  return (
    <div>
      <div className="flex items-center justify-between mb-4">
        <div>
          <h3
            style={{
              fontFamily: "var(--font-serif)",
              fontSize: 16,
              color: "var(--color-ink)",
            }}
          >
            {role.name}
            {role.isSystem && <Badge status="active" />}
          </h3>
          <p style={{ fontSize: 12, color: "var(--color-ink-muted)" }}>
            {role.code} · {t("admin.roles.userCount")}: {role.userCount} ·{" "}
            {role.dataScope}
          </p>
        </div>
        <Button variant="primary" onClick={handleSave} disabled={saving}>
          {saving ? t("admin.common.loading") : t("admin.common.save")}
        </Button>
      </div>

      <Table headers={["资源", "权限点", "操作", "说明", "授权"]}>
        {Object.entries(resourceGroups).map(([resource, perms]) =>
          perms.map((perm, idx) => (
            <TableRow key={perm.id}>
              {idx === 0 && (
                <TableCell
                  rowSpan={perms.length}
                  style={{ verticalAlign: "top", fontWeight: 500 }}
                >
                  <label
                    style={{ display: "flex", alignItems: "center", gap: 6 }}
                  >
                    <input
                      type="checkbox"
                      checked={perms.every((p) => selected.has(p.code))}
                      ref={(el) => {
                        if (el)
                          el.indeterminate =
                            perms.some((p) => selected.has(p.code)) &&
                            !perms.every((p) => selected.has(p.code));
                      }}
                      onChange={() => toggleResource(resource)}
                    />
                    {resource}
                  </label>
                </TableCell>
              )}
              <TableCell
                style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}
              >
                {perm.code}
              </TableCell>
              <TableCell>{perm.action}</TableCell>
              <TableCell
                style={{ color: "var(--color-ink-muted)", fontSize: 12 }}
              >
                {perm.description}
              </TableCell>
              <TableCell>
                <input
                  type="checkbox"
                  checked={selected.has(perm.code)}
                  onChange={() => toggle(perm.code)}
                />
              </TableCell>
            </TableRow>
          )),
        )}
      </Table>
    </div>
  );
}
