import { useState } from "react";
import { 
  Building2, 
  Calculator, 
  UserCircle, 
  ArrowLeft, 
  Edit, 
  Trash2, 
  Eye, 
  MapPin, 
  Phone, 
  Mail, 
  Briefcase, 
  CreditCard 
} from "lucide-react";
import { Button } from "./ui/button";
import { Badge } from "./ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Label } from "./ui/label";
import { Separator } from "./ui/separator";
import { Checkbox } from "./ui/checkbox";
import { TableRow, TableCell } from "./ui/table";
import { PageLayout } from "./organisms/PageLayout";
import { ListActions } from "./organisms/ListActions";
import { ClientRegistration } from "./ClientRegistration";
import { IntegratedListTemplateV2, TableColumn, TabOption } from "./templates/IntegratedListTemplateV2";
import { IntegratedFormTemplateV3, type IntegratedFormTemplateV3Config } from "./templates/IntegratedFormTemplateV3";
import { toast } from "sonner@2.0.3";

interface ClientData {
  id: string;
  code: string;
  businessNumber: string;
  name: string;
  type: "매입" | "매출" | "매입매출";
  representative: string;
  address: string;
  businessType: string;
  businessCategory: string;
  phone: string;
  mobile: string;
  fax: string;
  email: string;
  managerName: string;
  managerTel: string;
  memo: string;
  accountId: string;
  accountPassword: string;
  purchasePaymentDay: string;
  salesPaymentDay: string;
  taxAgreement: boolean;
  taxAmount: string;
  taxStartDate: string;
  taxEndDate: string;
  status: "활성" | "비활성";
  manager: string;
  badDebt: boolean;
  badDebtAmount: string;
  badDebtReceiveDate: string;
  badDebtEndDate: string;
  badDebtProgress: string;
}

