'use client';

/**
 * 동적 게시판 목록 페이지
 * boardCode에 따라 동적으로 게시판 데이터를 로드
 * mode=new인 경우 글쓰기 폼 렌더링
 */

import { useState, useMemo, useCallback, useEffect, Suspense } from 'react';
import { useRouter, useParams, useSearchParams } from 'next/navigation';
import { DynamicBoardCreateForm } from '@/components/board/DynamicBoard/DynamicBoardCreateForm';
import { MessageSquare, Plus } from 'lucide-react';
import { ListPageSkeleton } from '@/components/ui/skeleton';
import { format } from 'date-fns';
import { TableCell, TableRow } from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TableColumn,
} from '@/components/templates/UniversalListPage';
import { getDynamicBoardPosts } from '@/components/board/DynamicBoard/actions';
import { getBoardByCode } from '@/components/board/BoardManagement/actions';
import type { PostApiData } from '@/components/customer-center/shared/types';

const ITEMS_PER_PAGE = 10;

// 정렬 옵션
const SORT_OPTIONS = [
  { value: 'latest', label: '최신순' },
  { value: 'oldest', label: '오래된순' },
];

// 게시글 상태 옵션
const STATUS_OPTIONS = [
  { value: 'all', label: '전체' },
  { value: 'published', label: '게시됨' },
  { value: 'draft', label: '임시저장' },
];

interface BoardPost {
  id: string;
  title: string;
  content: string;
  authorId: string;
  authorName: string;
  status: string;
  views: number;
  isNotice: boolean;
  createdAt: string;
  updatedAt: string;
}

// API 데이터 → 프론트엔드 타입 변환
function transformApiToPost(apiData: PostApiData): BoardPost {
  return {
    id: String(apiData.id),
    title: apiData.title,
    content: apiData.content,
    authorId: String(apiData.user_id),
    authorName: apiData.author?.name || '회원',
    status: apiData.status,
    views: apiData.views,
    isNotice: apiData.is_notice,
    createdAt: apiData.created_at,
    updatedAt: apiData.updated_at,
  };
}

// Suspense로 감싸는 wrapper 컴포넌트
export default function DynamicBoardListPage() {
  return (
    <Suspense fallback={<ListPageSkeleton />}>
      <ModeRouter />
    </Suspense>
  );
}

// mode에 따라 다른 컴포넌트 렌더링 (hooks rule 준수)
function ModeRouter() {
  const params = useParams();
  const searchParams = useSearchParams();
  const boardCode = params.boardCode as string;
  const mode = searchParams.get('mode');

  // mode=new인 경우 글쓰기 폼 렌더링
  if (mode === 'new') {
    return <DynamicBoardCreateForm boardCode={boardCode} />;
  }

  return <DynamicBoardListContent boardCode={boardCode} />;
}

