'use client';

/**
 * 게시판 리스트 컴포넌트
 *
 * 디자인 스펙 기준:
 * - 페이지 타이틀: 게시판
 * - 페이지 설명: 게시판의 게시글을 등록하고 관리합니다.
 * - 테이블 컬럼: No., 제목, 작성자, 등록일, 조회수
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import { FileText, Plus, Pencil, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  IntegratedListTemplateV2,
  type TabOption,
  type TableColumn,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import type { Post, SortOption, BoardFilter } from '../types';
import { BOARD_FILTER_OPTIONS, MOCK_BOARDS } from '../types';

// ===== Mock 데이터 생성 =====
const generateMockPosts = (): Post[] => {
  const authors = [
    { id: 'user1', name: '홍길동', department: '개발팀', position: '과장' },
    { id: 'user2', name: '김철수', department: '인사팀', position: '대리' },
    { id: 'user3', name: '이영희', department: '총무팀', position: '사원' },
    { id: 'user4', name: '박지민', department: '마케팅팀', position: '차장' },
  ];
  const titles = [
    '제목',
    '2025년 1분기 사업계획 공지',
    '시스템 점검 안내',
    '연말 휴가 일정 안내',
    '신규 프로젝트 착수 회의',
  ];
  const boards = MOCK_BOARDS.filter((b) => b.id !== 'all');

  return Array.from({ length: 50 }, (_, i) => {
    const author = authors[i % authors.length];
    const board = boards[i % boards.length];
    const dayOffset = i % 30;

    return {
      id: `post-${i + 1}`,
      boardId: board.id,
      boardName: board.name,
      title: titles[i % titles.length],
      content: `<p>게시글 내용 ${i + 1}입니다. 이것은 테스트용 콘텐츠입니다.</p>`,
      authorId: author.id,
      authorName: author.name,
      authorDepartment: author.department,
      authorPosition: author.position,
      isPinned: i < 3, // 상위 3개만 상단 고정
      allowComments: i % 2 === 0,
      viewCount: 100 + i * 7,
      attachments: i % 3 === 0 ? [
        {
          id: `file-${i}`,
          fileName: 'abc.pdf',
          fileSize: 1024000,
          fileUrl: '/files/abc.pdf',
          mimeType: 'application/pdf',
        },
      ] : [],
      createdAt: format(new Date(2025, 8, dayOffset + 1, 12, 20), "yyyy-MM-dd'T'HH:mm:ss"),
      updatedAt: format(new Date(2025, 8, dayOffset + 1, 12, 20), "yyyy-MM-dd'T'HH:mm:ss"),
    };
  });
};

// 현재 로그인 사용자 ID (실제로는 auth context에서 가져옴)
const CURRENT_USER_ID = 'user1';

export function BoardList() {
  const router = useRouter();

  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption] = useState<SortOption>('latest'); // 기본 정렬: 최신순
  const [boardFilter, setBoardFilter] = useState<BoardFilter>('notice');
  const [activeTab, setActiveTab] = useState<string>('notice'); // 첫 번째 탭: 공지사항
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 날짜 범위 상태
  const [startDate, setStartDate] = useState('2025-09-01');
  const [endDate, setEndDate] = useState('2025-09-03');

  // 삭제 다이얼로그
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);

  // Mock 데이터
  const [data, setData] = useState<Post[]>(generateMockPosts);

  // ===== 체크박스 핸들러 =====
  const toggleSelection = useCallback((id: string) => {
    setSelectedItems((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) newSet.delete(id);
      else newSet.add(id);
      return newSet;
    });
  }, []);

  const toggleSelectAll = useCallback(() => {
    if (selectedItems.size === filteredData.length && filteredData.length > 0) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(filteredData.map((item) => item.id)));
    }
  }, [selectedItems.size]);

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    let result = data.filter((item) =>
      item.title.includes(searchQuery) ||
      item.authorName.includes(searchQuery)
    );

    // 탭 필터 (게시판 종류 또는 나의 게시글)
    if (activeTab === 'my') {
      // 나의 게시글 탭: 현재 사용자 게시글만
      result = result.filter((item) => item.authorId === CURRENT_USER_ID);
    } else if (activeTab !== 'all') {
      // 특정 게시판 탭
      result = result.filter((item) => item.boardId === activeTab);
    }

    // 게시판 필터 드롭다운 (탭과 별개로 추가 필터링)
    if (boardFilter === 'my') {
      result = result.filter((item) => item.authorId === CURRENT_USER_ID);
    } else if (boardFilter !== 'all' && boardFilter !== 'notice') {
      result = result.filter((item) => item.boardId === boardFilter);
    }

    // 정렬 (상단 고정은 항상 최상위)
    result.sort((a, b) => {
      // 상단 고정 우선
      if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;

      // 정렬 옵션에 따라
      switch (sortOption) {
        case 'latest':
          return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
        case 'oldest':
          return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
        case 'viewCount':
          return b.viewCount - a.viewCount;
        default:
          return 0;
      }
    });

    return result;
  }, [data, searchQuery, activeTab, boardFilter, sortOption]);

  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredData.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredData, currentPage, itemsPerPage]);

  const totalPages = Math.ceil(filteredData.length / itemsPerPage);

  // ===== 액션 핸들러 =====
  const handleRowClick = useCallback((item: Post) => {
    router.push(`/ko/board/${item.id}`);
  }, [router]);

  const handleNewPost = useCallback(() => {
    router.push('/ko/board/create');
  }, [router]);

  const handleDeleteClick = useCallback((id: string) => {
    setDeleteTargetId(id);
    setShowDeleteDialog(true);
  }, []);

  const handleConfirmDelete = useCallback(() => {
    if (deleteTargetId) {
      setData((prev) => prev.filter((item) => item.id !== deleteTargetId));
      setSelectedItems((prev) => {
        const newSet = new Set(prev);
        newSet.delete(deleteTargetId);
        return newSet;
      });
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
  }, [deleteTargetId]);

  // ===== 탭 옵션 (공지사항 고정 + 동적 게시판들 + 나의 게시글 고정) =====
  const tabs: TabOption[] = useMemo(() => {
    // 동적으로 생성되는 게시판들 (공지사항, 전체, 나의게시글 제외)
    const dynamicBoards = MOCK_BOARDS.filter(
      (b) => b.id !== 'all' && b.id !== 'notice' && b.id !== 'my'
    );

    return [
      // 첫 번째: 공지사항 (고정)
      {
        value: 'notice',
        label: '공지사항',
        count: data.filter((p) => p.boardId === 'notice').length,
      },
      // 중간: 동적 게시판들
      ...dynamicBoards.map((board) => ({
        value: board.id,
        label: board.name,
        count: data.filter((p) => p.boardId === board.id).length,
      })),
      // 마지막: 나의 게시글 (고정)
      {
        value: 'my',
        label: '나의 게시글',
        count: data.filter((p) => p.authorId === CURRENT_USER_ID).length,
      },
    ];
  }, [data]);

  // ===== 테이블 컬럼 (스크린샷 기준: No., 제목, 작성자, 등록일, 조회수) =====
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: 'No.', className: 'w-[60px] text-center' },
    { key: 'title', label: '제목', className: 'min-w-[300px]' },
    { key: 'author', label: '작성자', className: 'w-[120px]' },
    { key: 'createdAt', label: '등록일', className: 'w-[120px]' },
    { key: 'viewCount', label: '조회수', className: 'w-[80px] text-center' },
    { key: 'actions', label: '작업', className: 'w-[100px] text-center' },
  ], []);

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback((item: Post, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(item.id);
    const isMyPost = item.authorId === CURRENT_USER_ID;

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50 cursor-pointer"
        onClick={() => handleRowClick(item)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox checked={isSelected} onCheckedChange={() => toggleSelection(item.id)} />
        </TableCell>
        {/* No. */}
        <TableCell className="text-center text-sm text-gray-500">
          {item.isPinned ? (
            <span className="inline-flex items-center justify-center w-6 h-6 bg-red-500 text-white rounded-full text-xs font-bold">
              {globalIndex}
            </span>
          ) : (
            globalIndex
          )}
        </TableCell>
        {/* 제목 */}
        <TableCell className="font-medium">
          <div className="flex items-center gap-2">
            {item.isPinned && (
              <span className="text-xs text-red-500 font-medium">[공지]</span>
            )}
            <span className="truncate">{item.title}</span>
          </div>
        </TableCell>
        {/* 작성자 */}
        <TableCell>{item.authorName}</TableCell>
        {/* 등록일 */}
        <TableCell>{format(new Date(item.createdAt), 'yyyy-MM-dd')}</TableCell>
        {/* 조회수 */}
        <TableCell className="text-center">{item.viewCount}</TableCell>
        {/* 작업 */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          {isSelected && isMyPost && (
            <div className="flex items-center justify-center gap-1">
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
                onClick={() => router.push(`/ko/board/${item.id}/edit`)}
              >
                <Pencil className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
                onClick={() => handleDeleteClick(item.id)}
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleRowClick, handleDeleteClick, router]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: Post,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    const isMyPost = item.authorId === CURRENT_USER_ID;

    return (
      <ListMobileCard
        id={item.id}
        title={
          <div className="flex items-center gap-2">
            {item.isPinned && (
              <span className="text-xs text-red-500 font-medium">[공지]</span>
            )}
            <span>{item.title}</span>
          </div>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="작성자" value={item.authorName} />
            <InfoField label="등록일" value={format(new Date(item.createdAt), 'yyyy-MM-dd')} />
            <InfoField label="조회수" value={String(item.viewCount)} />
            <InfoField label="게시판" value={item.boardName} />
          </div>
        }
        actions={
          isSelected && isMyPost ? (
            <div className="flex gap-2 w-full">
              <Button
                variant="outline"
                className="flex-1"
                onClick={() => router.push(`/ko/board/${item.id}/edit`)}
              >
                <Pencil className="w-4 h-4 mr-2" /> 수정
              </Button>
              <Button
                variant="outline"
                className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
                onClick={() => handleDeleteClick(item.id)}
              >
                <Trash2 className="w-4 h-4 mr-2" /> 삭제
              </Button>
            </div>
          ) : undefined
        }
        onClick={() => handleRowClick(item)}
      />
    );
  }, [handleRowClick, handleDeleteClick, router]);

  // ===== 헤더 액션 =====
  const headerActions = (
    <>
      <DateRangeSelector
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
      />
      <Button className="ml-auto" onClick={handleNewPost}>
        <Plus className="h-4 w-4 mr-2" />
        게시글 등록
      </Button>
    </>
  );

  // ===== 테이블 헤더 액션 (필터 1개만: 게시판) =====
  const tableHeaderActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 게시판 필터 */}
      <Select value={boardFilter} onValueChange={(value) => setBoardFilter(value as BoardFilter)}>
        <SelectTrigger className="w-[140px]">
          <SelectValue placeholder="게시판" />
        </SelectTrigger>
        <SelectContent>
          {BOARD_FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  return (
    <>
      <IntegratedListTemplateV2<Post>
        title="게시판"
        description="게시판의 게시글을 등록하고 관리합니다."
        icon={FileText}
        headerActions={headerActions}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="제목, 작성자 검색..."
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredData.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>게시글 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              정말 삭제하시겠습니까?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

export default BoardList;