export function ClientManagement({ filterByType }: { filterByType?: 'all' | 'purchase' | 'sales' }) {
  const [viewMode, setViewMode] = useState<'list' | 'detail' | 'registration'>('list');
  const [editingClient, setEditingClient] = useState<ClientData | null>(null);
  const [viewingClient, setViewingClient] = useState<ClientData | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [currentTab, setCurrentTab] = useState<string>("all");
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  // 샘플 데이터
  const [clients, setClients] = useState<ClientData[]>([
    {
      id: "1",
      code: "2083",
      businessNumber: "1378627566",
      name: "오정건설주식회사",
      type: "매입",
      representative: "이정민",
      address: "경기도 김포시 통진읍 김포대로2462번길 8 1층",
      businessType: "수집운반업",
      businessCategory: "폐기물수집운반",
      phone: "010-8755-4335",
      mobile: "",
      fax: "",
      email: "a9874577@naver.com",
      managerName: "",
      managerTel: "",
      memo: "",
      accountId: "",
      accountPassword: "",
      purchasePaymentDay: "말일",
      salesPaymentDay: "말일",
      taxAgreement: false,
      taxAmount: "",
      taxStartDate: "",
      taxEndDate: "",
      status: "활성",
      manager: "김담당",
      badDebt: false,
      badDebtAmount: "",
      badDebtReceiveDate: "",
      badDebtEndDate: "",
      badDebtProgress: "",
    },
    {
      id: "2",
      code: "2084",
      businessNumber: "0104484748",
      name: "가올산업",
      type: "매출",
      representative: "김철수",
      address: "서울시 강남구 테헤란로 123",
      businessType: "도매",
      businessCategory: "건축자재",
      phone: "010-5555-1234",
      mobile: "010-1234-5678",
      fax: "02-555-5678",
      email: "info@gaol.com",
      managerName: "박영희",
      managerTel: "010-9876-5432",
      memo: "주요 거래처",
      accountId: "gaol123",
      accountPassword: "",
      purchasePaymentDay: "10일",
      salesPaymentDay: "15일",
      taxAgreement: true,
      taxAmount: "1000000",
      taxStartDate: "2024-01-01",
      taxEndDate: "2024-12-31",
      status: "활성",
      manager: "이담당",
      badDebt: true,
      badDebtAmount: "5000000",
      badDebtReceiveDate: "2024-01-15",
      badDebtEndDate: "2024-12-31",
      badDebtProgress: "1차 독촉장 발송 완료 (2024-01-20)\n법무법인 통한 내용증명 발송 (2024-02-01)\n채권추심 진행 중",
    },
    {
      id: "3",
      code: "2085",
      businessNumber: "1234567890",
      name: "조일알미늄 유리공사",
      type: "매입매출",
      representative: "조영수",
      address: "인천시 부평구 산업로 456",
      businessType: "제조",
      businessCategory: "알미늄",
      phone: "032-123-4567",
      mobile: "010-2222-3333",
      fax: "032-123-4568",
      email: "joil@example.com",
      managerName: "최현준",
      managerTel: "010-3333-4444",
      memo: "",
      accountId: "joil_alu",
      accountPassword: "",
      purchasePaymentDay: "말일",
      salesPaymentDay: "20일",
      taxAgreement: false,
      taxAmount: "",
      taxStartDate: "",
      taxEndDate: "",
      status: "활성",
      manager: "박담당",
      badDebt: false,
      badDebtAmount: "",
      badDebtReceiveDate: "",
      badDebtEndDate: "",
      badDebtProgress: "",
    },
  ]);

  const handleViewClient = (client: ClientData) => {
    setViewingClient(client);
    setViewMode('detail');
  };

  const handleBackToList = () => {
    setViewMode('list');
    setViewingClient(null);
    setEditingClient(null);
  };

  const handleOpenRegistration = (client?: ClientData) => {
    if (client) {
      setEditingClient(client);
    } else {
      setEditingClient(null);
    }
    setViewMode('registration');
  };

  const handleSaveClient = (clientData: ClientData) => {
    if (clientData.id && editingClient) {
      // 수정
      setClients(clients.map((c) => (c.id === clientData.id ? clientData : c)));
      toast.success("거래처가 수정되었습니다.");
    } else {
      // 신규 등록
      setClients([...clients, { ...clientData, id: Date.now().toString() }]);
      toast.success("거래처가 등록되었습니다.");
    }
    setViewMode('list');
    setEditingClient(null);
  };

  const handleDeleteClient = (id: string) => {
    if (confirm("삭제하시겠습니까?")) {
      setClients(clients.filter((c) => c.id !== id));
      setSelectedItems(prev => {
        const newSet = new Set(prev);
        newSet.delete(id);
        return newSet;
      });
      toast.success("거래처가 삭제되었습니다.");
    }
  };

  const handleBulkDelete = () => {
    if (selectedItems.size === 0) {
      toast.error("삭제할 항목을 선택해주세요.");
      return;
    }
    if (confirm(`선택한 ${selectedItems.size}개 항목을 삭제하시겠습니까?`)) {
      setClients(clients.filter((c) => !selectedItems.has(c.id)));
      setSelectedItems(new Set());
      toast.success("선택한 거래처가 삭제되었습니다.");
    }
  };

  const toggleItemSelection = (id: string) => {
    setSelectedItems(prev => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  const toggleSelectAll = () => {
    if (selectedItems.size === paginatedClients.length) {
      setSelectedItems(new Set());
    } else {
      setSelectedItems(new Set(paginatedClients.map(c => c.id)));
    }
  };

  // 필터링 로직
  const filteredClients = clients.filter((client) => {
    const matchesSearch =
      client.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      client.businessNumber.includes(searchQuery) ||
      client.representative.toLowerCase().includes(searchQuery.toLowerCase());
    
    // filterByType에 따른 필터링
    let matchesModuleFilter = true;
    if (filterByType === 'purchase') {
      matchesModuleFilter = client.type === "매입" || client.type === "매입매출";
    } else if (filterByType === 'sales') {
      matchesModuleFilter = client.type === "매출" || client.type === "매입매출";
    }
    
    // 탭 필터링
    const matchesTab =
      currentTab === "all" ||
      (currentTab === "purchase" && (client.type === "매입" || client.type === "매입매출")) ||
      (currentTab === "sales" && (client.type === "매출" || client.type === "매입매출")) ||
      (currentTab === "active" && client.status === "활성") ||
      (currentTab === "inactive" && client.status === "비활성");

    return matchesSearch && matchesModuleFilter && matchesTab;
  });

  // 페이지네이션
  const totalPages = Math.ceil(filteredClients.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const paginatedClients = filteredClients.slice(startIndex, startIndex + itemsPerPage);

  // 통계
  const stats = [
    {
      label: "전체 거래처",
      value: clients.length,
      icon: Building2,
      iconColor: "text-blue-600",
    },
    {
      label: "매입 거래처",
      value: clients.filter((c) => c.type === "매입" || c.type === "매입매출").length,
      icon: Calculator,
      iconColor: "text-orange-600",
    },
    {
      label: "매출 거래처",
      value: clients.filter((c) => c.type === "매출" || c.type === "매입매출").length,
      icon: Calculator,
      iconColor: "text-green-600",
    },
    {
      label: "활성 거래처",
      value: clients.filter((c) => c.status === "활성").length,
      icon: UserCircle,
      iconColor: "text-purple-600",
    },
  ];

  // 탭 구성
  const tabs: TabOption[] = [
    { value: "all", label: "전체", count: clients.length, color: "blue" },
    { value: "purchase", label: "매입", count: clients.filter((c) => c.type === "매입" || c.type === "매입매출").length, color: "orange" },
    { value: "sales", label: "매출", count: clients.filter((c) => c.type === "매출" || c.type === "매입매출").length, color: "green" },
    { value: "active", label: "활성", count: clients.filter((c) => c.status === "활성").length, color: "purple" },
    { value: "inactive", label: "비활성", count: clients.filter((c) => c.status === "비활성").length, color: "gray" },
  ];

  // 테이블 컬럼 정의
  const tableColumns: TableColumn[] = [
    { key: "number", label: "번호", className: "px-4" },
    { key: "code", label: "코드", className: "px-4" },
    { key: "type", label: "구분", className: "px-4" },
    { key: "name", label: "거래처명", className: "px-4" },
    { key: "representative", label: "대표자", className: "px-4 hidden md:table-cell" },
    { key: "managerName", label: "담당자", className: "px-4 hidden md:table-cell" },
    { key: "phone", label: "전화번호", className: "px-4 hidden lg:table-cell" },
    { key: "purchasePaymentDay", label: "매입 결제일", className: "px-4 hidden lg:table-cell" },
    { key: "salesPaymentDay", label: "매출 결제일", className: "px-4 hidden lg:table-cell" },
    { key: "badDebt", label: "악성채권", className: "px-4 text-center hidden lg:table-cell" },
    { key: "actions", label: "관리", className: "px-4 text-center" },
  ];

  // 등록/수정 화면
  if (viewMode === 'registration') {
    return (
      <ClientRegistration
        onBack={handleBackToList}
        onSave={handleSaveClient}
        editingClient={editingClient}
      />
    );
  }

  // 상세보기 화면 - IntegratedFormTemplateV3 사용
  if (viewMode === 'detail' && viewingClient) {
    // 거래처 유형별 색상
    const getTypeColor = (type: string) => {
      switch (type) {
        case "매입":
          return "bg-orange-50 text-orange-700";
        case "매출":
          return "bg-green-50 text-green-700";
        case "매입매출":
          return "bg-blue-50 text-blue-700";
        default:
          return "bg-gray-50 text-gray-700";
      }
    };

    // 액션 버튼
    const actions = (
      <div className="flex gap-2">
        <Button variant="outline" size="sm" onClick={handleBackToList}>
          <ArrowLeft className="h-4 w-4 mr-1" />
          목록
        </Button>
        <Button variant="outline" size="sm" onClick={() => handleOpenRegistration(viewingClient)}>
          <Edit className="h-4 w-4 mr-1" />
          수정
        </Button>
        <Button variant="destructive" size="sm" onClick={() => {
          handleDeleteClient(viewingClient.id);
          handleBackToList();
        }}>
          <Trash2 className="h-4 w-4 mr-1" />
          삭제
        </Button>
      </div>
    );

    // IntegratedFormTemplateV3 설정
    const templateConfig: IntegratedFormTemplateV3Config = {
      // 헤더
      header: {
        title: `${viewingClient.name}`,
        description: "거래처 상세 정보",
        icon: Building2,
        actions: actions,
        badge: (
          <div className="flex items-center gap-2">
            <Badge variant="outline" className={getTypeColor(viewingClient.type)}>
              {viewingClient.type}
            </Badge>
            <Badge variant="outline" className={
              viewingClient.status === "활성"
                ? "bg-green-50 text-green-700"
                : "bg-gray-50 text-gray-700"
            }>
              {viewingClient.status}
            </Badge>
          </div>
        ),
      },

      // 섹션들
      sections: [
        // 기본 정보
        {
          id: "basic-info",
          title: "기본 정보",
          icon: Building2,
          gridCols: {
            default: 1,
            md: 2,
            lg: 3,
          },
          fields: [
            {
              label: "CODE",
              value: viewingClient.code,
              type: "code",
            },
            {
              label: "사업자번호",
              value: viewingClient.businessNumber,
            },
            {
              label: "거래처 유형",
              value: (
                <Badge variant="outline" className={getTypeColor(viewingClient.type)}>
                  {viewingClient.type}
                </Badge>
              ),
              type: "badge",
            },
            {
              label: "거래처명",
              value: viewingClient.name,
            },
            {
              label: "대표자",
              value: viewingClient.representative,
            },
            {
              label: "상태",
              value: (
                <Badge variant="outline" className={
                  viewingClient.status === "활성"
                    ? "bg-green-50 text-green-700"
                    : "bg-gray-50 text-gray-700"
                }>
                  {viewingClient.status}
                </Badge>
              ),
              type: "badge",
            },
            {
              label: "주소",
              value: (
                <div className="flex items-start gap-2">
                  <MapPin className="h-4 w-4 text-muted-foreground mt-0.5" />
                  <span>{viewingClient.address || "-"}</span>
                </div>
              ),
              type: "custom",
              span: 3,
            },
            {
              label: "업태",
              value: viewingClient.businessType || "-",
            },
            {
              label: "종목",
              value: viewingClient.businessCategory || "-",
            },
            {
              label: "비고",
              value: viewingClient.memo || "-",
              span: 3,
              hidden: !viewingClient.memo,
            },
          ],
        },

        // 연락처 정보
        {
          id: "contact-info",
          title: "연락처 정보",
          icon: Phone,
          gridCols: {
            default: 1,
            md: 2,
          },
          fields: [
            {
              label: "전화",
              value: (
                <div className="flex items-center gap-2">
                  <Phone className="h-4 w-4 text-muted-foreground" />
                  <span>{viewingClient.phone || "-"}</span>
                </div>
              ),
              type: "custom",
            },
            {
              label: "휴대전화",
              value: (
                <div className="flex items-center gap-2">
                  <Phone className="h-4 w-4 text-muted-foreground" />
                  <span>{viewingClient.mobile || "-"}</span>
                </div>
              ),
              type: "custom",
            },
            {
              label: "팩스",
              value: viewingClient.fax || "-",
            },
            {
              label: "이메일",
              value: (
                <div className="flex items-center gap-2">
                  <Mail className="h-4 w-4 text-muted-foreground" />
                  <span>{viewingClient.email || "-"}</span>
                </div>
              ),
              type: "custom",
            },
            {
              label: "담당자명",
              value: viewingClient.managerName || "-",
            },
            {
              label: "담당자 연락처",
              value: viewingClient.managerTel || "-",
            },
          ],
        },

        // 결제 정보
        {
          id: "payment-info",
          title: "결제 정보",
          icon: CreditCard,
          gridCols: {
            default: 1,
            md: 2,
          },
          fields: [
            {
              label: "매입 결제일",
              value: viewingClient.purchasePaymentDay,
            },
            {
              label: "매출 결제일",
              value: viewingClient.salesPaymentDay,
            },
          ],
        },

        // 악성채권 정보 (조건부)
        {
          id: "bad-debt-info",
          title: "악성채권 정보",
          icon: Briefcase,
          hidden: !viewingClient.badDebt,
          cardClassName: "border-destructive",
          gridCols: {
            default: 1,
            md: 2,
          },
          fields: [
            {
              label: "악성채권 금액",
              value: (
                <span className="text-destructive font-semibold">
                  {viewingClient.badDebtAmount 
                    ? `₩${Number(viewingClient.badDebtAmount).toLocaleString()}` 
                    : "-"}
                </span>
              ),
              type: "custom",
            },
            {
              label: "수령일",
              value: viewingClient.badDebtReceiveDate || "-",
            },
            {
              label: "종료일",
              value: viewingClient.badDebtEndDate || "-",
            },
            {
              label: "진행 상황",
              value: (
                <pre className="text-sm whitespace-pre-wrap font-sans">
                  {viewingClient.badDebtProgress || "-"}
                </pre>
              ),
              type: "custom",
              span: 2,
              hidden: !viewingClient.badDebtProgress,
            },
          ],
        },
      ],

      maxWidth: "default",
    };

    return <IntegratedFormTemplateV3 config={templateConfig} />;
  }

  // 목록 화면 - IntegratedListTemplateV2 사용
  return (
    <IntegratedListTemplateV2
      title="거래처 목록"
      description="거래처 정보를 등록하고 관리합니다"
      icon={Building2}
      headerActions={
        <ListActions
          onAdd={() => handleOpenRegistration()}
          addText="거래처 등록"
          selectedCount={selectedItems.size}
          onBulkDelete={handleBulkDelete}
        />
      }
      stats={stats}
      searchValue={searchQuery}
      onSearchChange={setSearchQuery}
      searchPlaceholder="거래처명, 사업자번호, 대표자로 검색"
      tabs={tabs}
      activeTab={currentTab}
      onTabChange={setCurrentTab}
      tableColumns={tableColumns}
      tableTitle={`${tabs.find(t => t.value === currentTab)?.label || '전체'} 목록 (${filteredClients.length}개)`}
      data={paginatedClients}
      selectedItems={selectedItems}
      onToggleSelection={toggleItemSelection}
      onToggleSelectAll={toggleSelectAll}
      getItemId={(client) => client.id}
      renderTableRow={(client, index, globalIndex) => (
        <TableRow key={client.id} className="cursor-pointer hover:bg-muted/50" onClick={() => handleViewClient(client)}>
          <TableCell onClick={(e) => e.stopPropagation()}>
            <Checkbox
              checked={selectedItems.has(client.id)}
              onCheckedChange={() => toggleItemSelection(client.id)}
            />
          </TableCell>
          <TableCell>{filteredClients.length - globalIndex}</TableCell>
          <TableCell>
            <span className="font-medium font-mono text-xs bg-gray-100 px-2 py-1 rounded">
              {client.code}
            </span>
          </TableCell>
          <TableCell>
            <Badge
              className={
                client.type === "매입"
                  ? "bg-orange-100 text-orange-800 border-orange-300"
                  : client.type === "매출"
                  ? "bg-green-100 text-green-800 border-green-300"
                  : "bg-blue-100 text-blue-800 border-blue-300"
              }
            >
              {client.type}
            </Badge>
          </TableCell>
          <TableCell className="font-medium">{client.name}</TableCell>
          <TableCell className="hidden md:table-cell">{client.representative}</TableCell>
          <TableCell className="hidden md:table-cell">{client.managerName || "-"}</TableCell>
          <TableCell className="hidden lg:table-cell">{client.phone}</TableCell>
          <TableCell className="hidden lg:table-cell">{client.purchasePaymentDay}</TableCell>
          <TableCell className="hidden lg:table-cell">{client.salesPaymentDay}</TableCell>
          <TableCell className="hidden lg:table-cell text-center">
            {client.badDebt ? (
              <Badge variant="destructive">악성채권</Badge>
            ) : (
              <span className="text-muted-foreground">-</span>
            )}
          </TableCell>
          <TableCell onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-center gap-1">
              <Button
                variant="ghost"
                size="sm"
                onClick={(e) => {
                  e.stopPropagation();
                  handleViewClient(client);
                }}
              >
                <Eye className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={(e) => {
                  e.stopPropagation();
                  handleOpenRegistration(client);
                }}
              >
                <Edit className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="sm"
                onClick={(e) => {
                  e.stopPropagation();
                  handleDeleteClient(client.id);
                }}
              >
                <Trash2 className="h-4 w-4 text-destructive" />
              </Button>
            </div>
          </TableCell>
        </TableRow>
      )}
      renderMobileCard={(client, index, globalIndex, isSelected, onToggle) => (
        <div 
          key={client.id}
          className="border rounded-lg p-4 space-y-3 bg-white dark:bg-card hover:bg-muted/50 transition-colors shadow-sm cursor-pointer"
          onClick={() => handleViewClient(client)}
        >
          {/* 체크박스와 번호 */}
          <div className="flex items-start gap-3">
            <Checkbox
              checked={isSelected}
              onCheckedChange={onToggle}
              onClick={(e) => e.stopPropagation()}
              className="mt-1"
            />
            <div className="flex-1 min-w-0 space-y-3">
              {/* 번호 + 코드 */}
              <div className="flex items-center gap-2 flex-wrap">
                <Badge variant="outline" className="bg-gray-100 text-gray-700 font-mono text-xs">
                  #{filteredClients.length - globalIndex}
                </Badge>
                <code className="text-xs bg-blue-50 text-blue-700 px-2 py-1 rounded font-mono">
                  {client.code}
                </code>
              </div>
              
              {/* 거래처명 */}
              <div className="font-semibold text-base">
                {client.name}
              </div>

              {/* 구분 및 상태 */}
              <div className="flex items-center gap-2 flex-wrap">
                <Badge
                  className={
                    client.type === "매입"
                      ? "bg-orange-100 text-orange-800 border-orange-300"
                      : client.type === "매출"
                      ? "bg-green-100 text-green-800 border-green-300"
                      : "bg-blue-100 text-blue-800 border-blue-300"
                  }
                >
                  {client.type}
                </Badge>
                {client.badDebt && (
                  <Badge variant="destructive">악성채권</Badge>
                )}
              </div>

              {/* 상세 정보 */}
              <div className="space-y-2 text-sm">
                <div>
                  <span className="text-muted-foreground">대표자</span>
                  <div className="font-medium mt-0.5">{client.representative}</div>
                </div>
                <div>
                  <span className="text-muted-foreground">전화번호</span>
                  <div className="font-medium mt-0.5">{client.phone}</div>
                </div>
                {client.managerName && (
                  <div>
                    <span className="text-muted-foreground">담당자</span>
                    <div className="font-medium mt-0.5">{client.managerName}</div>
                  </div>
                )}
              </div>

              {/* 결제일 정보 */}
              <div className="grid grid-cols-2 gap-2 text-sm pt-2 border-t">
                <div>
                  <span className="text-muted-foreground text-xs">매입 결제일</span>
                  <div className="font-medium mt-0.5">{client.purchasePaymentDay}</div>
                </div>
                <div>
                  <span className="text-muted-foreground text-xs">매출 결제일</span>
                  <div className="font-medium mt-0.5">{client.salesPaymentDay}</div>
                </div>
              </div>

              {/* 악성채권 금액 */}
              {client.badDebt && client.badDebtAmount && (
                <div className="pt-2 border-t">
                  <span className="text-muted-foreground text-xs">악성채권 금액</span>
                  <div className="text-destructive font-semibold mt-0.5">
                    ₩{Number(client.badDebtAmount).toLocaleString()}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* 액션 버튼 */}
          <div className="flex items-center justify-end gap-1 pt-3 border-t">
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                handleViewClient(client);
              }}
              className="h-9 px-3 flex-1 max-w-[100px]"
            >
              <Eye className="h-4 w-4 mr-1.5" />
              <span className="text-sm">상세</span>
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                handleOpenRegistration(client);
              }}
              className="h-9 px-3 flex-1 max-w-[100px]"
            >
              <Edit className="h-4 w-4 mr-1.5" />
              <span className="text-sm">수정</span>
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={(e) => {
                e.stopPropagation();
                handleDeleteClient(client.id);
              }}
              className="h-9 px-3"
            >
              <Trash2 className="h-4 w-4 text-red-600" />
            </Button>
          </div>
        </div>
      )}
      pagination={{
        currentPage,
        totalPages,
        totalItems: filteredClients.length,
        itemsPerPage,
        onPageChange: setCurrentPage,
      }}
    />
  );
}