'use client';

import { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { CreditCard, Edit, Trash2, Plus, Search, RefreshCw } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import { TableRow, TableCell } from '@/components/ui/table';
import { DeleteConfirmDialog } from '@/components/ui/confirm-dialog';
import {
  UniversalListPage,
  type UniversalListConfig,
  type TabOption,
} from '@/components/templates/UniversalListPage';
import { ListMobileCard, InfoField } from '@/components/organisms/MobileCard';
import { toast } from 'sonner';
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 CardManagementProps {
  initialData?: Card[];
}

export function CardManagement({ initialData }: CardManagementProps) {
  const router = useRouter();

  // 카드 데이터 상태
  const [cards, setCards] = useState<Card[]>(initialData || []);
  const [isLoading, setIsLoading] = useState(!initialData);
  const isInitialLoadDone = useRef(false);

  // 데이터 로드
  useEffect(() => {
    if (!initialData) {
      loadCards();
    }
  }, [initialData]);

  const loadCards = async () => {
    if (!isInitialLoadDone.current) {
      setIsLoading(true);
    }
    const result = await getCards({ per_page: 100 });
    if (result.success && result.data) {
      setCards(result.data);
    } else {
      toast.error(result.error || '카드 목록을 불러오는데 실패했습니다.');
    }
    setIsLoading(false);
    isInitialLoadDone.current = true;
  };

  // 검색 및 필터 상태
  const [searchQuery, setSearchQuery] = 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 (searchQuery) {
      const search = searchQuery.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, searchQuery]);

  // 페이지네이션된 데이터
  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 = 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(async () => {
    const ids = Array.from(selectedItems);
    const result = await deleteCards(ids);
    if (result.success) {
      setCards(prev => prev.filter(card => !ids.includes(card.id)));
      setSelectedItems(new Set());
      toast.success('선택한 카드가 삭제되었습니다.');
    } else {
      toast.error(result.error || '삭제에 실패했습니다.');
    }
  }, [selectedItems]);

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

  const handleDeleteCard = useCallback(async () => {
    if (cardToDelete) {
      const result = await deleteCard(cardToDelete.id);
      if (result.success) {
        setCards(prev => prev.filter(card => card.id !== cardToDelete.id));
        toast.success('카드가 삭제되었습니다.');
      } else {
        toast.error(result.error || '삭제에 실패했습니다.');
      }
      setDeleteDialogOpen(false);
      setCardToDelete(null);
    }
  }, [cardToDelete]);

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

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

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

  // ===== UniversalListPage 설정 =====
  const cardManagementConfig: UniversalListConfig<Card> = useMemo(() => ({
    title: '카드관리',
    description: '카드 목록을 관리합니다',
    icon: CreditCard,
    basePath: '/hr/card-management',

    idField: 'id',

    actions: {
      getList: async () => ({
        success: true,
        data: cards,
        totalCount: cards.length,
      }),
      deleteBulk: async (ids) => {
        const result = await deleteCards(ids);
        if (result.success) {
          setCards(prev => prev.filter(card => !ids.includes(card.id)));
          setSelectedItems(new Set());
          toast.success('선택한 카드가 삭제되었습니다.');
        } else {
          toast.error(result.error || '삭제에 실패했습니다.');
        }
        return result;
      },
    },

    columns: tableColumns,

    tabs: tabs,
    defaultTab: activeTab,

    createButton: {
      label: '카드 등록',
      icon: Plus,
      onClick: handleAddCard,
    },

    searchPlaceholder: '카드명, 카드번호, 카드사, 사용자 검색...',

    itemsPerPage: itemsPerPage,

    clientSideFiltering: true,

    searchFilter: (item, searchValue) => {
      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)
      );
    },

    tabFilter: (item, activeTab) => {
      if (activeTab === 'all') return true;
      return item.status === activeTab;
    },

    renderTableRow: (item, index, globalIndex, handlers) => {
      const { isSelected, onToggle, onRowClick } = handlers;

      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={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={() => 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>
      );
    },

    renderMobileCard: (item, index, globalIndex, handlers) => {
      const { isSelected, onToggle } = handlers;

      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
          }
        />
      );
    },

    renderDialogs: () => (
      <DeleteConfirmDialog
        open={deleteDialogOpen}
        onOpenChange={setDeleteDialogOpen}
        onConfirm={handleDeleteCard}
        title="카드 삭제"
        description={
          <>
            &quot;{cardToDelete?.cardName}&quot; 카드를 삭제하시겠습니까?
            <br />
            <span className="text-destructive">
              삭제된 카드 정보는 복구할 수 없습니다.
            </span>
          </>
        }
      />
    ),
  }), [
    cards,
    tableColumns,
    tabs,
    activeTab,
    handleAddCard,
    handleRowClick,
    handleEdit,
    openDeleteDialog,
    deleteDialogOpen,
    cardToDelete,
    handleDeleteCard,
  ]);

  return (
    <UniversalListPage<Card>
      config={cardManagementConfig}
      initialData={cards}
      initialTotalCount={cards.length}
      externalIsLoading={isLoading}
    />
  );
}