// 실제 목록 컴포넌트 (자체 hooks 사용)
function DynamicBoardListContent({ boardCode }: { boardCode: string }) {
  const router = useRouter();

  // 게시판 정보
  const [boardName, setBoardName] = useState<string>('게시판');
  const [boardDescription, setBoardDescription] = useState<string>('');

  // 게시글 목록
  const [posts, setPosts] = useState<BoardPost[]>([]);
  const [, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 필터 및 검색
  const [searchValue, setSearchValue] = useState('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [sortOption, setSortOption] = useState<string>('latest');
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // 게시판 정보 로드
  useEffect(() => {
    async function fetchBoardInfo() {
      const result = await getBoardByCode(boardCode);
      if (result.success && result.data) {
        setBoardName(result.data.boardName);
        setBoardDescription(result.data.description || '');
      }
    }
    fetchBoardInfo();
  }, [boardCode]);

  // 게시글 목록 로드
  useEffect(() => {
    async function fetchPosts() {
      setIsLoading(true);
      setError(null);

      const result = await getDynamicBoardPosts(boardCode, { per_page: 100 });

      if (result.success && result.data) {
        const transformed = result.data.data.map(transformApiToPost);
        setPosts(transformed);
      } else {
        setError(result.error || '게시글 목록을 불러오는데 실패했습니다.');
      }

      setIsLoading(false);
    }

    fetchPosts();
  }, [boardCode]);

  // 필터링 및 정렬
  const filteredData = useMemo(() => {
    let result = [...posts];

    // 상태 필터
    if (statusFilter !== 'all') {
      result = result.filter((item) => item.status === statusFilter);
    }

    // 날짜 필터
    if (startDate && endDate) {
      result = result.filter((item) => {
        const itemDate = format(new Date(item.createdAt), 'yyyy-MM-dd');
        return itemDate >= startDate && itemDate <= endDate;
      });
    }

    // 검색 필터
    if (searchValue) {
      const searchLower = searchValue.toLowerCase();
      result = result.filter(
        (item) =>
          item.title.toLowerCase().includes(searchLower) ||
          item.authorName.toLowerCase().includes(searchLower)
      );
    }

    // 정렬
    if (sortOption === 'latest') {
      result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    } else {
      result.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
    }

    return result;
  }, [posts, statusFilter, startDate, endDate, searchValue, sortOption]);

  // 페이지네이션
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
    return filteredData.slice(startIndex, startIndex + ITEMS_PER_PAGE);
  }, [filteredData, currentPage]);

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

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

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

  const handleRowClick = useCallback(
    (item: BoardPost) => {
      router.push(`/ko/boards/${boardCode}/${item.id}?mode=view`);
    },
    [router, boardCode]
  );

  const handleCreate = useCallback(() => {
    router.push(`/ko/boards/${boardCode}?mode=new`);
  }, [router, boardCode]);

  // 상태 Badge
  const getStatusBadge = (status: string) => {
    if (status === 'published') {
      return <Badge variant="secondary" className="bg-green-100 text-green-700">게시됨</Badge>;
    }
    if (status === 'draft') {
      return <Badge variant="secondary" className="bg-yellow-100 text-yellow-700">임시저장</Badge>;
    }
    return <Badge variant="secondary">{status}</Badge>;
  };

  // 테이블 컬럼
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: 'No.', className: 'w-[60px] text-center' },
    { key: 'title', label: '제목', className: 'min-w-[200px]', copyable: true },
    { key: 'author', label: '작성자', className: 'w-[120px]', copyable: true },
    { key: 'views', label: '조회수', className: 'w-[80px] text-center', copyable: true },
    { key: 'status', label: '상태', className: 'w-[100px] text-center' },
    { key: 'createdAt', label: '등록일', className: 'w-[120px] text-center', copyable: true },
  ], []);

  // 테이블 행 렌더링
  const renderTableRow = useCallback(
    (
      item: BoardPost,
      index: number,
      globalIndex: number,
      handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
    ) => {
      const { isSelected, onToggle } = handlers;

      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={onToggle}
            />
          </TableCell>
          <TableCell className="text-center">{globalIndex}</TableCell>
          <TableCell>
            <div className="flex items-center gap-2">
              {item.isNotice && (
                <Badge variant="destructive" className="text-xs">공지</Badge>
              )}
              {item.title}
            </div>
          </TableCell>
          <TableCell>{item.authorName}</TableCell>
          <TableCell className="text-center">{item.views}</TableCell>
          <TableCell className="text-center">{getStatusBadge(item.status)}</TableCell>
          <TableCell className="text-center">
            {format(new Date(item.createdAt), 'yyyy-MM-dd')}
          </TableCell>
        </TableRow>
      );
    },
    [handleRowClick]
  );

  // 모바일 카드 렌더링
  const renderMobileCard = useCallback(
    (
      item: BoardPost,
      index: number,
      globalIndex: number,
      handlers: { isSelected: boolean; onToggle: () => void; onRowClick?: () => void }
    ) => {
      const { isSelected, onToggle } = handlers;
      return (
        <Card
          className="cursor-pointer hover:bg-muted/50"
          onClick={() => handleRowClick(item)}
        >
          <CardContent className="p-4">
            <div className="flex items-start gap-3">
              <div onClick={(e) => e.stopPropagation()}>
                <Checkbox checked={isSelected} onCheckedChange={onToggle} />
              </div>
              <div className="flex-1 space-y-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-muted-foreground">{globalIndex}</span>
                    {item.isNotice && (
                      <Badge variant="destructive" className="text-xs">공지</Badge>
                    )}
                  </div>
                  {getStatusBadge(item.status)}
                </div>
                <h3 className="font-medium">{item.title}</h3>
                <div className="flex items-center justify-between text-sm text-muted-foreground">
                  <span>{item.authorName}</span>
                  <span>{format(new Date(item.createdAt), 'yyyy-MM-dd')}</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      );
    },
    [handleRowClick]
  );

  if (error) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <p className="text-muted-foreground">{error}</p>
      </div>
    );
  }

  // UniversalListPage 설정
  const boardConfig: UniversalListConfig<BoardPost> = {
    title: boardName,
    description: boardDescription || `${boardName} 게시판입니다.`,
    icon: MessageSquare,
    basePath: `/boards/${boardCode}`,
    idField: 'id',

    actions: {
      getList: async () => ({
        success: true,
        data: filteredData,
        totalCount: filteredData.length,
      }),
    },

    columns: tableColumns,

    // 공통 패턴: dateRangeSelector + createButton + onSearchChange
    dateRangeSelector: {
      enabled: true,
      startDate,
      endDate,
      onStartDateChange: setStartDate,
      onEndDateChange: setEndDate,
    },
    createButton: {
      label: '글쓰기',
      icon: Plus,
      onClick: handleCreate,
    },
    onSearchChange: setSearchValue,

    tableHeaderActions: (
      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-muted-foreground whitespace-nowrap">
          총 {filteredData.length}건
        </span>
        <Select
          value={statusFilter}
          onValueChange={setStatusFilter}
        >
          <SelectTrigger className="min-w-[120px] w-auto">
            <SelectValue placeholder="상태" />
          </SelectTrigger>
          <SelectContent>
            {STATUS_OPTIONS.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select value={sortOption} onValueChange={setSortOption}>
          <SelectTrigger className="min-w-[100px] w-auto">
            <SelectValue placeholder="정렬" />
          </SelectTrigger>
          <SelectContent>
            {SORT_OPTIONS.map((option) => (
              <SelectItem key={option.value} value={option.value}>
                {option.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </div>
    ),

    searchPlaceholder: '제목, 작성자로 검색...',
    searchFilter: (item: BoardPost, search: string) => {
      const s = search.toLowerCase();
      return (
        item.title?.toLowerCase().includes(s) ||
        item.authorName?.toLowerCase().includes(s) ||
        false
      );
    },
    itemsPerPage: ITEMS_PER_PAGE,
    clientSideFiltering: true,

    renderTableRow,
    renderMobileCard,
  };

  return (
    <UniversalListPage<BoardPost>
      config={boardConfig}
      initialData={filteredData}
      initialTotalCount={filteredData.length}
      externalSelection={{
        selectedItems,
        setSelectedItems,
        onToggleSelection: handleToggleSelection,
        onToggleSelectAll: handleToggleSelectAll,
        getItemId: (item: BoardPost) => item.id,
      }}
      externalSearch={{
        searchValue: searchValue,
        setSearchValue: setSearchValue,
      }}
      externalPagination={{
        currentPage,
        totalPages,
        totalItems: filteredData.length,
        itemsPerPage: ITEMS_PER_PAGE,
        onPageChange: setCurrentPage,
      }}
    />
  );
}
