'use client';

export { BoardDetailClientV2 } from './BoardDetailClientV2';

import { useRouter } from 'next/navigation';
import { ClipboardList, Plus } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TabOption,
} from '@/components/templates/UniversalListPage';
import { getBoards, deleteBoard, deleteBoardsBulk } from './actions';
import type { Board } from './types';
import {
  BOARD_STATUS_LABELS,
  BOARD_STATUS_COLORS,
  BOARD_TARGET_LABELS,
} from './types';

// 날짜 포맷
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 대상 표시 텍스트
const getTargetDisplay = (board: Board) => {
  if (board.target === 'all') {
    return BOARD_TARGET_LABELS.all;
  }
  return board.targetName || BOARD_TARGET_LABELS.department;
};

// 탭 옵션 계산
const _computeTabs = (data: Board[]): TabOption[] => {
  const activeCount = data.filter((b) => b.status === 'active').length;
  const inactiveCount = data.filter((b) => b.status === 'inactive').length;

  return [
    { value: 'all', label: '전체', count: data.length, color: 'gray' },
    { value: 'active', label: '사용', count: activeCount, color: 'green' },
    { value: 'inactive', label: '미사용', count: inactiveCount, color: 'red' },
  ];
};

// UniversalListPage 설정 생성 함수
const createBoardManagementConfig = (router: ReturnType<typeof useRouter>): UniversalListConfig<Board> => ({
  // 페이지 기본 정보
  title: '게시판관리',
  description: '게시판 목록을 관리합니다',
  icon: ClipboardList,
  basePath: '/board/board-management',

  // ID 추출
  idField: 'id',

  // API 액션
  actions: {
    getList: async () => {
      const result = await getBoards();
      return {
        success: result.success,
        data: result.data,
        error: result.error,
      };
    },
    deleteItem: async (id: string) => {
      return await deleteBoard(id);
    },
    deleteBulk: async (ids: string[]) => {
      return await deleteBoardsBulk(ids);
    },
  },

  // 테이블 컬럼
  columns: [
    { key: 'rowNumber', label: 'No.', className: 'w-[60px] text-center' },
    { key: 'target', label: '대상', className: 'min-w-[100px]', copyable: true },
    { key: 'boardName', label: '게시판명', className: 'min-w-[150px]', copyable: true },
    { key: 'status', label: '상태', className: 'min-w-[80px]' },
    { key: 'authorName', label: '작성자', className: 'min-w-[100px]', copyable: true },
    { key: 'createdAt', label: '등록일시', className: 'min-w-[120px]', copyable: true },
  ],

  // 탭 설정 (클라이언트 사이드 계산)
  tabs: [
    { value: 'all', label: '전체', count: 0, color: 'gray' },
    { value: 'active', label: '사용', count: 0, color: 'green' },
    { value: 'inactive', label: '미사용', count: 0, color: 'red' },
  ],
  defaultTab: 'all',

  // 클라이언트 사이드 필터링
  clientSideFiltering: true,

  // 탭 필터
  tabFilter: (item, activeTab) => {
    if (activeTab === 'all') return true;
    return item.status === activeTab;
  },

  // 검색 필터
  searchFilter: (item, searchValue) => {
    const search = searchValue.toLowerCase();
    return (
      item.boardName.toLowerCase().includes(search) ||
      item.authorName.toLowerCase().includes(search) ||
      (item.targetName && item.targetName.toLowerCase().includes(search)) ||
      BOARD_TARGET_LABELS[item.target].toLowerCase().includes(search)
    );
  },

  // 검색 플레이스홀더
  searchPlaceholder: '게시판명, 작성자, 대상 검색...',

  // 등록 버튼
  createButton: {
    label: '게시판 등록',
    icon: Plus,
    onClick: () => router.push('/board/board-management?mode=new'),
  },

  // 삭제 확인 메시지
  deleteConfirmMessage: {
    title: '게시판 삭제',
    description: '선택한 게시판을 삭제하시겠습니까? 삭제된 게시판 정보는 복구할 수 없습니다.',
  },

  // 테이블 행 렌더링
  renderTableRow: (item, index, globalIndex, handlers) => {
    const { isSelected, onToggle, onRowClick, onEdit: _onEdit, onDelete: _onDelete } = handlers;

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50 cursor-pointer"
        onClick={() => onRowClick?.()}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox checked={isSelected} onCheckedChange={onToggle} />
        </TableCell>
        <TableCell className="text-muted-foreground text-center">
          {globalIndex}
        </TableCell>
        <TableCell>{getTargetDisplay(item)}</TableCell>
        <TableCell>{item.boardName}</TableCell>
        <TableCell>
          <Badge className={BOARD_STATUS_COLORS[item.status]}>
            {BOARD_STATUS_LABELS[item.status]}
          </Badge>
        </TableCell>
        <TableCell>{item.authorName}</TableCell>
        <TableCell>{formatDate(item.createdAt)}</TableCell>
      </TableRow>
    );
  },

  // 모바일 카드 렌더링
  renderMobileCard: (item, index, globalIndex, handlers) => {
    const { isSelected, onToggle, onRowClick, onEdit: _onEdit, onDelete: _onDelete } = handlers;

    return (
      <ListMobileCard
        id={item.id}
        title={item.boardName}
        headerBadges={
          <div className="flex items-center gap-2 flex-wrap">
            <Badge variant="outline" className="text-xs">
              {globalIndex}
            </Badge>
            <span className="text-xs text-muted-foreground">
              {getTargetDisplay(item)}
            </span>
          </div>
        }
        statusBadge={
          <Badge className={BOARD_STATUS_COLORS[item.status]}>
            {BOARD_STATUS_LABELS[item.status]}
          </Badge>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        onCardClick={onRowClick ? () => onRowClick() : undefined}
        infoGrid={
          <div className="grid grid-cols-2 gap-x-4 gap-y-3">
            <InfoField label="대상" value={getTargetDisplay(item)} />
            <InfoField label="작성자" value={item.authorName} />
            <InfoField label="등록일시" value={formatDate(item.createdAt)} />
          </div>
        }
      />
    );
  },
});

export function BoardManagement() {
  const router = useRouter();
  const config = createBoardManagementConfig(router);

  return <UniversalListPage<Board> config={config} />;
}