"use client";

import React, { useState, useCallback, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Plus, Edit, Trash2, Users, Menu, Filter, X, Search, Shield } 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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { companyAPI } from "@/lib/api/company";
import { ScrollToTop } from "@/components/common/ScrollToTop";

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

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

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

  // 회사 필터 (최고 관리자 전용)
  const [companies, setCompanies] = useState<Array<{ company_code: string; company_name: string }>>([]);
  const [selectedCompany, setSelectedCompany] = useState<string>("all");

  // 검색
  const [searchText, setSearchText] = useState("");

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

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

  // 회사 목록 로드 (최고 관리자만)
  const loadCompanies = useCallback(async () => {
    if (!isSuperAdmin) return;

    try {
      const companies = await companyAPI.getList();
      setCompanies(companies);
    } catch (error) {
      console.error("회사 목록 로드 오류:", error);
    }
  }, [isSuperAdmin]);

  // 데이터 로드
  const loadRoleGroups = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      // 최고 관리자: selectedCompany에 따라 필터링 (all이면 전체 조회)
      // 회사 관리자: 자기 회사만 조회
      const companyFilter =
        isSuperAdmin && selectedCompany !== "all"
          ? selectedCompany
          : isSuperAdmin
            ? undefined
            : currentUser?.company_code;

      console.log("권한 그룹 목록 조회:", { isSuperAdmin, selectedCompany, companyFilter });

      const response = await roleAPI.getList({
        companyCode: companyFilter,
      });

      if (response.success && response.data) {
        setRoleGroups(response.data);
        console.log("권한 그룹 조회 성공:", response.data.length, "개");
      } else {
        setError(response.message || "권한 그룹 목록을 불러오는데 실패했습니다.");
      }
    } catch (err) {
      console.error("권한 그룹 목록 로드 오류:", err);
      setError("권한 그룹 목록을 불러오는 중 오류가 발생했습니다.");
    } finally {
      setIsLoading(false);
    }
  }, [isSuperAdmin, selectedCompany, currentUser?.company_code]);

  useEffect(() => {
    if (isAdmin) {
      if (isSuperAdmin) {
        loadCompanies(); // 최고 관리자는 회사 목록 먼저 로드
      }
      loadRoleGroups();
    } else {
      setIsLoading(false);
    }
  }, [isAdmin, isSuperAdmin, loadRoleGroups, loadCompanies]);

  // 권한 그룹 생성 핸들러
  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) => {
      router.push(`/admin/userMng/rolesList/${role.objid}`);
    },
    [router],
  );

  // 검색 필터
  const filteredRoleGroups = useMemo(() => {
    if (!searchText.trim()) return roleGroups;
    const q = searchText.toLowerCase();
    return roleGroups.filter(
      (r) =>
        (r.auth_name || "").toLowerCase().includes(q) ||
        (r.auth_code || "").toLowerCase().includes(q),
    );
  }, [roleGroups, searchText]);

  // 관리자가 아니면 접근 제한
  if (!isAdmin) {
    return (
      <div className="flex min-h-screen flex-col bg-background">
        <div className="w-full space-y-4 p-6">
          <div className="space-y-1 border-b pb-3">
            <h1 className="text-2xl font-bold tracking-tight">권한 그룹 관리</h1>
            <p className="text-xs text-muted-foreground">회사 내 권한 그룹을 생성하고 멤버를 관리합니다 (회사 관리자 이상)</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">접근 권한 없음</h3>
            <p className="text-muted-foreground mb-4 text-center text-sm">
              권한 그룹 관리는 회사 관리자 이상만 접근할 수 있습니다.
            </p>
            <Button variant="outline" onClick={() => window.history.back()}>
              뒤로 가기
            </Button>
          </div>
        </div>

        <ScrollToTop />
      </div>
    );
  }

  return (
    <div className="flex min-h-screen flex-col bg-background">
      <div className="w-full space-y-4 p-6">
        {/* 페이지 헤더 */}
        <div className="flex items-end justify-between border-b pb-3">
          <div className="space-y-0.5">
            <h1 className="text-xl font-bold tracking-tight">권한 그룹 관리</h1>
            <p className="text-xs text-muted-foreground">회사 내 권한 그룹을 생성하고 멤버를 관리합니다 (회사 관리자 이상)</p>
          </div>
          <Button onClick={handleCreateRole} size="sm" className="gap-1.5 h-9">
            <Plus className="h-4 w-4" />
            <span className="text-sm">권한 그룹 생성</span>
          </Button>
        </div>

        {/* 에러 메시지 */}
        {error && (
          <div className="border-destructive/50 bg-destructive/10 rounded-lg border p-3">
            <div className="flex items-center justify-between gap-2">
              <p className="text-destructive text-sm font-semibold">{error}</p>
              <button
                onClick={() => setError(null)}
                className="text-destructive hover:text-destructive/80 transition-colors"
                aria-label="에러 메시지 닫기"
              >
                <X className="h-4 w-4" />
              </button>
            </div>
          </div>
        )}

        {/* 검색 / 필터 영역 */}
        <div className="bg-card flex flex-wrap items-center gap-2 rounded-lg border p-3 shadow-sm">
          <div className="relative flex-1 min-w-[200px] max-w-sm">
            <Search className="text-muted-foreground absolute top-1/2 left-2.5 h-3.5 w-3.5 -translate-y-1/2" />
            <Input
              placeholder="권한명, 코드 검색..."
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              className="h-8 pl-8 text-xs"
            />
          </div>
          {isSuperAdmin && (
            <div className="flex items-center gap-1.5">
              <Filter className="text-muted-foreground h-3.5 w-3.5" />
              <Select value={selectedCompany} onValueChange={(value) => setSelectedCompany(value)}>
                <SelectTrigger className="h-8 w-[180px] text-xs">
                  <SelectValue placeholder="회사 선택" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">전체 회사</SelectItem>
                  {companies.map((company) => (
                    <SelectItem key={company.company_code} value={company.company_code}>
                      {company.company_name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          )}
          <div className="ml-auto text-xs text-muted-foreground">
            전체 <span className="text-foreground font-semibold">{filteredRoleGroups.length}</span>개
          </div>
        </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-7 w-7 animate-spin rounded-full border-4 border-t-transparent"></div>
              <p className="text-muted-foreground text-xs">권한 그룹 목록을 불러오는 중...</p>
            </div>
          </div>
        ) : filteredRoleGroups.length === 0 ? (
          <div className="bg-card flex h-56 flex-col items-center justify-center rounded-lg border shadow-sm">
            <Shield className="text-muted-foreground mb-3 h-10 w-10 opacity-30" />
            <p className="text-muted-foreground text-sm">
              {searchText ? "검색 결과가 없습니다" : "등록된 권한 그룹이 없습니다"}
            </p>
            <p className="text-muted-foreground text-xs mt-1">
              {searchText ? "다른 검색어로 시도해보세요" : "권한 그룹을 생성하여 멤버를 관리해보세요"}
            </p>
          </div>
        ) : (
          <div className="grid gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 2xl:grid-cols-6">
            {filteredRoleGroups.map((role) => (
              <div
                key={role.objid}
                className="group bg-card relative flex flex-col rounded-lg border shadow-sm transition-all hover:shadow-md hover:border-primary/40"
              >
                {/* 카드 본문 (클릭 시 상세 페이지) */}
                <div
                  className="cursor-pointer p-3 flex-1"
                  onClick={() => handleViewDetail(role)}
                >
                  <div className="flex items-start justify-between gap-2 mb-2.5">
                    <div className="flex items-center gap-1.5 min-w-0 flex-1">
                      <Shield className="text-primary h-3.5 w-3.5 flex-shrink-0" />
                      <h3 className="text-sm font-semibold truncate group-hover:text-primary transition-colors">
                        {role.auth_name}
                      </h3>
                    </div>
                    <span
                      className={`rounded-full px-1.5 py-0.5 text-[10px] font-medium flex-shrink-0 ${
                        role.status === "active"
                          ? "bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400"
                          : "bg-muted text-muted-foreground"
                      }`}
                    >
                      {role.status === "active" ? "활성" : "비활성"}
                    </span>
                  </div>
                  <p className="text-muted-foreground font-mono text-[10px] truncate mb-2.5">
                    {role.auth_code}
                  </p>

                  {/* 정보 */}
                  <div className="space-y-1 border-t pt-2.5">
                    {isSuperAdmin && (
                      <div className="flex justify-between items-center text-[11px]">
                        <span className="text-muted-foreground">회사</span>
                        <span className="font-medium truncate ml-2 max-w-[100px]" title={companies.find((c) => c.company_code === role.company_code)?.company_name || role.company_code}>
                          {companies.find((c) => c.company_code === role.company_code)?.company_name || role.company_code}
                        </span>
                      </div>
                    )}
                    <div className="flex justify-between items-center text-[11px]">
                      <span className="text-muted-foreground flex items-center gap-1">
                        <Users className="h-2.5 w-2.5" />
                        멤버
                      </span>
                      <span className="font-semibold">{role.member_count || 0}명</span>
                    </div>
                    <div className="flex justify-between items-center text-[11px]">
                      <span className="text-muted-foreground flex items-center gap-1">
                        <Menu className="h-2.5 w-2.5" />
                        메뉴 권한
                      </span>
                      <span className="font-semibold">{role.menu_count || 0}개</span>
                    </div>
                  </div>
                </div>

                {/* 액션 버튼 */}
                <div className="flex border-t">
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEditRole(role);
                    }}
                    className="flex-1 flex items-center justify-center gap-1 py-1.5 text-[11px] font-medium hover:bg-muted/60 transition-colors text-muted-foreground hover:text-foreground"
                  >
                    <Edit className="h-3 w-3" />
                    수정
                  </button>
                  <div className="w-px bg-border" />
                  <button
                    onClick={(e) => {
                      e.stopPropagation();
                      handleDeleteRole(role);
                    }}
                    className="flex-1 flex items-center justify-center gap-1 py-1.5 text-[11px] font-medium text-muted-foreground hover:bg-destructive/10 hover:text-destructive transition-colors"
                  >
                    <Trash2 className="h-3 w-3" />
                    삭제
                  </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>
  );
}

