"use client";

import { useCompanyManagement } from "@/hooks/useCompanyManagement";
import { CompanyToolbar } from "@/components/admin/CompanyToolbar";
import { CompanyTable } from "@/components/admin/CompanyTable";
import { CompanyFormModal } from "@/components/admin/CompanyFormModal";
import { CompanyDeleteDialog } from "@/components/admin/CompanyDeleteDialog";
import { DiskUsageSummary } from "@/components/admin/DiskUsageSummary";
import { ScrollToTop } from "@/components/common/ScrollToTop";
import { useAuth } from "@/hooks/useAuth";
import { AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { usePageMultiLang } from "@/hooks/usePageMultiLang";

// 다국어 키 목록
const LANG_KEYS = [
  "company.page.title",
  "company.page.description",
  "company.access.denied.title",
  "company.access.denied.description",
  "company.access.denied.back",
  "company.toolbar.total",
  "company.toolbar.create",
  "company.table.companyCode",
  "company.table.companyName",
  "company.table.writer",
  "company.table.diskUsage",
  "company.table.diskNoInfo",
  "company.table.fileCount",
  "company.table.actions",
  "company.table.empty",
  "company.table.cardWriter",
  "company.table.cardDiskUsage",
  "company.table.actionDept",
  "company.table.actionEdit",
  "company.table.actionDelete",
  "company.form.titleCreate",
  "company.form.titleEdit",
  "company.form.companyName",
  "company.form.companyNamePlaceholder",
  "company.form.businessNumber",
  "company.form.businessNumberHint",
  "company.form.representativeName",
  "company.form.representativeNamePlaceholder",
  "company.form.representativePhone",
  "company.form.email",
  "company.form.website",
  "company.form.address",
  "company.form.addressPlaceholder",
  "company.form.companyCodeLabel",
  "company.form.writerLabel",
  "company.form.regdateLabel",
  "company.form.cancel",
  "company.form.save",
  "company.form.update",
  "company.delete.title",
  "company.delete.description",
  "company.delete.companyName",
  "company.delete.companyCode",
  "company.delete.writer",
  "company.delete.regdate",
  "company.delete.cancel",
  "company.delete.confirm",
] as const;

// 한국어 기본 텍스트
const DEFAULT_TEXTS: Record<string, string> = {
  "company.page.title": "회사 관리",
  "company.page.description": "시스템에서 사용하는 회사 정보를 관리합니다",
  "company.access.denied.title": "접근 권한 없음",
  "company.access.denied.description": "회사 관리는 최고 관리자만 접근할 수 있습니다.",
  "company.access.denied.back": "뒤로 가기",
  "company.toolbar.total": "총",
  "company.toolbar.create": "회사 등록",
  "company.table.companyCode": "회사코드",
  "company.table.companyName": "회사명",
  "company.table.writer": "등록자",
  "company.table.diskUsage": "디스크 사용량",
  "company.table.diskNoInfo": "정보 없음",
  "company.table.fileCount": "{count}개 파일",
  "company.table.actions": "작업",
  "company.table.empty": "등록된 회사가 없습니다.",
  "company.table.cardWriter": "작성자",
  "company.table.cardDiskUsage": "디스크 사용량",
  "company.table.actionDept": "부서관리",
  "company.table.actionEdit": "수정",
  "company.table.actionDelete": "삭제",
  "company.form.titleCreate": "새 회사 등록",
  "company.form.titleEdit": "회사 정보 수정",
  "company.form.companyName": "회사명",
  "company.form.companyNamePlaceholder": "회사명을 입력하세요",
  "company.form.businessNumber": "사업자등록번호",
  "company.form.businessNumberHint": "10자리 숫자 (자동 하이픈 추가)",
  "company.form.representativeName": "대표자명",
  "company.form.representativeNamePlaceholder": "대표자명을 입력하세요",
  "company.form.representativePhone": "대표 연락처",
  "company.form.email": "이메일",
  "company.form.website": "웹사이트",
  "company.form.address": "회사 주소",
  "company.form.addressPlaceholder": "서울특별시 강남구...",
  "company.form.companyCodeLabel": "회사 코드:",
  "company.form.writerLabel": "등록자:",
  "company.form.regdateLabel": "등록일:",
  "company.form.cancel": "취소",
  "company.form.save": "등록",
  "company.form.update": "수정",
  "company.delete.title": "회사 삭제 확인",
  "company.delete.description": "선택한 회사를 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.",
  "company.delete.companyName": "회사명",
  "company.delete.companyCode": "회사 코드",
  "company.delete.writer": "등록자",
  "company.delete.regdate": "등록일",
  "company.delete.cancel": "취소",
  "company.delete.confirm": "삭제",
};

/**
 * 회사 관리 페이지
 * 최고 관리자만 접근 가능
 */
export default function CompanyPage() {
  const { user: currentUser } = useAuth();
  const isSuperAdmin = currentUser?.companyCode === "*" && currentUser?.userType === "SUPER_ADMIN";

  const { t } = usePageMultiLang({
    keys: LANG_KEYS,
    defaults: DEFAULT_TEXTS,
    menuCode: "company.management",
  });

  const {
    // 데이터
    companies,
    searchFilter,
    isLoading,
    error,

    // 디스크 사용량 관련
    diskUsageInfo,
    isDiskUsageLoading,
    loadDiskUsage,

    // 모달 상태
    modalState,
    deleteState,

    // 검색 기능
    updateSearchFilter,
    clearSearchFilter,

    // 모달 제어
    openCreateModal,
    openEditModal,
    closeModal,
    updateFormData,

    // 삭제 다이얼로그 제어
    openDeleteDialog,
    closeDeleteDialog,

    // CRUD 작업
    saveCompany,
    deleteCompany,

    // 에러 처리
    clearError,
  } = useCompanyManagement();

  if (!isSuperAdmin) {
    return (
      <div className="flex h-full flex-col bg-background">
        <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("company.page.title")}</h1>
            <p className="text-sm text-muted-foreground">{t("company.page.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("company.access.denied.title")}</h3>
            <p className="text-muted-foreground mb-4 text-center text-sm">
              {t("company.access.denied.description")}
            </p>
            <Button variant="outline" onClick={() => window.history.back()}>
              {t("company.access.denied.back")}
            </Button>
          </div>
        </div>
      </div>
    );
  }

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

        {/* 디스크 사용량 요약 */}
        <DiskUsageSummary diskUsageInfo={diskUsageInfo} isLoading={isDiskUsageLoading} onRefresh={loadDiskUsage} />

        {/* 툴바 - 검색, 필터, 등록 버튼 */}
        <CompanyToolbar
          searchFilter={searchFilter}
          totalCount={companies.length}
          filteredCount={companies.length}
          onSearchChange={updateSearchFilter}
          onSearchClear={clearSearchFilter}
          onCreateClick={openCreateModal}
          t={t}
        />

        {/* 회사 목록 테이블 */}
        <CompanyTable companies={companies} isLoading={isLoading} onEdit={openEditModal} onDelete={openDeleteDialog} t={t} />

        {/* 회사 등록/수정 모달 */}
        <CompanyFormModal
          modalState={modalState}
          isLoading={isLoading}
          error={error}
          onClose={closeModal}
          onSave={saveCompany}
          onFormChange={updateFormData}
          onClearError={clearError}
          t={t}
        />

        {/* 회사 삭제 확인 다이얼로그 */}
        <CompanyDeleteDialog
          deleteState={deleteState}
          isLoading={isLoading}
          error={error}
          onClose={closeDeleteDialog}
          onConfirm={deleteCompany}
          onClearError={clearError}
          t={t}
        />
      </div>

      {/* Scroll to Top 버튼 */}
      <ScrollToTop />
    </div>
  );
}
