"use client";

import { type ReactNode, useState } from "react";
import {
  useRoles,
  useCreateRole,
  useUpdateRolePermissions,
} from "@/hooks/use-roles";
import { usePermissions } from "@/hooks/use-permissions";
import { useToast } from "@/providers/toast-provider";
import {
  PageHeader,
  PaperCard,
  Button,
  LoadingState,
  ErrorState,
  Badge,
} from "@/components/ui";
import { RolePermissionMatrix } from "@/components/role-permission-matrix";
import { t } from "@/lib/i18n";
import type { RoleViewModel } from "@/types/view-models";

export default function RolesPage(): ReactNode {
  const { data: roles, loading, error } = useRoles();
  const { data: permissions } = usePermissions();
  const { show } = useToast();
  const [createRole] = useCreateRole();
  const [updateRolePermissions] = useUpdateRolePermissions();
  const [selectedRoleId, setSelectedRoleId] = useState<string | null>(null);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newRoleName, setNewRoleName] = useState("");
  const [newRoleCode, setNewRoleCode] = useState("");
  const [newRoleDescription, setNewRoleDescription] = useState("");
  const [creating, setCreating] = useState(false);

  const selectedRole: RoleViewModel | null = selectedRoleId
    ? (roles.find((r) => r.id === selectedRoleId) ?? null)
    : (roles[0] ?? null);

  const handleCreateRole = async () => {
    if (!newRoleName || !newRoleCode) {
      show("warning", "请填写角色名称和代码");
      return;
    }
    setCreating(true);
    try {
      await createRole({
        name: newRoleName,
        code: newRoleCode,
        description: newRoleDescription,
        dataScope: "SCHOOL",
      });
      show("success", "角色已创建");
      setShowCreateForm(false);
      setNewRoleName("");
      setNewRoleCode("");
      setNewRoleDescription("");
      window.location.reload();
    } catch (err) {
      show(
        "error",
        "创建失败",
        err instanceof Error ? err.message : String(err),
      );
    } finally {
      setCreating(false);
    }
  };

  const handleSavePermissions = async (permissionCodes: string[]) => {
    if (!selectedRole) return;
    try {
      await updateRolePermissions(selectedRole.id, permissionCodes);
      show("success", "权限已更新");
    } catch (err) {
      show(
        "error",
        "更新失败",
        err instanceof Error ? err.message : String(err),
      );
    }
  };

  return (
    <div style={{ padding: 32, maxWidth: 1200, margin: "0 auto" }}>
      <PageHeader
        title={t("admin.roles.title")}
        description="管理角色、配置权限矩阵"
        actions={
          <Button variant="primary" onClick={() => setShowCreateForm(true)}>
            {t("admin.roles.new")}
          </Button>
        }
      />

      <div className="flex gap-4">
        {/* 左侧：角色列表 */}
        <PaperCard className="p-4" style={{ width: 280, flexShrink: 0 }}>
          <h3
            style={{
              fontFamily: "var(--font-serif)",
              fontSize: 14,
              color: "var(--color-ink-muted)",
              marginBottom: 12,
              textTransform: "uppercase",
              letterSpacing: "0.05em",
            }}
          >
            角色列表
          </h3>
          {loading && <LoadingState />}
          {error && <ErrorState message={error.message} />}
          <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
            {roles.map((role) => (
              <li key={role.id}>
                <button
                  onClick={() => setSelectedRoleId(role.id)}
                  style={{
                    display: "block",
                    width: "100%",
                    textAlign: "left",
                    padding: "8px 12px",
                    background:
                      selectedRole?.id === role.id
                        ? "var(--color-accent-light)"
                        : "transparent",
                    border: "none",
                    borderLeft:
                      selectedRole?.id === role.id
                        ? "2px solid var(--color-accent)"
                        : "2px solid transparent",
                    cursor: "pointer",
                    color: "var(--color-ink)",
                    fontSize: 13,
                  }}
                >
                  <div style={{ fontWeight: 500 }}>{role.name}</div>
                  <div
                    style={{
                      fontSize: 11,
                      color: "var(--color-ink-muted)",
                      display: "flex",
                      gap: 6,
                      alignItems: "center",
                    }}
                  >
                    <span>{role.code}</span>
                    {role.isSystem && <Badge status="active" />}
                  </div>
                </button>
              </li>
            ))}
          </ul>
        </PaperCard>

        {/* 右侧：权限矩阵 */}
        <PaperCard className="p-4" style={{ flex: 1 }}>
          {selectedRole && permissions.length > 0 ? (
            <RolePermissionMatrix
              role={selectedRole}
              permissions={permissions}
              onSave={handleSavePermissions}
            />
          ) : (
            <LoadingState />
          )}
        </PaperCard>
      </div>

      {/* 新建角色对话框 */}
      {showCreateForm && (
        <div
          role="dialog"
          aria-modal="true"
          style={{
            position: "fixed",
            inset: 0,
            background: "rgba(0,0,0,0.4)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 1000,
          }}
        >
          <div
            style={{
              width: 400,
              padding: 24,
              background: "var(--bg-paper)",
              borderRadius: 8,
              border: "1px solid var(--color-rule)",
            }}
          >
            <h2
              style={{
                fontFamily: "var(--font-serif)",
                fontSize: 18,
                color: "var(--color-ink)",
                marginBottom: 16,
              }}
            >
              {t("admin.roles.new")}
            </h2>
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  角色名称
                </span>
                <input
                  type="text"
                  value={newRoleName}
                  onChange={(e) => setNewRoleName(e.target.value)}
                  style={{
                    padding: "6px 10px",
                    border: "1px solid var(--color-rule)",
                    borderRadius: 4,
                    fontSize: 13,
                  }}
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  角色代码
                </span>
                <input
                  type="text"
                  value={newRoleCode}
                  onChange={(e) => setNewRoleCode(e.target.value)}
                  placeholder="如 grade_leader"
                  style={{
                    padding: "6px 10px",
                    border: "1px solid var(--color-rule)",
                    borderRadius: 4,
                    fontSize: 13,
                    fontFamily: "var(--font-mono)",
                  }}
                />
              </label>
              <label
                style={{ display: "flex", flexDirection: "column", gap: 4 }}
              >
                <span style={{ fontSize: 12, color: "var(--color-ink)" }}>
                  描述
                </span>
                <textarea
                  value={newRoleDescription}
                  onChange={(e) => setNewRoleDescription(e.target.value)}
                  rows={3}
                  style={{
                    padding: "6px 10px",
                    border: "1px solid var(--color-rule)",
                    borderRadius: 4,
                    fontSize: 13,
                  }}
                />
              </label>
              <div
                style={{
                  display: "flex",
                  justifyContent: "flex-end",
                  gap: 8,
                  marginTop: 8,
                }}
              >
                <Button
                  variant="secondary"
                  onClick={() => setShowCreateForm(false)}
                >
                  {t("admin.common.cancel")}
                </Button>
                <Button
                  variant="primary"
                  onClick={handleCreateRole}
                  disabled={creating}
                >
                  {creating
                    ? t("admin.common.loading")
                    : t("admin.common.save")}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
