'use client';

/**
 * 거래처관리 - UniversalListPage 마이그레이션
 *
 * 기존 IntegratedListTemplateV2 → UniversalListPage config 기반으로 변환
 * - 클라이언트 사이드 필터링 (검색, 필터, 정렬)
 * - Stats 카드 (단순 표시, 클릭 없음)
 * - filterConfig (single 5개: 구분, 신용등급, 거래등급, 악성채권, 정렬)
 * - 삭제 기능 (deleteConfirmMessage)
 */

import { useState, useMemo, useCallback } from 'react';
import { invalidateDashboard } from '@/lib/dashboard-invalidation';
import { useRouter } from 'next/navigation';
import { format, startOfMonth, endOfMonth } from 'date-fns';
import { formatNumber } from '@/lib/utils/amount';
import {
  Building2,
} from 'lucide-react';
import { TableRow, TableCell } 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 {
  Vendor,
  SortOption,
} from './types';
export type { Vendor } from './types';
import {
  VENDOR_CATEGORY_OPTIONS,
  VENDOR_CATEGORY_LABELS,
  VENDOR_CATEGORY_COLORS,
  CREDIT_RATING_OPTIONS,
  CREDIT_RATING_COLORS,
  TRANSACTION_GRADE_OPTIONS,
  TRANSACTION_GRADE_LABELS,
  TRANSACTION_GRADE_COLORS,
  BAD_DEBT_STATUS_OPTIONS,
  BAD_DEBT_STATUS_LABELS,
  BAD_DEBT_STATUS_COLORS,
  VENDOR_STATUS_LABELS,
  VENDOR_STATUS_COLORS,
  SORT_OPTIONS,
} from './types';
import { deleteClient } from './actions';
import { toast } from 'sonner';

// ===== 테이블 컬럼 정의 =====
const tableColumns = [
  { key: 'no', label: '번호', className: 'text-center w-[60px]' },
  { key: 'category', label: '구분', className: 'text-center w-[100px]', sortable: true, copyable: true },
  { key: 'vendorName', label: '거래처명', sortable: true, copyable: true },
  { key: 'purchasePaymentDay', label: '매입 결제일', className: 'text-center w-[100px]', sortable: true, copyable: true },
  { key: 'salesPaymentDay', label: '매출 결제일', className: 'text-center w-[100px]', sortable: true, copyable: true },
  { key: 'creditRating', label: '신용등급', className: 'text-center w-[90px]', sortable: true },
  { key: 'transactionGrade', label: '거래등급', className: 'text-center w-[100px]', sortable: true },
  { key: 'outstandingAmount', label: '미수금', className: 'text-right w-[120px]', sortable: true, copyable: true },
  { key: 'badDebtStatus', label: '악성채권', className: 'text-center w-[90px]', sortable: true },
  { key: 'status', label: '상태', className: 'text-center w-[80px]', sortable: true },
];

// ===== 컴포넌트 Props =====
interface VendorManagementProps {
  initialData: Vendor[];
  initialTotal: number;
}

