"use client";

import React, { useState, useCallback, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Plus, Edit, Trash2, Users, Menu } from "lucide-react";
import { roleAPI, RoleGroup } from "@/lib/api/role";
import { useAuth } from "@/hooks/useAuth";
import { AlertCircle } from "lucide-react";
import { RoleFormModal } from "@/components/admin/RoleFormModal";
import { RoleDeleteModal } from "@/components/admin/RoleDeleteModal";
import { useRouter } from "next/navigation";
import { useTabStore } from "@/stores/tabStore";
import { ScrollToTop } from "@/components/common/ScrollToTop";
import { usePageMultiLang } from "@/hooks/usePageMultiLang";

const LANG_KEYS = [
  "roles.title",
  "roles.description",
  "access.denied",
  "access.denied.msg",
  "button.back",
  "error.occurred",
  "error.close.aria",
  "roles.list.title",
  "button.create",
  "loading",
  "empty.message",
  "empty.hint",
  "status.active",
  "status.inactive",
  "label.memberCount",
  "label.menuPermissions",
  "count.members",
  "count.menus",
  "button.edit",
  "button.delete",
  "error.load.list",
  "error.load.list.generic",
] as const;

const DEFAULT_TEXTS: Record<string, string> = {
  "roles.title": "권한 그룹 관리",
  "roles.description": "권한 그룹을 생성하고 멤버를 관리합니다 (회사 관리자 이상)",
  "access.denied": "접근 권한 없음",
  "access.denied.msg": "권한 그룹 관리는 회사 관리자 이상만 접근할 수 있습니다.",
  "button.back": "뒤로 가기",
  "error.occurred": "오류가 발생했습니다",
  "error.close.aria": "에러 메시지 닫기",
  "roles.list.title": "권한 그룹 목록",
  "button.create": "권한 그룹 생성",
  "loading": "권한 그룹 목록을 불러오는 중...",
  "empty.message": "등록된 권한 그룹이 없습니다.",
  "empty.hint": "권한 그룹을 생성하여 멤버를 관리해보세요.",
  "status.active": "활성",
  "status.inactive": "비활성",
  "label.memberCount": "멤버 수",
  "label.menuPermissions": "메뉴 권한",
  "count.members": "{count}명",
  "count.menus": "{count}개",
  "button.edit": "수정",
  "button.delete": "삭제",
  "error.load.list": "권한 그룹 목록을 불러오는데 실패했습니다.",
  "error.load.list.generic": "권한 그룹 목록을 불러오는 중 오류가 발생했습니다.",
};

/**
 * 권한 그룹 관리 페이지
 * URL: /admin/roles
 *
 * shadcn/ui 스타일 가이드 적용
 *
 * 기능:
 * - 회사별 권한 그룹 목록 조회
 * - 권한 그룹 생성/수정/삭제
 * - 멤버 관리 (Dual List Box)
 * - 메뉴 권한 설정 (CRUD 권한)
 * - 상세 페이지로 이동 (멤버 관리 + 메뉴 권한 설정)
 */
