'use client';

/**
 * 팝업관리 리스트 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색)
 * - headerActions (팝업 등록 버튼)
 * - 선택 시 수정/삭제 버튼
 */

import { useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Megaphone } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import { TableCell, TableRow } from '@/components/ui/table';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent } from '@/components/ui/card';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
} from '@/components/templates/UniversalListPage';
import { type Popup } from './types';
import { deletePopup } from './actions';

interface PopupListProps {
  initialData: Popup[];
}

export function PopupList({ initialData }: PopupListProps) {
  const router = useRouter();

  // ===== 핸들러 =====
  const handleRowClick = useCallback(
    (item: Popup) => {
      router.push(`/ko/settings/popup-management/${item.id}?mode=view`);
    },
    [router]
  );

  const handleCreate = useCallback(() => {
    router.push('/ko/settings/popup-management?mode=new');
  }, [router]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Popup> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '팝업관리',
      description: '팝업 목록을 관리합니다.',
      icon: Megaphone,
      basePath: '/settings/popup-management',

      // ID 추출
      idField: 'id',

      // API 액션 (initialData 사용)
      actions: {
        getList: async () => {
          // initialData를 사용하므로 빈 배열 반환 (실제로는 호출되지 않음)
          return { success: true, data: [], totalCount: 0 };
        },
        deleteItem: async (id: string) => {
          const result = await deletePopup(id);
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: [
        { key: 'no', label: '번호', className: 'w-[60px] text-center' },
        { key: 'target', label: '대상', className: 'w-[80px] text-center', copyable: true },
        { key: 'title', label: '제목', className: 'min-w-[150px]', copyable: true },
        { key: 'status', label: '상태', className: 'w-[80px] text-center' },
        { key: 'author', label: '작성자', className: 'w-[100px] text-center', copyable: true },
        { key: 'createdAt', label: '등록일', className: 'w-[110px] text-center', copyable: true },
        { key: 'period', label: '기간', className: 'w-[180px] 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)
        );
      },

      // 공통 헤더 옵션: 등록 버튼 (오른쪽 끝)
      createButton: {
        label: '팝업 등록',
        onClick: handleCreate,
      },

      // 삭제 확인 메시지
      deleteConfirmMessage: {
        title: '팝업 삭제',
        description: '선택한 팝업을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.',
      },

      // 테이블 행 렌더링
      renderTableRow: (
        item: Popup,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Popup>
      ) => {
        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 className="text-center">
              {item.target === 'all' ? '전사' : item.targetName || '부서별'}
            </TableCell>
            <TableCell>{item.title}</TableCell>
            <TableCell className="text-center">
              <Badge variant={item.status === 'active' ? 'default' : 'secondary'}>
                {item.status === 'active' ? '사용함' : '사용안함'}
              </Badge>
            </TableCell>
            <TableCell className="text-center">{item.author}</TableCell>
            <TableCell className="text-center">{item.createdAt}</TableCell>
            <TableCell className="text-center">
              {item.startDate}~{item.endDate}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Popup,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Popup>
      ) => {
        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>
                    <Badge variant={item.status === 'active' ? 'default' : 'secondary'}>
                      {item.status === 'active' ? '사용함' : '사용안함'}
                    </Badge>
                  </div>
                  <h3 className="font-medium">{item.title}</h3>
                  <div className="flex flex-wrap gap-2 text-sm text-muted-foreground">
                    <span>{item.target === 'all' ? '전사' : item.targetName || '부서별'}</span>
                    <span>|</span>
                    <span>{item.author}</span>
                    <span>|</span>
                    <span>{item.createdAt}</span>
                  </div>
                  <div className="text-sm text-muted-foreground">
                    기간: {item.startDate} ~ {item.endDate}
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        );
      },
    }),
    [handleRowClick, handleCreate]
  );

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

export default PopupList;
