'use client';

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

import { useState, useMemo, useCallback, useEffect, useRef } 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 { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TabOption,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { toast } from 'sonner';
import type { Post } from '../types';
import { getBoards } from '../BoardManagement/actions';
import { isNextRedirectError } from '@/lib/utils/redirect-error';
import { getPosts, getMyPosts, deletePost } from '../actions';
import type { Board } from '../BoardManagement/types';

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

  // ===== 상태 관리 =====
  const [activeTab, setActiveTab] = useState<string>('');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

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

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

  // 데이터 상태
  const [boards, setBoards] = useState<Board[]>([]);
  const [posts, setPosts] = useState<Post[]>([]);
  const [totalItems, setTotalItems] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [isLoading, setIsLoading] = useState(true);
  const isInitialLoadDone = useRef(false);
  const [currentUserId, setCurrentUserId] = useState<string>('');
  const [searchQuery, setSearchQuery] = useState('');

  // ===== 게시판 목록 조회 (탭 생성용) =====
  useEffect(() => {
    async function fetchBoards() {
      const result = await getBoards();
      if (result.success && result.data) {
        setBoards(result.data);
        if (result.data.length > 0 && !activeTab) {
          setActiveTab(result.data[0].boardCode);
        }
      }
    }
    fetchBoards();
  }, []);

  // ===== 게시글 목록 조회 =====
  useEffect(() => {
    async function fetchPosts() {
      if (!activeTab) return;

      if (!isInitialLoadDone.current) {
        setIsLoading(true);
      }
      try {
        let result;

        if (activeTab === 'my') {
          result = await getMyPosts({
            search: searchQuery || undefined,
            per_page: itemsPerPage,
            page: currentPage,
          });
        } else {
          result = await getPosts(activeTab, {
            search: searchQuery || undefined,
            per_page: itemsPerPage,
            page: currentPage,
          });
        }

        if (result.success && result.posts) {
          setPosts(result.posts);
          if (result.data) {
            setTotalItems(result.data.total);
            setTotalPages(result.data.last_page);
          }
        } else {
          setPosts([]);
          setTotalItems(0);
          setTotalPages(1);
          if (result.error) {
            toast.error(result.error);
          }
        }
      } catch (error) {
        if (isNextRedirectError(error)) throw error;
        console.error('게시글 조회 오류:', error);
        setPosts([]);
      } finally {
        setIsLoading(false);
        isInitialLoadDone.current = true;
      }
    }

    fetchPosts();
  }, [activeTab, currentPage, searchQuery]);

  // ===== 현재 사용자 ID 가져오기 =====
  useEffect(() => {
    if (typeof window !== 'undefined') {
      const userId = localStorage.getItem('user_id') || '';
      setCurrentUserId(userId);
    }
  }, []);

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

  const handleNewPost = useCallback(() => {
    const boardCode = activeTab !== 'my' ? activeTab : boards[0]?.boardCode;
    if (boardCode) {
      router.push(`/ko/board/${boardCode}?mode=new`);
    } else {
      router.push('/ko/board?mode=new');
    }
  }, [router, activeTab, boards]);

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

  const handleConfirmDelete = useCallback(async () => {
    if (deleteTargetId && deleteTargetBoardCode) {
      const result = await deletePost(deleteTargetBoardCode, deleteTargetId);
      if (result.success) {
        setPosts((prev) => prev.filter((item) => item.id !== deleteTargetId));
        toast.success('게시글이 삭제되었습니다.');
      } else {
        toast.error(result.error || '게시글 삭제에 실패했습니다.');
      }
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
    setDeleteTargetBoardCode('');
  }, [deleteTargetId, deleteTargetBoardCode]);

  // ===== 탭 옵션 (게시판 목록 + 나의 게시글) =====
  const tabs: TabOption[] = useMemo(() => {
    const boardTabs = boards.map((board) => ({
      value: board.boardCode,
      label: board.boardName,
      count: 0,
    }));

    return [
      ...boardTabs,
      {
        value: 'my',
        label: '나의 게시글',
        count: 0,
      },
    ];
  }, [boards]);

  // ===== 정렬된 데이터 (상단 고정 우선) =====
  const sortedData = useMemo(() => {
    const result = [...posts];
    result.sort((a, b) => {
      if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;
      return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
    });
    return result;
  }, [posts]);

  // ===== 탭 변경 핸들러 =====
  const handleTabChange = useCallback((tab: string) => {
    setActiveTab(tab);
    setCurrentPage(1);
  }, []);

  // ===== UniversalListPage 설정 =====
  const boardListConfig: UniversalListConfig<Post> = useMemo(
    () => ({
      title: '게시판',
      description: '게시판의 게시글을 등록하고 관리합니다.',
      icon: FileText,
      basePath: '/board',

      idField: 'id',

      actions: {
        getList: async () => ({
          success: true,
          data: sortedData,
          totalCount: totalItems,
          totalPages: totalPages,
        }),
      },

      columns: [
        { key: 'no', label: 'No.', className: 'w-[60px] text-center' },
        { key: 'title', label: '제목', className: 'min-w-[300px]', sortable: true, copyable: true },
        { key: 'author', label: '작성자', className: 'w-[120px]', sortable: true, copyable: true },
        { key: 'createdAt', label: '등록일', className: 'w-[120px]', sortable: true, copyable: true },
        { key: 'viewCount', label: '조회수', className: 'w-[80px] text-center', sortable: true, copyable: true },
        { key: 'actions', label: '작업', className: 'w-[100px] text-center' },
      ],

      tabs: tabs,
      defaultTab: activeTab,

      dateRangeSelector: {
        enabled: true,
        showPresets: false,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      createButton: {
        label: '게시글 등록',
        icon: Plus,
        onClick: handleNewPost,
      },

      searchPlaceholder: '제목, 작성자 검색...',

      itemsPerPage: itemsPerPage,

      renderTableRow: (item, index, globalIndex, handlers) => {
        const { isSelected, onToggle, onRowClick } = handlers;
        const isMyPost = item.authorId === currentUserId;

        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-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">
                  공지
                </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>
                )}
                {item.isSecret && (
                  <span className="text-xs text-gray-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.boardCode}/${item.id}?mode=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, item.boardCode)}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              )}
            </TableCell>
          </TableRow>
        );
      },

      renderMobileCard: (item, index, globalIndex, handlers) => {
        const { isSelected, onToggle, onRowClick } = handlers;
        const isMyPost = item.authorId === currentUserId;

        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>
                )}
                {item.isSecret && (
                  <span className="text-xs text-gray-500 font-medium">[비밀]</span>
                )}
                <span>{item.title}</span>
              </div>
            }
            isSelected={isSelected}
            onToggleSelection={onToggle}
            onCardClick={onRowClick ? () => onRowClick() : undefined}
            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.boardCode}/${item.id}?mode=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, item.boardCode)}
                  >
                    <Trash2 className="w-4 h-4 mr-2" /> 삭제
                  </Button>
                </div>
              ) : undefined
            }
          />
        );
      },

      renderDialogs: () => (
        <DeleteConfirmDialog
          open={showDeleteDialog}
          onOpenChange={setShowDeleteDialog}
          onConfirm={handleConfirmDelete}
          title="게시글 삭제"
          description="정말 삭제하시겠습니까?"
        />
      ),
    }),
    [
      sortedData,
      totalItems,
      totalPages,
      tabs,
      activeTab,
      startDate,
      endDate,
      handleNewPost,
      currentUserId,
      router,
      handleDeleteClick,
      showDeleteDialog,
      handleConfirmDelete,
    ]
  );

  return (
    <UniversalListPage<Post>
      config={boardListConfig}
      initialData={sortedData}
      initialTotalCount={totalItems}
      externalPagination={{
        currentPage,
        totalPages,
        totalItems,
        itemsPerPage,
        onPageChange: (page) => {
          setCurrentPage(page);
        },
      }}
      onTabChange={handleTabChange}
      onSearchChange={setSearchQuery}
      externalIsLoading={isLoading}
    />
  );
}

export default BoardList;
