'use client';

/**
 * 현장설명회 관리 - UniversalListPage 마이그레이션
 *
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector (공통 헤더)
 * - filterConfig (multi: 거래처, 참석자 / single: 구분, 상태, 정렬)
 */

import { useState, useMemo, useCallback } from 'react';
import { Calendar, CalendarDays, CalendarCheck, CalendarClock, Pencil, Trash2 } from 'lucide-react';
import { useListHandlers } from '@/hooks/useListHandlers';
import { Button } from '@/components/ui/button';
import { TableCell, TableRow } from '@/components/ui/table';
import { Checkbox } from '@/components/ui/checkbox';
import { MobileCard } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import type { SiteBriefing } from './types';
import { getSiteBriefingList, deleteSiteBriefing, deleteSiteBriefings } from './actions';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'briefingCode', label: '현설번호', className: 'w-[100px]', copyable: true },
  { key: 'partnerName', label: '거래처', className: 'w-[120px]', copyable: true },
  { key: 'projectName', label: '현장명', className: 'min-w-[150px]', copyable: true },
  { key: 'briefingDate', label: '현장설명회일', className: 'w-[120px] text-center', copyable: true },
  { key: 'briefingType', label: '구분', className: 'w-[80px] text-center', copyable: true },
  { key: 'attendee', label: '참석자', className: 'w-[100px] text-center', copyable: true },
  { key: 'bidDate', label: '입찰일', className: 'w-[120px] text-center', copyable: true },
  { key: 'status', label: '상태', className: 'w-[100px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[80px] text-center' },
];

// 상태별 스타일
const STATUS_STYLES: Record<string, string> = {
  scheduled: 'text-red-500 font-medium',
  attended: 'text-gray-900',
  absent: 'text-gray-500',
};

const STATUS_LABELS: Record<string, string> = {
  scheduled: '참석예정',
  attended: '참석완료',
  absent: '불참',
};

// 상태 옵션
const STATUS_OPTIONS = [
  { value: 'scheduled', label: '참석예정' },
  { value: 'attended', label: '참석완료' },
  { value: 'absent', label: '불참' },
];

// 구분 옵션
const TYPE_OPTIONS = [
  { value: 'online', label: '온라인' },
  { value: 'offline', label: '오프라인' },
];

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

// 목업 데이터
const MOCK_PARTNERS = [
  { value: '1', label: '대한건설' },
  { value: '2', label: '삼성시공' },
  { value: '3', label: 'LG건설' },
];

const MOCK_ATTENDEES = [
  { value: 'hong', label: '홍길동' },
  { value: 'kim', label: '김철수' },
  { value: 'lee', label: '이영희' },
];

interface SiteBriefingListClientProps {
  initialData?: SiteBriefing[];
}