export default function RolesPage() {
  const { user: currentUser } = useAuth();
  const router = useRouter();
  const openTab = useTabStore((s) => s.openTab);
  const { t } = usePageMultiLang({ keys: LANG_KEYS, defaults: DEFAULT_TEXTS, menuCode: "roles.management" });

  // 회사 관리자 또는 최고 관리자 여부
  const isAdmin =
    (currentUser?.companyCode === "*" && currentUser?.userType === "SUPER_ADMIN") ||
    currentUser?.userType === "COMPANY_ADMIN";

  // 상태 관리
  const [roleGroups, setRoleGroups] = useState<RoleGroup[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 모달 상태
  const [formModal, setFormModal] = useState({
    isOpen: false,
    editingRole: null as RoleGroup | null,
  });

  const [deleteModal, setDeleteModal] = useState({
    isOpen: false,
    role: null as RoleGroup | null,
  });

  // 데이터 로드 (단일 테넌시: 현재 사용자 회사 기준)
  const loadRoleGroups = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const response = await roleAPI.getList({
        companyCode: currentUser?.companyCode,
      });

      if (response.success && response.data) {
        setRoleGroups(response.data);
      } else {
        setError(response.message || t("error.load.list"));
      }
    } catch (err) {
      console.error("권한 그룹 목록 로드 오류:", err);
      setError(t("error.load.list.generic"));
    } finally {
      setIsLoading(false);
    }
  }, [currentUser?.companyCode, t]);

  useEffect(() => {
    if (isAdmin) {
      loadRoleGroups();
    } else {
      setIsLoading(false);
    }
  }, [isAdmin, loadRoleGroups]);

  // 권한 그룹 생성 핸들러
  const handleCreateRole = useCallback(() => {
    setFormModal({ isOpen: true, editingRole: null });
  }, []);

  // 권한 그룹 수정 핸들러
  const handleEditRole = useCallback((role: RoleGroup) => {
    setFormModal({ isOpen: true, editingRole: role });
  }, []);

  // 권한 그룹 삭제 핸들러
  const handleDeleteRole = useCallback((role: RoleGroup) => {
    setDeleteModal({ isOpen: true, role });
  }, []);

  // 폼 모달 닫기
  const handleFormModalClose = useCallback(() => {
    setFormModal({ isOpen: false, editingRole: null });
  }, []);

  // 삭제 모달 닫기
  const handleDeleteModalClose = useCallback(() => {
    setDeleteModal({ isOpen: false, role: null });
  }, []);

  // 모달 성공 후 새로고침
  const handleModalSuccess = useCallback(() => {
    loadRoleGroups();
  }, [loadRoleGroups]);

  // 상세 페이지로 이동
  const handleViewDetail = useCallback(
    (role: RoleGroup) => {
      openTab({
        type: "admin",
        title: role.authName,
        adminUrl: `/admin/userMng/rolesList/${role.objid}`,
      });
    },
    [openTab],
  );

  // 관리자가 아니면 접근 제한
  if (!isAdmin) {
    return (
      <div className="bg-background h-full overflow-y-auto">
        <div className="space-y-6 p-6">
          <div className="space-y-2 border-b pb-4">
            <h1 className="text-3xl font-bold tracking-tight">{t("roles.title")}</h1>
            <p className="text-sm text-muted-foreground">{t("roles.description")}</p>
          </div>

          <div className="bg-card flex h-64 flex-col items-center justify-center rounded-lg border p-6 shadow-sm">
            <AlertCircle className="text-destructive mb-4 h-12 w-12" />
            <h3 className="mb-2 text-lg font-semibold">{t("access.denied")}</h3>
            <p className="text-muted-foreground mb-4 text-center text-sm">
              {t("access.denied.msg")}
            </p>
            <Button variant="outline" onClick={() => window.history.back()}>
              {t("button.back")}
            </Button>
          </div>
        </div>

        <ScrollToTop />
      </div>
    );
  }

  return (
    <div className="bg-background h-full overflow-y-auto">
      <div className="space-y-6 p-6">
        {/* 페이지 헤더 */}
        <div className="space-y-2 border-b pb-4">
          <h1 className="text-3xl font-bold tracking-tight">{t("roles.title")}</h1>
          <p className="text-sm text-muted-foreground">{t("roles.description")}</p>
        </div>

        {/* 에러 메시지 */}
        {error && (
          <div className="border-destructive/50 bg-destructive/10 rounded-lg border p-4">
            <div className="flex items-center justify-between">
              <p className="text-destructive text-sm font-semibold">{t("error.occurred")}</p>
              <button
                onClick={() => setError(null)}
                className="text-destructive hover:text-destructive/80 transition-colors"
                aria-label={t("error.close.aria")}
              >
                ✕
              </button>
            </div>
            <p className="text-destructive/80 mt-1.5 text-sm">{error}</p>
          </div>
        )}

        {/* 액션 버튼 영역 */}
        <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
          <h2 className="text-xl font-semibold">{t("roles.list.title")} ({roleGroups.length})</h2>

          <Button onClick={handleCreateRole} className="gap-2">
            <Plus className="h-4 w-4" />
            {t("button.create")}
          </Button>
        </div>

        {/* 권한 그룹 목록 */}
        {isLoading ? (
          <div className="bg-card rounded-lg border p-12 shadow-sm">
            <div className="flex flex-col items-center justify-center gap-4">
              <div className="border-primary h-8 w-8 animate-spin rounded-full border-4 border-t-transparent"></div>
              <p className="text-muted-foreground text-sm">{t("loading")}</p>
            </div>
          </div>
        ) : roleGroups.length === 0 ? (
          <div className="bg-card flex h-64 flex-col items-center justify-center rounded-lg border shadow-sm">
            <div className="flex flex-col items-center gap-2 text-center">
              <p className="text-muted-foreground text-sm">{t("empty.message")}</p>
              <p className="text-muted-foreground text-xs">{t("empty.hint")}</p>
            </div>
          </div>
        ) : (
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {roleGroups.map((role) => (
              <div key={role.objid} className="bg-card rounded-lg border shadow-sm transition-colors">
                {/* 헤더 (클릭 시 상세 페이지) */}
                <div
                  className="hover:bg-muted/50 cursor-pointer p-4 transition-colors"
                  onClick={() => handleViewDetail(role)}
                >
                  <div className="mb-4 flex items-start justify-between">
                    <div className="flex-1">
                      <h3 className="text-base font-semibold">{role.authName}</h3>
                      <p className="text-muted-foreground mt-1 font-mono text-sm">{role.authCode}</p>
                    </div>
                    <span
                      className={`rounded-full px-2 py-1 text-xs font-medium ${
                        role.status === "active" ? "bg-emerald-100 text-emerald-800" : "bg-muted text-foreground"
                      }`}
                    >
                      {role.status === "active" ? t("status.active") : t("status.inactive")}
                    </span>
                  </div>

                  {/* 정보 */}
                  <div className="space-y-2 border-t pt-4">
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground flex items-center gap-1">
                        <Users className="h-3 w-3" />
                        {t("label.memberCount")}
                      </span>
                      <span className="font-medium">{t("count.members", { count: role.memberCount || 0 })}</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span className="text-muted-foreground flex items-center gap-1">
                        <Menu className="h-3 w-3" />
                        {t("label.menuPermissions")}
                      </span>
                      <span className="font-medium">{t("count.menus", { count: role.menuCount || 0 })}</span>
                    </div>
                  </div>
                </div>

                {/* 액션 버튼 */}
                <div className="flex gap-2 border-t p-3">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEditRole(role);
                    }}
                    className="flex-1 gap-1 text-xs"
                  >
                    <Edit className="h-3 w-3" />
                    {t("button.edit")}
                  </Button>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteRole(role);
                    }}
                    className="text-destructive hover:bg-destructive hover:text-destructive-foreground gap-1 text-xs"
                  >
                    <Trash2 className="h-3 w-3" />
                    {t("button.delete")}
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}

        {/* 모달들 */}
        <RoleFormModal
          isOpen={formModal.isOpen}
          onClose={handleFormModalClose}
          onSuccess={handleModalSuccess}
          editingRole={formModal.editingRole}
        />

        <RoleDeleteModal
          isOpen={deleteModal.isOpen}
          onClose={handleDeleteModalClose}
          onSuccess={handleModalSuccess}
          role={deleteModal.role}
        />
      </div>

      {/* Scroll to Top 버튼 (모바일/태블릿 전용) */}
      <ScrollToTop />
    </div>
  );
}

