'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
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 {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
  IntegratedListTemplateV2,
  type TabOption,
  type TableColumn,
} from '@/components/templates/IntegratedListTemplateV2';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import type { Card, CardStatus } from './types';
import {
  CARD_STATUS_LABELS,
  CARD_STATUS_COLORS,
  getCardCompanyLabel,
} from './types';

// 카드번호 마스킹 (가운데 숨김)
const maskCardNumber = (cardNumber: string): string => {
  const parts = cardNumber.split('-');
  if (parts.length === 4) {
    return `${parts[0]}-****-****-${parts[3]}`;
  }
  return cardNumber;
};

// Mock 데이터
const mockCards: Card[] = [
  {
    id: '1',
    cardCompany: 'shinhan',
    cardNumber: '1234-5678-9012-3456',
    cardName: '법인카드1',
    expiryDate: '0327',
    pinPrefix: '12',
    status: 'active',
    user: {
      id: 'u1',
      departmentId: 'd1',
      departmentName: '부서명',
      employeeId: 'e1',
      employeeName: '부여직원',
      positionId: 'p1',
      positionName: '부서장',
    },
    createdAt: '2024-01-01T00:00:00Z',
    updatedAt: '2024-01-01T00:00:00Z',
  },
  {
    id: '2',
    cardCompany: 'kb',
    cardNumber: '1234-5678-9012-3456',
    cardName: '국민카드',
    expiryDate: '0528',
    pinPrefix: '34',
    status: 'active',
    user: {
      id: 'u2',
      departmentId: 'd2',
      departmentName: '부서명',
      employeeId: 'e2',
      employeeName: '부여직원',
      positionId: 'p2',
      positionName: '팀장',
    },
    createdAt: '2024-02-01T00:00:00Z',
    updatedAt: '2024-02-01T00:00:00Z',
  },
  {
    id: '3',
    cardCompany: 'shinhan',
    cardNumber: '1234-5678-9012-3456',
    cardName: '신한카드',
    expiryDate: '0426',
    pinPrefix: '56',
    status: 'suspended',
    user: {
      id: 'u3',
      departmentId: 'd1',
      departmentName: '부서명',
      employeeId: 'e3',
      employeeName: '부여직원',
      positionId: 'p3',
      positionName: '부서장',
    },
    createdAt: '2024-03-01T00:00:00Z',
    updatedAt: '2024-03-01T00:00:00Z',
  },
];

// 추가 Mock 데이터 생성
const generateMockCards = (): Card[] => {
  const cards: Card[] = [...mockCards];
  const companies: Array<'shinhan' | 'kb' | 'samsung' | 'hyundai' | 'lotte'> = ['shinhan', 'kb', 'samsung', 'hyundai', 'lotte'];
  const departments = ['부서명'];
  const positions = ['팀장', '부서장', '파트장'];

  for (let i = 4; i <= 15; i++) {
    const status: CardStatus = i % 5 === 0 ? 'suspended' : 'active';
    cards.push({
      id: String(i),
      cardCompany: companies[i % companies.length],
      cardNumber: `1234-5678-9012-${String(i).padStart(4, '0')}`,
      cardName: `법인카드${i}`,
      expiryDate: `0${(i % 12) + 1}27`,
      pinPrefix: String(i).padStart(2, '0'),
      status,
      user: {
        id: `u${i}`,
        departmentId: `d${(i % 3) + 1}`,
        departmentName: departments[0],
        employeeId: `e${i}`,
        employeeName: '부여직원',
        positionId: `p${(i % 3) + 1}`,
        positionName: positions[i % positions.length],
      },
      createdAt: '2024-01-01T00:00:00Z',
      updatedAt: '2024-01-01T00:00:00Z',
    });
  }
  return cards;
};

