'use client';

/**
 * 거래처 관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - 탭 필터링 (전체/신규)
 * - createButton (거래처 등록)
 * - filterConfig (single: 악성채권, 정렬)
 * - stats 카드 (클릭 없음, 정보 표시용)
 */

import { useState, useMemo, useCallback, useEffect } from 'react';
import { Building2, AlertTriangle, 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 { Badge } from '@/components/ui/badge';
import { MobileCard } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
  type StatCard,
} from '@/components/templates/UniversalListPage';
import type { Partner, PartnerStats } from './types';
import { getPartnerList, deletePartner, deletePartners, getPartnerStats } from './actions';

// 테이블 컬럼 정의
const tableColumns = [
  { key: 'no', label: '번호', className: 'w-[60px] text-center' },
  { key: 'partnerCode', label: '거래처번호', className: 'w-[100px]', copyable: true },
  { key: 'category', label: '구분', className: 'w-[80px] text-center', copyable: true },
  { key: 'partnerName', label: '거래처명', className: 'min-w-[150px]', copyable: true },
  { key: 'representative', label: '대표자', className: 'w-[100px]', copyable: true },
  { key: 'manager', label: '담당자', className: 'w-[100px]', copyable: true },
  { key: 'phone', label: '전화번호', className: 'w-[130px]', copyable: true },
  { key: 'paymentDay', label: '매출 결제일', className: 'w-[100px] text-center', copyable: true },
  { key: 'isBadDebt', label: '악성채권', className: 'w-[90px] text-center' },
  { key: 'actions', label: '작업', className: 'w-[100px] text-center' },
];

interface PartnerListClientProps {
  initialData?: Partner[];
  initialStats?: PartnerStats;
}

export default function PartnerListClient({ initialData = [], initialStats }: PartnerListClientProps) {
  // ===== 공통 핸들러 Hook =====
  const { handleRowClick, handleEdit, router } = useListHandlers<Partner>(
    'construction/project/bidding/partners'
  );

  // ===== 외부 상태 =====
  const [stats, setStats] = useState<PartnerStats>(
    initialStats ?? { total: 0, unregistered: 0, badDebt: 0, normal: 0 }
  );

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

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

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Partner> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '거래처 관리',
      description: '거래처 정보를 관리합니다',
      icon: Building2,
      basePath: '/construction/project/bidding/partners',

      // ID 추출
      idField: 'id',

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

      // 테이블 컬럼
      columns: tableColumns,

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

      // 탭 설정
      tabs: [
        { value: 'all', label: '전체', count: stats.total },
        { value: 'new', label: '신규', count: stats.unregistered },
      ],
      defaultTab: 'all',

      // 탭 필터
      tabFilter: (item, activeTab) => {
        if (activeTab === 'new') {
          const sevenDaysAgo = new Date();
          sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
          return new Date(item.createdAt) >= sevenDaysAgo;
        }
        return true;
      },

      // 검색 필터
      searchPlaceholder: '거래처명, 거래처번호, 대표자 검색',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.partnerCode.toLowerCase().includes(search) ||
          item.partnerName.toLowerCase().includes(search) ||
          item.representative.toLowerCase().includes(search) ||
          item.manager.toLowerCase().includes(search)
        );
      },

      // 필터 설정
      filterConfig: [
        {
          key: 'badDebt',
          label: '악성채권',
          type: 'single',
          options: [
            { value: 'badDebt', label: '악성채권' },
            { value: 'normal', label: '정상' },
          ],
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: [
            { value: 'latest', label: '최신순' },
            { value: 'oldest', label: '등록순' },
            { value: 'nameAsc', label: '이름 오름차순' },
            { value: 'nameDesc', label: '이름 내림차순' },
          ],
        },
      ],
      initialFilters: {
        badDebt: 'all',
        sortBy: 'latest',
      },
      filterTitle: '거래처 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // 악성채권 필터
          const badDebtFilter = filterValues.badDebt as string;
          if (badDebtFilter === 'badDebt' && !item.isBadDebt) return false;
          if (badDebtFilter === 'normal' && item.isBadDebt) 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 'nameAsc':
            sorted.sort((a, b) => a.partnerName.localeCompare(b.partnerName, 'ko'));
            break;
          case 'nameDesc':
            sorted.sort((a, b) => b.partnerName.localeCompare(a.partnerName, 'ko'));
            break;
        }
        return sorted;
      },

      // 공통 헤더 옵션
      createButton: {
        label: '거래처 등록',
        onClick: handleCreate,
      },

      // Stats 카드 (정보 표시용, 클릭 없음)
      computeStats: (): StatCard[] => [
        {
          label: '전체 거래처',
          value: stats.total,
          icon: Building2,
          iconColor: 'text-blue-500',
        },
        {
          label: '미등록',
          value: stats.unregistered,
          icon: AlertTriangle,
          iconColor: 'text-orange-500',
        },
      ],

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

      // 테이블 행 렌더링
      renderTableRow: (
        item: Partner,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Partner>
      ) => (
        <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 className="font-medium">{item.partnerCode}</TableCell>
          <TableCell className="text-center">
            <Badge variant="secondary">{item.category}</Badge>
          </TableCell>
          <TableCell className="font-medium">{item.partnerName}</TableCell>
          <TableCell>{item.representative}</TableCell>
          <TableCell>{item.manager}</TableCell>
          <TableCell>{item.phone}</TableCell>
          <TableCell className="text-center">{item.paymentDay ? `${item.paymentDay}일` : '-'}</TableCell>
          <TableCell className="text-center">
            {item.isBadDebt ? (
              <Badge variant="destructive">악성채권</Badge>
            ) : (
              <span className="text-muted-foreground">-</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: Partner,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Partner>
      ) => (
        <MobileCard
          key={item.id}
          title={item.partnerName}
          subtitle={item.partnerCode}
          badge={item.isBadDebt ? '악성채권' : undefined}
          badgeVariant={item.isBadDebt ? 'destructive' : 'secondary'}
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(item)}
          details={[
            { label: '구분', value: item.category },
            { label: '대표자', value: item.representative },
            { label: '담당자', value: item.manager },
            { label: '전화번호', value: item.phone },
            { label: '매출 결제일', value: item.paymentDay ? `${item.paymentDay}일` : '-' },
          ]}
        />
      ),
    }),
    [stats, handleRowClick, handleCreate, handleEdit]
  );

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