'use client';

/**
 * 공지사항 목록 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (날짜, 검색, 정렬)
 * - DateRangeSelector (headerActions)
 * - 정렬 filterConfig (PC: 인라인, 모바일: 바텀시트)
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Bell } from 'lucide-react';
import { TableCell, TableRow } from '@/components/ui/table';
import { Card, CardContent } from '@/components/ui/card';
import { Checkbox } from '@/components/ui/checkbox';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
} from '@/components/templates/UniversalListPage';
import {
  type Notice,
  type SortOption,
  SORT_OPTIONS,
  transformPostToNotice,
} from './types';
import { getPosts, deletePost } from '../shared/actions';

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

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

  // ===== 행 클릭 핸들러 =====
  const handleRowClick = useCallback(
    (item: Notice) => {
      router.push(`/ko/customer-center/notices/${item.id}?mode=view`);
    },
    [router]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Notice> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '공지사항',
      description: '공지사항을 확인합니다.',
      icon: Bell,
      basePath: '/customer-center/notices',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getPosts('notices', { per_page: 100 });
          if (result.success && result.data) {
            const transformed = result.data.data.map(transformPostToNotice);
            return { success: true, data: transformed, totalCount: transformed.length };
          }
          return { success: false, error: result.error };
        },
        deleteItem: async (id: string) => {
          const result = await deletePost('notices', id);
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'no', label: 'No.', className: 'w-[60px] text-center' },
        { key: 'title', label: '제목', className: 'min-w-[200px]', copyable: true },
        { key: 'author', label: '작성자', className: 'w-[100px] text-center', copyable: true },
        { key: 'createdAt', label: '등록일', className: 'w-[120px] text-center', copyable: true },
        { key: 'viewCount', label: '조회수', className: 'w-[80px] text-center', copyable: true },
      ],

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

      // 검색 필터
      searchPlaceholder: '제목, 작성자로 검색...',
      searchFilter: (item, searchValue) => {
        const searchLower = searchValue.toLowerCase();
        return (
          item.title.toLowerCase().includes(searchLower) ||
          item.author.toLowerCase().includes(searchLower)
        );
      },

      // 커스텀 필터 (날짜)
      customFilterFn: (items, _filterValues) => {
        if (!items || items.length === 0) return items;
        // 날짜 필터는 외부 상태 사용
        if (!startDate || !endDate) return items;
        return items.filter((item) => {
          const itemDate = item.createdAt;
          return itemDate >= startDate && itemDate <= endDate;
        });
      },

      // 커스텀 정렬 (filterValues에서 정렬 옵션 참조)
      customSortFn: (items, filterValues) => {
        const sorted = [...items];
        const sortOption = (filterValues.sort as SortOption) || 'latest';
        switch (sortOption) {
          case 'latest':
            sorted.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
            break;
          case 'oldest':
            sorted.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
            break;
          case 'views':
            sorted.sort((a, b) => b.viewCount - a.viewCount);
            break;
        }
        return sorted;
      },

      // 필터 설정 (PC: 인라인, 모바일: 바텀시트로 자동 분기)
      filterConfig: [
        {
          key: 'sort',
          label: '정렬',
          type: 'single',
          options: SORT_OPTIONS.map((opt) => ({ value: opt.value, label: opt.label })),
        },
      ],
      initialFilters: { sort: 'latest' },

      // 공통 헤더 옵션: 날짜 선택기 (왼쪽)
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 테이블 헤더 액션 (총 건수만 표시 - 정렬은 filterConfig로 이동)
      tableHeaderActions: ({ totalCount }) => (
        <span className="text-sm text-muted-foreground">
          총 {totalCount}건
        </span>
      ),

      // 테이블 행 렌더링
      renderTableRow: (
        item: Notice,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Notice>
      ) => {
        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={handlers.isSelected}
                onCheckedChange={handlers.onToggle}
              />
            </TableCell>
            <TableCell className="text-center">{globalIndex}</TableCell>
            <TableCell>{item.title}</TableCell>
            <TableCell className="text-center">{item.author}</TableCell>
            <TableCell className="text-center">{item.createdAt}</TableCell>
            <TableCell className="text-center">{item.viewCount}</TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Notice,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Notice>
      ) => {
        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={handlers.isSelected}
                    onCheckedChange={handlers.onToggle}
                  />
                </div>
                <div className="flex-1 space-y-2">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-muted-foreground">{globalIndex}</span>
                    <span className="text-sm text-muted-foreground">조회 {item.viewCount}</span>
                  </div>
                  <h3 className="font-medium">{item.title}</h3>
                  <div className="flex flex-wrap gap-2 text-sm text-muted-foreground">
                    <span>{item.author}</span>
                    <span>|</span>
                    <span>{item.createdAt}</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        );
      },
    }),
    [startDate, endDate, handleRowClick]
  );

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

export default NoticeList;
