'use client';

/**
 * 이벤트 목록 컴포넌트
 *
 * 디자인 스펙:
 * - 페이지 타이틀: 이벤트
 * - 페이지 설명: 이벤트를 확인합니다.
 * - 날짜 범위 선택 + 기간 프리셋 버튼
 * - 탭: 진행중인 이벤트 / 종료된 이벤트
 * - 검색 + 정렬 (최신순)
 * - 테이블 컬럼: No, 제목, 작성자, 기간, 조회수
 */

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Calendar } from 'lucide-react';
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type TabOption,
  type PaginationConfig,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import {
  type Event,
  type EventTab,
  type SortOption,
  SORT_OPTIONS,
  MOCK_EVENTS,
} from './types';

const ITEMS_PER_PAGE = 10;

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

  // ===== 상태 관리 =====
  const [events] = useState<Event[]>(MOCK_EVENTS);
  const [searchValue, setSearchValue] = useState('');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const [sortOption, setSortOption] = useState<SortOption>('latest');
  const [activeTab, setActiveTab] = useState<EventTab>('ongoing');

  // 날짜 범위
  const [startDate, setStartDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [endDate, setEndDate] = useState(format(new Date(), 'yyyy-MM-dd'));

  // ===== 오늘 날짜 기준 진행중/종료 판별 =====
  const today = format(new Date(), 'yyyy-MM-dd');

  // ===== 탭별 이벤트 개수 계산 =====
  const eventCounts = useMemo(() => {
    const ongoing = events.filter((item) => item.endDate >= today).length;
    const ended = events.filter((item) => item.endDate < today).length;
    return { ongoing, ended };
  }, [events, today]);

  // ===== 탭 옵션 (테이블 내부 TabChip 스타일) =====
  const tabs: TabOption[] = [
    { value: 'ongoing', label: '진행중인 이벤트', count: eventCounts.ongoing, color: 'blue' },
    { value: 'ended', label: '종료된 이벤트', count: eventCounts.ended, color: 'gray' },
  ];

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

    // 탭 필터 (진행중/종료)
    if (activeTab === 'ongoing') {
      result = result.filter((item) => item.endDate >= today);
    } else {
      result = result.filter((item) => item.endDate < today);
    }

    // 날짜 필터 (이벤트 시작일/종료일 범위로 필터)
    if (startDate && endDate) {
      result = result.filter((item) => {
        // 이벤트 기간이 선택한 기간과 겹치는지 확인
        return item.startDate <= endDate && item.endDate >= startDate;
      });
    }

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

    // 정렬
    switch (sortOption) {
      case 'latest':
        result.sort((a, b) => b.startDate.localeCompare(a.startDate));
        break;
      case 'oldest':
        result.sort((a, b) => a.startDate.localeCompare(b.startDate));
        break;
      case 'views':
        result.sort((a, b) => b.viewCount - a.viewCount);
        break;
    }

    return result;
  }, [events, searchValue, startDate, endDate, sortOption, activeTab, today]);

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

  const handleTabChange = useCallback((value: string) => {
    setActiveTab(value as EventTab);
    setCurrentPage(1); // 탭 변경 시 첫 페이지로
    setSelectedItems(new Set()); // 선택 초기화
  }, []);

  // ===== 테이블 컬럼 =====
  const tableColumns: TableColumn[] = [
    { key: 'no', label: 'No.', className: 'w-[60px] text-center' },
    { key: 'title', label: '제목', className: 'min-w-[200px]' },
    { key: 'author', label: '작성자', className: 'w-[100px] text-center' },
    { key: 'period', label: '기간', className: 'w-[200px] text-center' },
    { key: 'viewCount', label: '조회수', className: 'w-[80px] text-center' },
  ];

  // ===== 테이블 행 렌더링 =====
  const renderTableRow = useCallback(
    (item: Event, 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>{item.title}</TableCell>
          <TableCell className="text-center">{item.author}</TableCell>
          <TableCell className="text-center">
            {item.startDate} ~ {item.endDate}
          </TableCell>
          <TableCell className="text-center">{item.viewCount}</TableCell>
        </TableRow>
      );
    },
    [selectedItems, handleRowClick, handleToggleSelection]
  );

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback(
    (
      item: Event,
      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>
                  <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.startDate} ~ {item.endDate}</span>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      );
    },
    [handleRowClick]
  );

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

  return (
    <IntegratedListTemplateV2
      title="이벤트"
      description="이벤트를 확인합니다."
      icon={Calendar}
      headerActions={
        <DateRangeSelector
          startDate={startDate}
          endDate={endDate}
          onStartDateChange={setStartDate}
          onEndDateChange={setEndDate}
        />
      }
      tabs={tabs}
      activeTab={activeTab}
      onTabChange={handleTabChange}
      searchValue={searchValue}
      onSearchChange={setSearchValue}
      searchPlaceholder="제목, 작성자로 검색..."
      tableHeaderActions={
        <div className="flex items-center gap-2">
          <span className="text-sm text-muted-foreground">
            총 {filteredData.length}건
          </span>
          <Select value={sortOption} onValueChange={(v) => setSortOption(v as SortOption)}>
            <SelectTrigger className="w-[120px]">
              <SelectValue placeholder="정렬" />
            </SelectTrigger>
            <SelectContent>
              {SORT_OPTIONS.map((option) => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      }
      tableColumns={tableColumns}
      data={paginatedData}
      allData={filteredData}
      selectedItems={selectedItems}
      onToggleSelection={handleToggleSelection}
      onToggleSelectAll={handleToggleSelectAll}
      getItemId={(item) => item.id}
      renderTableRow={renderTableRow}
      renderMobileCard={renderMobileCard}
      pagination={pagination}
    />
  );
}

export default EventList;