'use client';

import { useMemo } from 'react';
import { CreditCard, Edit, Trash2, Plus } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import {
  UniversalListPage,
  type UniversalListConfig,
  type SelectionHandlers,
  type RowClickHandlers,
} from '@/components/templates/UniversalListPage';
import type { Card } from './types';
import {
  CARD_STATUS_LABELS,
  CARD_STATUS_COLORS,
  getCardCompanyLabel,
} from './types';
import { getCards, deleteCard, deleteCards } from './actions';

// 카드번호는 이미 마스킹되어 있음 (****-****-****-1234)
const maskCardNumber = (cardNumber: string): string => {
  return cardNumber;
};

interface CardManagementUnifiedProps {
  initialData?: Card[];
}

export function CardManagementUnified({ initialData }: CardManagementUnifiedProps) {
  // UniversalListPage Config 정의
  const config: UniversalListConfig<Card> = useMemo(() => ({
    // ===== 페이지 기본 정보 =====
    title: '카드관리',
    description: '카드 목록을 관리합니다',
    icon: CreditCard,
    basePath: '/hr/card-management',

    // ===== ID 추출 =====
    idField: 'id',

    // ===== API 액션 =====
    actions: {
      getList: async () => {
        const result = await getCards({ per_page: 100 });
        return {
          success: result.success,
          data: result.data,
          totalCount: result.data?.length || 0,
          error: result.error,
        };
      },
      deleteItem: async (id: string) => {
        return await deleteCard(id);
      },
      deleteBulk: async (ids: string[]) => {
        return await deleteCards(ids);
      },
    },

    // ===== 테이블 컬럼 =====
    columns: [
      { key: 'rowNumber', label: '번호', className: 'w-[60px] text-center' },
      { key: 'cardCompany', label: '카드사', className: 'min-w-[100px]' },
      { key: 'cardNumber', label: '카드번호', className: 'min-w-[160px]' },
      { key: 'cardName', label: '카드명', className: 'min-w-[120px]' },
      { key: 'status', label: '상태', className: 'min-w-[80px]' },
      { key: 'department', label: '부서', className: 'min-w-[100px]' },
      { key: 'userName', label: '사용자', className: 'min-w-[100px]' },
      { key: 'position', label: '직책', className: 'min-w-[100px]' },
      { key: 'actions', label: '작업', className: 'w-[100px] text-right' },
    ],

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

    // 탭 필터 함수
    tabFilter: (item: Card, activeTab: string) => {
      if (activeTab === 'all') return true;
      return item.status === activeTab;
    },

    // 검색 필터 함수
    searchFilter: (item: Card, searchValue: string) => {
      const search = searchValue.toLowerCase();
      return (
        item.cardName.toLowerCase().includes(search) ||
        item.cardNumber.includes(search) ||
        getCardCompanyLabel(item.cardCompany).toLowerCase().includes(search) ||
        (item.user?.employeeName.toLowerCase().includes(search) || false)
      );
    },

    // ===== 탭 설정 (데이터 기반으로 count 업데이트) =====
    tabs: [
      { value: 'all', label: '전체', count: 0, color: 'gray' },
      { value: 'active', label: '사용', count: 0, color: 'green' },
      { value: 'suspended', label: '정지', count: 0, color: 'red' },
    ],

    // ===== 검색 설정 =====
    searchPlaceholder: '카드명, 카드번호, 카드사, 사용자 검색...',

    // ===== 상세 보기 모드 =====
    detailMode: 'page',

    // ===== 헤더 액션 =====
    headerActions: ({ onCreate }) => (
      <Button className="ml-auto" onClick={onCreate}>
        <Plus className="w-4 h-4 mr-2" />
        카드 등록
      </Button>
    ),

    // ===== 삭제 확인 메시지 =====
    deleteConfirmMessage: {
      title: '카드 삭제',
      description: '삭제된 카드 정보는 복구할 수 없습니다.',
    },

    // ===== 테이블 행 렌더링 =====
    renderTableRow: (
      item: Card,
      index: number,
      globalIndex: number,
      handlers: SelectionHandlers & RowClickHandlers<Card>
    ) => {
      const { isSelected, onToggle, onRowClick, onEdit, onDelete } = handlers;

      return (
        <TableRow
          key={item.id}
          className="hover:bg-muted/50 cursor-pointer"
          onClick={() => onRowClick(item)}
        >
          <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
            <Checkbox
              checked={isSelected}
              onCheckedChange={onToggle}
            />
          </TableCell>
          <TableCell className="text-muted-foreground text-center">
            {globalIndex}
          </TableCell>
          <TableCell>{getCardCompanyLabel(item.cardCompany)}</TableCell>
          <TableCell className="font-mono">{maskCardNumber(item.cardNumber)}</TableCell>
          <TableCell>{item.cardName}</TableCell>
          <TableCell>
            <Badge className={CARD_STATUS_COLORS[item.status]}>
              {CARD_STATUS_LABELS[item.status]}
            </Badge>
          </TableCell>
          <TableCell>{item.user?.departmentName || '-'}</TableCell>
          <TableCell>{item.user?.employeeName || '-'}</TableCell>
          <TableCell>{item.user?.positionName || '-'}</TableCell>
          <TableCell className="text-right" onClick={(e) => e.stopPropagation()}>
            {isSelected && (
              <div className="flex items-center justify-end gap-1">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => onEdit?.(item)}
                  title="수정"
                >
                  <Edit className="w-4 h-4" />
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => onDelete?.(item)}
                  title="삭제"
                >
                  <Trash2 className="w-4 h-4 text-red-500" />
                </Button>
              </div>
            )}
          </TableCell>
        </TableRow>
      );
    },

    // ===== 모바일 카드 렌더링 =====
    renderMobileCard: (
      item: Card,
      index: number,
      globalIndex: number,
      handlers: SelectionHandlers & RowClickHandlers<Card>
    ) => {
      const { isSelected, onToggle, onRowClick, onEdit, onDelete } = handlers;

      return (
        <ListMobileCard
          key={item.id}
          id={item.id}
          title={item.cardName}
          headerBadges={
            <div className="flex items-center gap-2 flex-wrap">
              <Badge variant="outline" className="text-xs">
                #{globalIndex}
              </Badge>
              <span className="text-xs text-muted-foreground">
                {getCardCompanyLabel(item.cardCompany)}
              </span>
            </div>
          }
          statusBadge={
            <Badge className={CARD_STATUS_COLORS[item.status]}>
              {CARD_STATUS_LABELS[item.status]}
            </Badge>
          }
          isSelected={isSelected}
          onToggleSelection={onToggle}
          onCardClick={() => onRowClick(item)}
          infoGrid={
            <div className="grid grid-cols-2 gap-x-4 gap-y-3">
              <InfoField label="카드번호" value={maskCardNumber(item.cardNumber)} />
              <InfoField label="유효기간" value={`${item.expiryDate.slice(0, 2)}/${item.expiryDate.slice(2)}`} />
              <InfoField label="부서" value={item.user?.departmentName || '-'} />
              <InfoField label="사용자" value={item.user?.employeeName || '-'} />
              <InfoField label="직책" value={item.user?.positionName || '-'} />
            </div>
          }
          actions={
            isSelected ? (
              <div className="flex gap-2 flex-wrap">
                <Button
                  variant="default"
                  size="default"
                  className="flex-1 min-w-[100px] h-11"
                  onClick={(e) => { e.stopPropagation(); onEdit?.(item); }}
                >
                  <Edit className="h-4 w-4 mr-2" />
                  수정
                </Button>
                <Button
                  variant="outline"
                  size="default"
                  className="flex-1 min-w-[100px] h-11 border-red-200 text-red-600 hover:border-red-300 bg-transparent"
                  onClick={(e) => { e.stopPropagation(); onDelete?.(item); }}
                >
                  <Trash2 className="h-4 w-4 mr-2" />
                  삭제
                </Button>
              </div>
            ) : undefined
          }
        />
      );
    },

    // ===== 추가 옵션 =====
    showCheckbox: true,
    showRowNumber: true,
    itemsPerPage: 20,
  }), []);

  return (
    <UniversalListPage<Card>
      config={config}
      initialData={initialData}
    />
  );
}
