'use client';

/**
 * 팝업관리 리스트 컴포넌트
 *
 * 디자인 스펙:
 * - 페이지 타이틀: 팝업관리
 * - 페이지 설명: 팝업 목록을 관리합니다.
 * - 테이블 컬럼: 체크박스, No, 대상, 제목, 상태, 작성자, 등록일, 기간, 작업
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Megaphone, Plus, Pencil, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type PaginationConfig,
} from '@/components/templates/IntegratedListTemplateV2';
import { type Popup, MOCK_POPUPS } from './types';

const ITEMS_PER_PAGE = 10;

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

  // ===== 상태 관리 =====
  const [popups] = useState<Popup[]>(MOCK_POPUPS);
  const [searchValue, setSearchValue] = useState('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);

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

  // ===== 필터링된 데이터 =====
  const filteredData = useMemo(() => {
    let result = [...popups];

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

    return result;
  }, [popups, searchValue]);

  // ===== 페이지네이션 =====
  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: Popup) => {
    router.push(`/ko/settings/popup-management/${item.id}`);
  }, [router]);

  const handleEdit = useCallback(
    (id: string) => {
      router.push(`/ko/settings/popup-management/${id}/edit`);
    },
    [router]
  );

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

  const handleConfirmDelete = useCallback(() => {
    if (deleteTargetId) {
      console.log('Delete popup:', deleteTargetId);
      // TODO: API 호출
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
  }, [deleteTargetId]);

  const handleBulkDelete = useCallback(() => {
    console.log('Bulk delete:', Array.from(selectedItems));
    // TODO: API 호출
    setSelectedItems(new Set());
  }, [selectedItems]);

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

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = [
    { key: 'no', label: '번호', className: 'w-[60px] text-center' },
    { key: 'target', label: '대상', className: 'w-[80px] text-center' },
    { key: 'title', label: '제목', className: 'min-w-[150px]' },
    { key: 'status', label: '상태', className: 'w-[80px] text-center' },
    { key: 'author', label: '작성자', className: 'w-[100px] text-center' },
    { key: 'createdAt', label: '등록일', className: 'w-[110px] text-center' },
    { key: 'period', label: '기간', className: 'w-[180px] text-center' },
    { key: 'actions', label: '작업', className: 'w-[180px] text-center' },
  ];

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback(
    (item: Popup, index: number, globalIndex: number) => {
      const isSelected = selectedItems.has(item.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={() => handleToggleSelection(item.id)}
            />
          </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>
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            {isSelected && (
              <div className="flex items-center justify-center gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleEdit(item.id)}
                  title="수정"
                >
                  <Pencil className="h-4 w-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => handleDelete(item.id)}
                  title="삭제"
                  className="text-destructive hover:text-destructive"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            )}
          </TableCell>
        </TableRow>
      );
    },
    [
      selectedItems,
      handleRowClick,
      handleToggleSelection,
      handleEdit,
      handleDelete,
    ]
  );

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback(
    (
      item: Popup,
      index: number,
      globalIndex: number,
      isSelected: boolean,
      onToggle: () => void
    ) => {
      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">
                  <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>
                {isSelected && (
                  <div className="flex gap-2 pt-2" onClick={(e) => e.stopPropagation()}>
                    <Button variant="outline" size="sm" onClick={() => handleEdit(item.id)}>
                      수정
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="text-destructive"
                      onClick={() => handleDelete(item.id)}
                    >
                      삭제
                    </Button>
                  </div>
                )}
              </div>
            </div>
          </CardContent>
        </Card>
      );
    },
    [handleRowClick, handleEdit, handleDelete]
  );

  // ===== 페이지네이션 설정 =====
  const pagination: PaginationConfig = {
    currentPage,
    totalPages,
    totalItems: filteredData.length,
    itemsPerPage: ITEMS_PER_PAGE,
    onPageChange: setCurrentPage,
  };

  return (
    <>
      <IntegratedListTemplateV2
        title="팝업관리"
        description="팝업 목록을 관리합니다."
        icon={Megaphone}
        headerActions={
          <Button className="ml-auto" onClick={handleCreate}>
            <Plus className="h-4 w-4 mr-2" />
            팝업 등록
          </Button>
        }
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        searchPlaceholder="제목, 작성자로 검색..."
        tableColumns={tableColumns}
        data={paginatedData}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={handleToggleSelection}
        onToggleSelectAll={handleToggleSelectAll}
        getItemId={(item) => item.id}
        onBulkDelete={handleBulkDelete}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={pagination}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>팝업 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              선택한 팝업을 삭제하시겠습니까? 이 작업은 되돌릴 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction onClick={handleConfirmDelete}>삭제</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}

export default PopupList;
