'use client';

/**
 * 현장관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 클릭 필터링 (activeStatTab)
 * - DateRangeSelector (headerActions → dateRangeSelector config)
 * - filterConfig (multi: 거래처 / single: 상태, 정렬)
 * - 삭제 기능 (deleteConfirmMessage로 AlertDialog 대체)
 */

import { useState, useMemo, useEffect } from 'react';
import { Building2, HardHat, AlertCircle, Pencil } 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 { Site, SiteStats } from './types';
import {
  SITE_STATUS_OPTIONS,
  SITE_SORT_OPTIONS,
  SITE_STATUS_STYLES,
  SITE_STATUS_LABELS,
} from './types';
import { getSiteList, getSiteStats, deleteSite, deleteSites } from './actions';
import { useDateRange } from '@/hooks';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'siteCode', label: '현장번호', className: 'w-[120px]', copyable: true },
  { key: 'partnerName', label: '거래처', className: 'w-[100px]', copyable: true },
  { key: 'siteName', label: '현장명', className: 'min-w-[150px]', copyable: true },
  { key: 'address', label: '위치', className: 'min-w-[200px]', copyable: true },
  { key: 'status', label: '상태', className: 'w-[80px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[80px] text-center' },
];

// 목업 거래처 목록
const MOCK_PARTNERS = [
  { value: '1', label: '회사명A' },
  { value: '2', label: '회사명B' },
  { value: '3', label: '회사명C' },
];

interface SiteManagementListClientProps {
  initialData?: Site[];
  initialStats?: SiteStats;
}

export default function SiteManagementListClient({
  initialData = [],
  initialStats,
}: SiteManagementListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit } = useListHandlers<Site>('construction/order/site-management');

  // ===== 외부 상태 (UniversalListPage 외부에서 관리) =====
  const [activeStatTab, setActiveStatTab] = useState<'all' | 'construction' | 'unregistered'>('all');
  const { startDate, endDate, setStartDate, setEndDate } = useDateRange('today');
  const [stats, setStats] = useState<SiteStats | null>(initialStats || null);
  const [searchQuery, setSearchQuery] = useState('');

  // Stats 로드
  useEffect(() => {
    if (!initialStats) {
      getSiteStats().then((result) => {
        if (result.success && result.data) {
          setStats(result.data);
        }
      });
    }
  }, [initialStats]);

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Site> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '현장관리',
      description: '현장을 관리합니다',
      icon: Building2,
      basePath: '/construction/order/site-management',

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          const result = await getSiteList({
            size: 1000,
            startDate: startDate || undefined,
            endDate: endDate || undefined,
          });
          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 deleteSite(id);
          return { success: result.success, error: result.error };
        },
        deleteBulk: async (ids: string[]) => {
          const result = await deleteSites(ids);
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

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

      // 검색 필터
      searchPlaceholder: '현장번호, 거래처, 현장명, 위치 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.siteName.toLowerCase().includes(search) ||
          item.siteCode.toLowerCase().includes(search) ||
          item.partnerName.toLowerCase().includes(search) ||
          item.address.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'partner',
          label: '거래처',
          type: 'multi',
          options: MOCK_PARTNERS,
        },
        {
          key: 'status',
          label: '상태',
          type: 'single',
          options: SITE_STATUS_OPTIONS.filter((o) => o.value !== 'all'),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: SITE_SORT_OPTIONS,
        },
      ],
      initialFilters: {
        partner: [],
        status: 'all',
        sortBy: 'latest',
      },
      filterTitle: '현장 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // Stats 탭 필터
          if (activeStatTab === 'construction' && item.status !== 'active') return false;
          if (activeStatTab === 'unregistered' && item.status !== 'unregistered') 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.status !== statusFilter) return false;

          return true;
        });
      },

      // 커스텀 정렬 함수
      customSortFn: (items, filterValues) => {
        const sorted = [...items];
        const sortBy = (filterValues.sortBy as string) || 'latest';

        switch (sortBy) {
          case 'latest':
            sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
            break;
          case 'oldest':
            sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
            break;
          case 'partnerNameAsc':
            sorted.sort((a, b) => a.partnerName.localeCompare(b.partnerName, 'ko'));
            break;
          case 'partnerNameDesc':
            sorted.sort((a, b) => b.partnerName.localeCompare(a.partnerName, 'ko'));
            break;
          case 'siteNameAsc':
            sorted.sort((a, b) => a.siteName.localeCompare(b.siteName, 'ko'));
            break;
          case 'siteNameDesc':
            sorted.sort((a, b) => b.siteName.localeCompare(a.siteName, 'ko'));
            break;
        }
        return sorted;
      },

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

      // 공통 헤더 옵션
      dateRangeSelector: {
        enabled: true,
        startDate,
        endDate,
        onStartDateChange: setStartDate,
        onEndDateChange: setEndDate,
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 현장',
          value: stats?.total ?? 0,
          icon: Building2,
          iconColor: 'text-blue-600',
          onClick: () => setActiveStatTab('all'),
          isActive: activeStatTab === 'all',
        },
        {
          label: '시공 현장',
          value: stats?.construction ?? 0,
          icon: HardHat,
          iconColor: 'text-green-600',
          onClick: () => setActiveStatTab('construction'),
          isActive: activeStatTab === 'construction',
        },
        {
          label: '미등록 현장',
          value: stats?.unregistered ?? 0,
          icon: AlertCircle,
          iconColor: 'text-red-500',
          onClick: () => setActiveStatTab('unregistered'),
          isActive: activeStatTab === 'unregistered',
        },
      ],

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

      // 테이블 행 렌더링
      renderTableRow: (
        item: Site,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Site>
      ) => (
        <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.siteCode}</TableCell>
          <TableCell>{item.partnerName}</TableCell>
          <TableCell>{item.siteName}</TableCell>
          <TableCell>{item.address || '-'}</TableCell>
          <TableCell className="text-center">
            <span className={SITE_STATUS_STYLES[item.status]}>
              {SITE_STATUS_LABELS[item.status]}
            </span>
          </TableCell>
          <TableCell className="text-center">
            {handlers.isSelected && (
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(item);
                }}
              >
                <Pencil className="h-4 w-4" />
              </Button>
            )}
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        item: Site,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Site>
      ) => (
        <MobileCard
          key={item.id}
          title={item.siteName}
          subtitle={item.siteCode}
          badge={SITE_STATUS_LABELS[item.status]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '거래처', value: item.partnerName },
            { label: '위치', value: item.address || '-' },
          ]}
        />
      ),
    }),
    [startDate, endDate, activeStatTab, stats, handleRowClick, handleEdit, searchQuery]
  );

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