export default function SiteBriefingListClient({ initialData = [] }: SiteBriefingListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit, router } = useListHandlers<SiteBriefing>(
    'construction/project/bidding/site-briefings'
  );

  // Stats 탭 상태
  const [activeStatTab, setActiveStatTab] = useState<'all' | 'scheduled' | 'attended'>('all');
  // 날짜 범위
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');
  const [searchQuery, setSearchQuery] = useState('');

  // ===== 추가 핸들러 =====
  const handleCreate = useCallback(() => {
    router.push('/ko/construction/project/bidding/site-briefings?mode=new');
  }, [router]);

  // ===== UniversalListPage Config (최소 버전) =====
  const config: UniversalListConfig<SiteBriefing> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '현장설명회 관리',
      description: '현장설명회를 등록하고 관리합니다',
      icon: Calendar,
      basePath: '/construction/project/bidding/site-briefings',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getSiteBriefingList({ size: 100 });
          if (result.success && result.data) {
            return {
              success: true,
              data: result.data.items,
              totalCount: result.data.total,
            };
          }
          return { success: false, error: result.error };
        },
        deleteItem: async (id: string) => {
          const result = await deleteSiteBriefing(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await deleteSiteBriefings(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 삭제 확인 메시지
      deleteConfirmMessage: {
        title: '현장설명회 삭제',
        description: '선택한 현장설명회를 삭제하시겠습니까?',
      },

      // 테이블 컬럼
      columns: tableColumns,

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

      // 검색
      searchPlaceholder: '현장번호, 거래처, 현장명 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          (item.briefingCode || '').toLowerCase().includes(search) ||
          (item.partnerName || '').toLowerCase().includes(search) ||
          (item.title || '').toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        { key: 'partner', label: '거래처', type: 'multi', options: MOCK_PARTNERS },
        { key: 'type', label: '구분', type: 'single', options: TYPE_OPTIONS },
        { key: 'attendee', label: '참석자', type: 'multi', options: MOCK_ATTENDEES },
        { key: 'status', label: '상태', type: 'single', options: STATUS_OPTIONS },
        { key: 'sortBy', label: '정렬', type: 'single', options: SORT_OPTIONS },
      ],
      initialFilters: {
        partner: [],
        type: 'all',
        attendee: [],
        status: 'all',
        sortBy: 'latest',
      },
      filterTitle: '현장설명회 필터',

      // 커스텀 필터 함수 (activeStatTab 필터링 포함)
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // Stats 탭 필터
          if (activeStatTab === 'scheduled' && item.attendanceStatus !== 'scheduled') return false;
          if (activeStatTab === 'attended' && item.attendanceStatus !== 'attended') return false;

          // 거래처 필터 (다중선택)
          const partnerFilters = filterValues.partner as string[];
          if (partnerFilters?.length > 0 && !partnerFilters.includes(item.partnerId)) return false;

          // 상태 필터
          const statusFilter = filterValues.status as string;
          if (statusFilter && statusFilter !== 'all' && item.attendanceStatus !== statusFilter) return false;

          return true;
        });
      },

      // 커스텀 정렬 함수
      customSortFn: (items, filterValues) => {
        const sorted = [...items];
        const sortBy = (filterValues.sortBy as string) || 'latest';
        if (sortBy === 'latest') {
          sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
        } else if (sortBy === 'oldest') {
          sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
        }
        return sorted;
      },

      // 검색창 (공통 컴포넌트에서 자동 생성)
      hideSearch: true,
      searchValue: searchQuery,
      onSearchChange: setSearchQuery,

      // 날짜 범위 선택기
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // 등록 버튼
      createButton: {
        label: '현장설명회 등록',
        onClick: handleCreate,
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 현장설명회',
          value: 0,
          icon: CalendarDays,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('all'),
          isActive: activeStatTab === 'all',
        },
        {
          label: '참석예정',
          value: 0,
          icon: CalendarClock,
          iconColor: 'text-orange-500',
          onClick: () => setActiveStatTab('scheduled'),
          isActive: activeStatTab === 'scheduled',
        },
        {
          label: '참석완료',
          value: 0,
          icon: CalendarCheck,
          iconColor: 'text-green-600',
          onClick: () => setActiveStatTab('attended'),
          isActive: activeStatTab === 'attended',
        },
      ],

      // 테이블 행 렌더링 (최소)
      renderTableRow: (
        item: SiteBriefing,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<SiteBriefing>
      ) => {
        const displayStatus = item.attendanceStatus || 'scheduled';

        return (
          <TableRow
            key={item.id}
            className="cursor-pointer hover:bg-muted/50"
            onClick={() => handleRowClick(item)}
          >
            <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
              <Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
            </TableCell>
            <TableCell className="text-center text-muted-foreground">{globalIndex}</TableCell>
            <TableCell>{item.briefingCode}</TableCell>
            <TableCell>{item.partnerName}</TableCell>
            <TableCell>{item.title}</TableCell>
            <TableCell className="text-center">{item.briefingDate}</TableCell>
            <TableCell className="text-center">온라인</TableCell>
            <TableCell className="text-center">홍길동</TableCell>
            <TableCell className="text-center">{item.bidDate || '-'}</TableCell>
            <TableCell className="text-center">
              <span className={STATUS_STYLES[displayStatus]}>{STATUS_LABELS[displayStatus]}</span>
            </TableCell>
            <TableCell className="text-center">
              {handlers.isSelected && (
                <div className="flex items-center justify-center gap-1">
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleEdit(item);
                    }}
                  >
                    <Pencil className="h-4 w-4" />
                  </Button>
                  <Button
                    variant="ghost"
                    size="icon"
                    className="h-8 w-8 text-destructive hover:text-destructive"
                    onClick={(e) => {
                      e.stopPropagation();
                      handlers.onDelete?.(item);
                    }}
                  >
                    <Trash2 className="h-4 w-4" />
                  </Button>
                </div>
              )}
            </TableCell>
          </TableRow>
        );
      },

      // 모바일 카드 렌더링 (최소)
      renderMobileCard: (
        item: SiteBriefing,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<SiteBriefing>
      ) => {
        const displayStatus = item.attendanceStatus || 'scheduled';

        return (
          <MobileCard
            key={item.id}
            title={item.title}
            subtitle={item.briefingCode}
            badge={STATUS_LABELS[displayStatus]}
            badgeVariant="secondary"
            isSelected={handlers.isSelected}
            onToggle={handlers.onToggle}
            onClick={() => handleRowClick(item)}
            details={[
              { label: '거래처', value: item.partnerName },
              { label: '현장설명회일', value: item.briefingDate },
              { label: '구분', value: '온라인' },
              { label: '참석자', value: '홍길동' },
              { label: '입찰일', value: item.bidDate || '-' },
            ]}
          />
        );
      },
    }),
    [handleRowClick, handleEdit, handleCreate, activeStatTab, startDate, endDate, searchQuery]
  );

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