export function CardManagement() {
  const router = useRouter();

  // 카드 데이터 상태
  const [cards, setCards] = useState<Card[]>(generateMockCards);

  // 검색 및 필터 상태
  const [searchValue, setSearchValue] = useState('');
  const [activeTab, setActiveTab] = useState<string>('all');
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 다이얼로그 상태
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [cardToDelete, setCardToDelete] = useState<Card | null>(null);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());

  // 필터링된 데이터
  const filteredCards = useMemo(() => {
    let filtered = cards;

    // 탭 필터 (상태)
    if (activeTab !== 'all') {
      filtered = filtered.filter(c => c.status === activeTab);
    }

    // 검색 필터
    if (searchValue) {
      const search = searchValue.toLowerCase();
      filtered = filtered.filter(c =>
        c.cardName.toLowerCase().includes(search) ||
        c.cardNumber.includes(search) ||
        getCardCompanyLabel(c.cardCompany).toLowerCase().includes(search) ||
        c.user?.employeeName.toLowerCase().includes(search)
      );
    }

    return filtered;
  }, [cards, activeTab, searchValue]);

  // 페이지네이션된 데이터
  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredCards.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredCards, currentPage, itemsPerPage]);

  // 통계 계산
  const stats = useMemo(() => {
    const activeCount = cards.filter(c => c.status === 'active').length;
    const suspendedCount = cards.filter(c => c.status === 'suspended').length;
    return { activeCount, suspendedCount };
  }, [cards]);

  // 탭 옵션
  const tabs: TabOption[] = useMemo(() => [
    { value: 'all', label: '전체', count: cards.length, color: 'gray' },
    { value: 'active', label: '사용', count: stats.activeCount, color: 'green' },
    { value: 'suspended', label: '정지', count: stats.suspendedCount, color: 'red' },
  ], [cards.length, stats]);

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = useMemo(() => [
    { 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' },
  ], []);

  // 체크박스 토글
  const toggleSelection = useCallback((id: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  }, []);

  // 전체 선택/해제
  const toggleSelectAll = useCallback(() => {
    if (selectedItems.size === paginatedData.length && paginatedData.length > 0) {
      setSelectedItems(new Set());
    } else {
      const allIds = new Set(paginatedData.map((item) => item.id));
      setSelectedItems(allIds);
    }
  }, [selectedItems.size, paginatedData]);

  // 일괄 삭제 핸들러
  const handleBulkDelete = useCallback(() => {
    const ids = Array.from(selectedItems);
    setCards(prev => prev.filter(card => !ids.includes(card.id)));
    setSelectedItems(new Set());
  }, [selectedItems]);

  // 핸들러
  const handleAddCard = useCallback(() => {
    router.push('/ko/hr/card-management/new');
  }, [router]);

  const handleDeleteCard = useCallback(() => {
    if (cardToDelete) {
      setCards(prev => prev.filter(card => card.id !== cardToDelete.id));
      setDeleteDialogOpen(false);
      setCardToDelete(null);
    }
  }, [cardToDelete]);

  const handleRowClick = useCallback((row: Card) => {
    router.push(`/ko/hr/card-management/${row.id}`);
  }, [router]);

  const handleEdit = useCallback((id: string) => {
    router.push(`/ko/hr/card-management/${id}/edit`);
  }, [router]);

  const openDeleteDialog = useCallback((card: Card) => {
    setCardToDelete(card);
    setDeleteDialogOpen(true);
  }, []);

  // 테이블 행 렌더링
  const renderTableRow = useCallback((item: Card, index: number, globalIndex: number) => {
    const isSelected = selectedItems.has(item.id);

    return (
      <TableRow
        key={item.id}
        className="hover:bg-muted/50 cursor-pointer"
        onClick={() => handleRowClick(item)}
      >
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <Checkbox
            checked={isSelected}
            onCheckedChange={() => toggleSelection(item.id)}
          />
        </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={() => handleEdit(item.id)}
                title="수정"
              >
                <Edit className="w-4 h-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={() => openDeleteDialog(item)}
                title="삭제"
              >
                <Trash2 className="w-4 h-4 text-red-500" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleRowClick, handleEdit, openDeleteDialog]);

  // 모바일 카드 렌더링
  const renderMobileCard = useCallback((
    item: Card,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        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={() => handleRowClick(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(); handleEdit(item.id); }}
              >
                <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(); openDeleteDialog(item); }}
              >
                <Trash2 className="h-4 w-4 mr-2" />
                삭제
              </Button>
            </div>
          ) : undefined
        }
      />
    );
  }, [handleRowClick, handleEdit, openDeleteDialog]);

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

  // 페이지네이션 설정
  const totalPages = Math.ceil(filteredCards.length / itemsPerPage);

  return (
    <>
      <IntegratedListTemplateV2<Card>
        title="카드관리"
        description="카드 목록을 관리합니다"
        icon={CreditCard}
        headerActions={headerActions}
        searchValue={searchValue}
        onSearchChange={setSearchValue}
        searchPlaceholder="카드명, 카드번호, 카드사, 사용자 검색..."
        tabs={tabs}
        activeTab={activeTab}
        onTabChange={setActiveTab}
        tableColumns={tableColumns}
        data={paginatedData}
        totalCount={filteredCards.length}
        allData={filteredCards}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        onBulkDelete={handleBulkDelete}
        getItemId={(item) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredCards.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>카드 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              &quot;{cardToDelete?.cardName}&quot; 카드를 삭제하시겠습니까?
              <br />
              <span className="text-destructive">
                삭제된 카드 정보는 복구할 수 없습니다.
              </span>
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleDeleteCard}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}