'use client';

import { useState, useMemo } from 'react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { PageHeader } from '@/components/organisms/PageHeader';
import { Building2 } from 'lucide-react';
import { DepartmentStats } from './DepartmentStats';
import { DepartmentToolbar } from './DepartmentToolbar';
import { DepartmentTree } from './DepartmentTree';
import { DepartmentDialog } from './DepartmentDialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import type { Department } from './types';
import { countAllDepartments, getAllDepartmentIds, findDepartmentById } from './types';

/**
 * 무제한 깊이 트리 구조 목업 데이터
 */
const mockDepartments: Department[] = [
  {
    id: 1,
    name: '회사명',
    parentId: null,
    depth: 0,
    children: [
      {
        id: 2,
        name: '경영지원본부',
        parentId: 1,
        depth: 1,
        children: [
          {
            id: 4,
            name: '인사팀',
            parentId: 2,
            depth: 2,
            children: [
              {
                id: 7,
                name: '채용파트',
                parentId: 4,
                depth: 3,
                children: [
                  { id: 10, name: '신입채용셀', parentId: 7, depth: 4, children: [] },
                  { id: 11, name: '경력채용셀', parentId: 7, depth: 4, children: [] },
                ]
              },
              { id: 8, name: '교육파트', parentId: 4, depth: 3, children: [] },
            ]
          },
          { id: 5, name: '총무팀', parentId: 2, depth: 2, children: [] },
        ]
      },
      {
        id: 3,
        name: '개발본부',
        parentId: 1,
        depth: 1,
        children: [
          { id: 6, name: '프론트엔드팀', parentId: 3, depth: 2, children: [] },
          { id: 9, name: '백엔드팀', parentId: 3, depth: 2, children: [] },
        ]
      },
    ]
  }
];