export function VendorManagement({ initialData, initialTotal: _initialTotal }: VendorManagementProps) {
  const router = useRouter();

  // ===== 날짜 범위 상태 (빈 값 = 전체 조회) =====
  const [startDate, setStartDate] = useState('');
  const [endDate, setEndDate] = useState('');

  // ===== 외부 상태 (Stats 계산용) =====
  const [vendorData, setVendorData] = useState<Vendor[]>(initialData);

  // ===== Stats 계산 =====
  const stats = useMemo(() => {
    const totalCount = vendorData.length;
    const salesCount = vendorData.filter(d => d.category === 'sales' || d.category === 'both').length;
    const purchaseCount = vendorData.filter(d => d.category === 'purchase' || d.category === 'both').length;
    return { totalCount, salesCount, purchaseCount };
  }, [vendorData]);

  // ===== 핸들러 =====
  const handleRowClick = useCallback(
    (vendor: Vendor) => {
      router.push(`/ko/accounting/vendors/${vendor.id}?mode=view`);
    },
    [router]
  );

  // ===== UniversalListPage Config =====
  const config: UniversalListConfig<Vendor> = useMemo(
    () => ({
      // 페이지 기본 정보
      title: '거래처관리',
      description: '거래처 정보를 등록하고 관리합니다',
      icon: Building2,
      basePath: '/accounting/vendors',

      // 등록 버튼
      createButton: {
        label: '거래처 등록',
        onClick: () => router.push('/ko/accounting/vendors?mode=new'),
      },

      // ID 추출
      idField: 'id',

      // API 액션
      actions: {
        getList: async () => {
          // 이미 initialData로 로드됨, 클라이언트 사이드 필터링
          return {
            success: true,
            data: initialData,
            totalCount: initialData.length,
          };
        },
        deleteItem: async (id: string) => {
          const result = await deleteClient(id);
          if (result.success) {
            invalidateDashboard('client');
            toast.success('거래처가 삭제되었습니다.');
          }
          return { success: result.success, error: result.error };
        },
      },

      // 테이블 컬럼
      columns: tableColumns,

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

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

      // 데이터 변경 콜백 (Stats 계산용)
      onDataChange: (data) => setVendorData(data),

      // 검색 필터
      searchPlaceholder: '거래처명, 거래처코드, 사업자번호 검색...',
      searchFilter: (item, searchValue) => {
        const search = searchValue.toLowerCase();
        return (
          item.vendorName.toLowerCase().includes(search) ||
          item.vendorCode.toLowerCase().includes(search) ||
          item.businessNumber.toLowerCase().includes(search)
        );
      },

      // 필터 설정 (5개 single 필터)
      filterConfig: [
        {
          key: 'category',
          label: '구분',
          type: 'single',
          options: VENDOR_CATEGORY_OPTIONS.filter(o => o.value !== 'all').map(o => ({
            value: o.value,
            label: o.label,
          })),
        },
        {
          key: 'creditRating',
          label: '신용등급',
          type: 'single',
          options: CREDIT_RATING_OPTIONS.filter(o => o.value !== 'all').map(o => ({
            value: o.value,
            label: o.label,
          })),
        },
        {
          key: 'transactionGrade',
          label: '거래등급',
          type: 'single',
          options: TRANSACTION_GRADE_OPTIONS.filter(o => o.value !== 'all').map(o => ({
            value: o.value,
            label: o.label,
          })),
        },
        {
          key: 'badDebt',
          label: '악성채권',
          type: 'single',
          options: BAD_DEBT_STATUS_OPTIONS.filter(o => o.value !== 'all').map(o => ({
            value: o.value,
            label: o.label,
          })),
        },
        {
          key: 'sortBy',
          label: '정렬',
          type: 'single',
          options: SORT_OPTIONS.map(o => ({
            value: o.value,
            label: o.label,
          })),
        },
      ],
      initialFilters: {
        category: 'all',
        creditRating: 'all',
        transactionGrade: 'all',
        badDebt: 'all',
        sortBy: 'latest',
      },
      filterTitle: '거래처 필터',

      // 커스텀 필터 함수
      customFilterFn: (items, filterValues) => {
        if (!items || items.length === 0) return items;
        return items.filter((item) => {
          // 구분 필터
          const categoryFilter = filterValues.category as string;
          if (categoryFilter && categoryFilter !== 'all' && item.category !== categoryFilter) {
            return false;
          }

          // 신용등급 필터
          const creditRatingFilter = filterValues.creditRating as string;
          if (creditRatingFilter && creditRatingFilter !== 'all' && item.creditRating !== creditRatingFilter) {
            return false;
          }

          // 거래등급 필터
          const transactionGradeFilter = filterValues.transactionGrade as string;
          if (transactionGradeFilter && transactionGradeFilter !== 'all' && item.transactionGrade !== transactionGradeFilter) {
            return false;
          }

          // 악성채권 필터
          const badDebtFilter = filterValues.badDebt as string;
          if (badDebtFilter && badDebtFilter !== 'all' && item.badDebtStatus !== badDebtFilter) {
            return false;
          }

          return true;
        });
      },

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

        switch (sortBy) {
          case 'oldest':
            sorted.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
            break;
          case 'nameAsc':
            sorted.sort((a, b) => a.vendorName.localeCompare(b.vendorName));
            break;
          case 'nameDesc':
            sorted.sort((a, b) => b.vendorName.localeCompare(a.vendorName));
            break;
          case 'outstandingHigh':
            sorted.sort((a, b) => b.outstandingAmount - a.outstandingAmount);
            break;
          case 'outstandingLow':
            sorted.sort((a, b) => a.outstandingAmount - b.outstandingAmount);
            break;
          default: // latest
            sorted.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
            break;
        }
        return sorted;
      },

      // Stats 카드
      computeStats: (): StatCard[] => [
        {
          label: '전체 거래처',
          value: `${stats.totalCount}개`,
          icon: Building2,
          iconColor: 'text-blue-500',
        },
        {
          label: '매출 거래처',
          value: `${stats.salesCount}개`,
          icon: Building2,
          iconColor: 'text-green-500',
        },
        {
          label: '매입 거래처',
          value: `${stats.purchaseCount}개`,
          icon: Building2,
          iconColor: 'text-orange-500',
        },
      ],

      // 삭제 확인 메시지
      deleteConfirmMessage: {
        title: '거래처 삭제',
        description: '이 거래처를 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.',
      },

      // 테이블 행 렌더링
      renderTableRow: (
        vendor: Vendor,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Vendor>
      ) => (
        <TableRow
          key={vendor.id}
          className="hover:bg-muted/50 cursor-pointer"
          onClick={() => handleRowClick(vendor)}
        >
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <Checkbox checked={handlers.isSelected} onCheckedChange={handlers.onToggle} />
          </TableCell>
          {/* 번호 */}
          <TableCell className="text-center text-sm text-gray-500">{globalIndex}</TableCell>
          {/* 구분 */}
          <TableCell className="text-center">
            <Badge className={VENDOR_CATEGORY_COLORS[vendor.category]}>
              {VENDOR_CATEGORY_LABELS[vendor.category]}
            </Badge>
          </TableCell>
          {/* 거래처명 */}
          <TableCell className="font-medium">{vendor.vendorName}</TableCell>
          {/* 매입 결제일 */}
          <TableCell className="text-center">{vendor.purchasePaymentDay}일</TableCell>
          {/* 매출 결제일 */}
          <TableCell className="text-center">{vendor.salesPaymentDay}일</TableCell>
          {/* 신용등급 */}
          <TableCell className="text-center">
            <Badge className={CREDIT_RATING_COLORS[vendor.creditRating]}>
              {vendor.creditRating}
            </Badge>
          </TableCell>
          {/* 거래등급 */}
          <TableCell className="text-center">
            <Badge className={TRANSACTION_GRADE_COLORS[vendor.transactionGrade]}>
              {TRANSACTION_GRADE_LABELS[vendor.transactionGrade]}
            </Badge>
          </TableCell>
          {/* 미수금 */}
          <TableCell className="text-right">
            {vendor.outstandingAmount > 0 ? (
              <span className="text-red-600 font-medium">{formatNumber(vendor.outstandingAmount)}원</span>
            ) : (
              <span className="text-gray-500">-</span>
            )}
          </TableCell>
          {/* 악성채권 */}
          <TableCell className="text-center">
            {vendor.badDebtStatus === 'none' ? (
              <span className="text-gray-400">-</span>
            ) : (
              <Badge className={BAD_DEBT_STATUS_COLORS[vendor.badDebtStatus]}>
                {BAD_DEBT_STATUS_LABELS[vendor.badDebtStatus]}
              </Badge>
            )}
          </TableCell>
          {/* 상태 */}
          <TableCell className="text-center">
            <Badge className={VENDOR_STATUS_COLORS[vendor.isActive ? 'active' : 'inactive']}>
              {VENDOR_STATUS_LABELS[vendor.isActive ? 'active' : 'inactive']}
            </Badge>
          </TableCell>
        </TableRow>
      ),

      // 모바일 카드 렌더링
      renderMobileCard: (
        vendor: Vendor,
        index: number,
        globalIndex: number,
        handlers: SelectionHandlers & RowClickHandlers<Vendor>
      ) => (
        <MobileCard
          key={vendor.id}
          title={vendor.vendorName}
          subtitle={vendor.vendorCode}
          badge={VENDOR_CATEGORY_LABELS[vendor.category]}
          badgeVariant="secondary"
          isSelected={handlers.isSelected}
          onToggle={handlers.onToggle}
          onClick={() => handleRowClick(vendor)}
          details={[
            { label: '거래등급', value: TRANSACTION_GRADE_LABELS[vendor.transactionGrade] },
            {
              label: '미수금',
              value: vendor.outstandingAmount > 0 ? `${formatNumber(vendor.outstandingAmount)}원` : '-',
            },
            { label: '결제일', value: `매입 ${vendor.purchasePaymentDay}일 / 매출 ${vendor.salesPaymentDay}일` },
            { label: '상태', value: VENDOR_STATUS_LABELS[vendor.isActive ? 'active' : 'inactive'] },
          ]}
        />
      ),
    }),
    [initialData, stats, handleRowClick, router, startDate, endDate]
  );

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