export function DepartmentManagement() {
  // 부서 데이터 상태
  const [departments, setDepartments] = useState<Department[]>(mockDepartments);

  // 선택 상태
  const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());

  // 펼침 상태 (기본: 최상위만 펼침)
  const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set([1]));

  // 검색어
  const [searchQuery, setSearchQuery] = useState('');

  // 다이얼로그 상태
  const [dialogOpen, setDialogOpen] = useState(false);
  const [dialogMode, setDialogMode] = useState<'add' | 'edit'>('add');
  const [selectedDepartment, setSelectedDepartment] = useState<Department | undefined>();
  const [parentDepartment, setParentDepartment] = useState<Department | undefined>();

  // 삭제 확인 다이얼로그
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [departmentToDelete, setDepartmentToDelete] = useState<Department | null>(null);
  const [isBulkDelete, setIsBulkDelete] = useState(false);

  // 전체 부서 수 계산
  const totalCount = useMemo(() => countAllDepartments(departments), [departments]);

  // 모든 부서 ID
  const allIds = useMemo(() => getAllDepartmentIds(departments), [departments]);

  // 펼침/접힘 토글
  const handleToggleExpand = (id: number) => {
    setExpandedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  // 선택 토글
  const handleToggleSelect = (id: number) => {
    setSelectedIds(prev => {
      const next = new Set(prev);
      if (next.has(id)) {
        next.delete(id);
      } else {
        next.add(id);
      }
      return next;
    });
  };

  // 전체 선택/해제
  const handleToggleSelectAll = () => {
    if (selectedIds.size === allIds.length) {
      setSelectedIds(new Set());
    } else {
      setSelectedIds(new Set(allIds));
    }
  };

  // 부서 추가 (행 버튼)
  const handleAdd = (parentId: number) => {
    const parent = findDepartmentById(departments, parentId);
    setParentDepartment(parent || undefined);
    setSelectedDepartment(undefined);
    setDialogMode('add');
    setDialogOpen(true);
  };

  // 부서 추가 (상단 버튼 - 선택된 부서의 하위에 일괄 추가)
  const handleBulkAdd = () => {
    if (selectedIds.size === 0) {
      // 선택된 부서가 없으면 최상위에 추가
      setParentDepartment(undefined);
    } else {
      // 선택된 첫 번째 부서를 부모로 설정
      const firstSelectedId = Array.from(selectedIds)[0];
      const parent = findDepartmentById(departments, firstSelectedId);
      setParentDepartment(parent || undefined);
    }
    setSelectedDepartment(undefined);
    setDialogMode('add');
    setDialogOpen(true);
  };

  // 부서 수정
  const handleEdit = (department: Department) => {
    setSelectedDepartment(department);
    setParentDepartment(undefined);
    setDialogMode('edit');
    setDialogOpen(true);
  };

  // 부서 삭제 (단일)
  const handleDelete = (department: Department) => {
    setDepartmentToDelete(department);
    setIsBulkDelete(false);
    setDeleteDialogOpen(true);
  };

  // 부서 삭제 (일괄)
  const handleBulkDelete = () => {
    if (selectedIds.size === 0) return;
    setDepartmentToDelete(null);
    setIsBulkDelete(true);
    setDeleteDialogOpen(true);
  };

  // 삭제 확인
  const confirmDelete = () => {
    if (isBulkDelete) {
      // 일괄 삭제 로직
      setDepartments(prev => deleteDepartmentsRecursive(prev, selectedIds));
      setSelectedIds(new Set());
    } else if (departmentToDelete) {
      // 단일 삭제 로직
      setDepartments(prev => deleteDepartmentsRecursive(prev, new Set([departmentToDelete.id])));
      setSelectedIds(prev => {
        const next = new Set(prev);
        next.delete(departmentToDelete.id);
        return next;
      });
    }
    setDeleteDialogOpen(false);
    setDepartmentToDelete(null);
  };

  // 재귀적으로 부서 삭제
  const deleteDepartmentsRecursive = (depts: Department[], idsToDelete: Set<number>): Department[] => {
    return depts
      .filter(dept => !idsToDelete.has(dept.id))
      .map(dept => ({
        ...dept,
        children: dept.children ? deleteDepartmentsRecursive(dept.children, idsToDelete) : []
      }));
  };

  // 부서 추가/수정 제출
  const handleDialogSubmit = (name: string) => {
    if (dialogMode === 'add') {
      // 새 부서 추가
      const newId = Math.max(...allIds, 0) + 1;
      const newDept: Department = {
        id: newId,
        name,
        parentId: parentDepartment?.id || null,
        depth: parentDepartment ? parentDepartment.depth + 1 : 0,
        children: []
      };

      if (parentDepartment) {
        // 부모 부서의 children에 추가
        setDepartments(prev => addChildDepartment(prev, parentDepartment.id, newDept));
      } else {
        // 최상위에 추가
        setDepartments(prev => [...prev, newDept]);
      }
    } else if (dialogMode === 'edit' && selectedDepartment) {
      // 부서 수정
      setDepartments(prev => updateDepartmentName(prev, selectedDepartment.id, name));
    }
    setDialogOpen(false);
  };

  // 재귀적으로 자식 부서 추가
  const addChildDepartment = (depts: Department[], parentId: number, newDept: Department): Department[] => {
    return depts.map(dept => {
      if (dept.id === parentId) {
        return {
          ...dept,
          children: [...(dept.children || []), newDept]
        };
      }
      if (dept.children) {
        return {
          ...dept,
          children: addChildDepartment(dept.children, parentId, newDept)
        };
      }
      return dept;
    });
  };

  // 재귀적으로 부서명 업데이트
  const updateDepartmentName = (depts: Department[], id: number, name: string): Department[] => {
    return depts.map(dept => {
      if (dept.id === id) {
        return { ...dept, name };
      }
      if (dept.children) {
        return {
          ...dept,
          children: updateDepartmentName(dept.children, id, name)
        };
      }
      return dept;
    });
  };

  return (
    <PageLayout>
      <PageHeader
        title="부서관리"
        description="부서 정보를 관리합니다"
        icon={Building2}
      />

      <div className="space-y-4">
        {/* 전체 부서 카운트 */}
        <DepartmentStats totalCount={totalCount} />

        {/* 검색 + 추가/삭제 버튼 */}
        <DepartmentToolbar
          totalCount={totalCount}
          selectedCount={selectedIds.size}
          searchQuery={searchQuery}
          onSearchChange={setSearchQuery}
          onAdd={handleBulkAdd}
          onDelete={handleBulkDelete}
        />

        {/* 트리 테이블 */}
        <DepartmentTree
          departments={departments}
          expandedIds={expandedIds}
          selectedIds={selectedIds}
          onToggleExpand={handleToggleExpand}
          onToggleSelect={handleToggleSelect}
          onToggleSelectAll={handleToggleSelectAll}
          onAdd={handleAdd}
          onEdit={handleEdit}
          onDelete={handleDelete}
        />
      </div>

      {/* 추가/수정 다이얼로그 */}
      <DepartmentDialog
        isOpen={dialogOpen}
        onOpenChange={setDialogOpen}
        mode={dialogMode}
        parentDepartment={parentDepartment}
        department={selectedDepartment}
        onSubmit={handleDialogSubmit}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>부서 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              {isBulkDelete
                ? `선택한 부서 ${selectedIds.size}개를 삭제하시겠습니까?`
                : `"${departmentToDelete?.name}" 부서를 삭제하시겠습니까?`
              }
              <br />
              <span className="text-destructive">
                삭제된 부서의 인원은 회사(기본) 인원으로 변경됩니다.
              </span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </PageLayout>
  );
}