'use client';

import { useState, useMemo, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { format } from 'date-fns';
import {
  Receipt,
  Plus,
  Pencil,
  Save,
  Trash2,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { TableRow, TableCell, TableHead } from '@/components/ui/table';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  IntegratedListTemplateV2,
  type TableColumn,
  type StatCard,
} from '@/components/templates/IntegratedListTemplateV2';
import { DateRangeSelector } from '@/components/molecules/DateRangeSelector';
import { ListMobileCard, InfoField } from '@/components/organisms/ListMobileCard';
import type {
  SalesRecord,
  SalesStatus,
  SalesType,
  SortOption,
  IssuanceFilter,
} from './types';
import {
  SORT_OPTIONS,
  SALES_STATUS_LABELS,
  SALES_STATUS_COLORS,
  SALES_TYPE_LABELS,
  SALES_TYPE_FILTER_OPTIONS,
  ISSUANCE_FILTER_OPTIONS,
  ACCOUNT_SUBJECT_SELECTOR_OPTIONS,
} from './types';

// ===== Mock 데이터 생성 (Hydration 오류 방지를 위해 고정값 사용) =====
const generateMockData = (): SalesRecord[] => {
  const salesTypes: SalesType[] = ['credit', 'product', 'goods', 'parts', 'construction', 'rental', 'other'];
  const statuses: SalesStatus[] = ['monthlyClose', 'lastMonth', 'agreed', 'outstanding'];
  const vendors = ['(주)삼성전자', '현대자동차', 'LG전자', 'SK하이닉스', '네이버', '카카오', '쿠팡', '배달의민족'];

  // 고정된 금액 패턴 (Hydration 오류 방지)
  const amounts = [1000000, 2500000, 500000, 3000000, 1500000, 800000, 4000000, 2000000];
  const quantities = [10, 25, 5, 30, 15, 8, 40, 20];

  return Array.from({ length: 50 }, (_, i) => {
    const supplyAmount = amounts[i % amounts.length] + (i * 100000);
    const vat = Math.floor(supplyAmount * 0.1);
    const totalAmount = supplyAmount + vat;
    // 짝수 인덱스는 전액 입금, 홀수 인덱스는 부분 입금 또는 미입금
    const receivedAmount = i % 2 === 0 ? totalAmount : Math.floor(totalAmount * (i % 3 === 0 ? 0.5 : 0));
    const outstandingAmount = totalAmount - receivedAmount;

    return {
      id: `sales-${i + 1}`,
      salesNo: `SL-2025-${String(i + 1).padStart(4, '0')}`,
      salesDate: format(new Date(2025, 11, (i % 17) + 1), 'yyyy-MM-dd'),
      vendorId: `vendor-${i % vendors.length}`,
      vendorName: vendors[i % vendors.length],
      salesType: salesTypes[i % salesTypes.length],
      accountSubject: salesTypes[i % salesTypes.length],
      items: [
        {
          id: `item-${i}-1`,
          itemName: `품목 ${i + 1}`,
          quantity: quantities[i % quantities.length],
          unitPrice: Math.floor(supplyAmount / quantities[i % quantities.length]),
          supplyAmount,
          vat,
          note: '',
        },
      ],
      totalSupplyAmount: supplyAmount,
      totalVat: vat,
      totalAmount,
      receivedAmount,
      outstandingAmount,
      taxInvoiceIssued: i % 2 === 0,
      transactionStatementIssued: i % 3 === 0,
      note: i % 3 === 0 ? '비고 내용' : '',
      status: outstandingAmount > 0 ? 'outstanding' : statuses[i % statuses.length],
      createdAt: '2025-12-18T00:00:00.000Z',
      updatedAt: '2025-12-18T00:00:00.000Z',
    };
  });
};

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

  // ===== 상태 관리 =====
  const [searchQuery, setSearchQuery] = useState('');
  const [sortOption, setSortOption] = useState<SortOption>('latest');
  const [salesTypeFilter, setSalesTypeFilter] = useState<string>('all');
  const [vendorFilter, setVendorFilter] = useState<string>('all');
  const [issuanceFilter, setIssuanceFilter] = useState<IssuanceFilter>('all');
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 20;

  // 상단 계정과목명 선택 (저장용)
  const [selectedAccountSubject, setSelectedAccountSubject] = useState<string>('unset');

  // 계정과목명 저장 다이얼로그
  const [showSaveDialog, setShowSaveDialog] = useState(false);

  // 삭제 다이얼로그
  const [showDeleteDialog, setShowDeleteDialog] = useState(false);
  const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);

  // 날짜 범위 상태
  const [startDate, setStartDate] = useState('2025-01-01');
  const [endDate, setEndDate] = useState('2025-12-31');

  // Mock 데이터 (토글 상태 변경을 위해 setData 추가)
  const [data, setData] = useState<SalesRecord[]>(generateMockData);

  // ===== 체크박스 핸들러 =====
  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 filteredData = useMemo(() => {
    let result = data.filter(item =>
      item.salesNo.includes(searchQuery) ||
      item.vendorName.includes(searchQuery) ||
      item.note.includes(searchQuery)
    );

    // 거래처 필터
    if (vendorFilter !== 'all') {
      result = result.filter(item => item.vendorName === vendorFilter);
    }

    // 매출 유형 필터
    if (salesTypeFilter !== 'all') {
      result = result.filter(item => item.salesType === salesTypeFilter);
    }

    // 발행여부 필터
    if (issuanceFilter === 'taxInvoicePending') {
      result = result.filter(item => !item.taxInvoiceIssued);
    } else if (issuanceFilter === 'transactionStatementPending') {
      result = result.filter(item => !item.transactionStatementIssued);
    }

    // 정렬
    switch (sortOption) {
      case 'latest':
        result.sort((a, b) => new Date(b.salesDate).getTime() - new Date(a.salesDate).getTime());
        break;
      case 'oldest':
        result.sort((a, b) => new Date(a.salesDate).getTime() - new Date(b.salesDate).getTime());
        break;
      case 'amountHigh':
        result.sort((a, b) => b.totalAmount - a.totalAmount);
        break;
      case 'amountLow':
        result.sort((a, b) => a.totalAmount - b.totalAmount);
        break;
    }

    return result;
  }, [data, searchQuery, vendorFilter, salesTypeFilter, issuanceFilter, sortOption]);

  const paginatedData = useMemo(() => {
    const startIndex = (currentPage - 1) * itemsPerPage;
    return filteredData.slice(startIndex, startIndex + itemsPerPage);
  }, [filteredData, currentPage, itemsPerPage]);

  const totalPages = Math.ceil(filteredData.length / itemsPerPage);

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

  // ===== 액션 핸들러 =====
  const handleDelete = useCallback(() => {
    console.log('삭제:', Array.from(selectedItems));
    setSelectedItems(new Set());
  }, [selectedItems]);

  const handleNewSales = useCallback(() => {
    router.push('/ko/accounting/sales/new');
  }, [router]);

  const handleRowClick = useCallback((item: SalesRecord) => {
    router.push(`/ko/accounting/sales/${item.id}`);
  }, [router]);

  // 개별 항목 삭제 핸들러
  const handleDeleteClick = useCallback((id: string) => {
    setDeleteTargetId(id);
    setShowDeleteDialog(true);
  }, []);

  // 삭제 확정 핸들러
  const handleConfirmDelete = useCallback(() => {
    if (deleteTargetId) {
      console.log('삭제:', deleteTargetId);
      setData(prev => prev.filter(item => item.id !== deleteTargetId));
      setSelectedItems(prev => {
        const newSet = new Set(prev);
        newSet.delete(deleteTargetId);
        return newSet;
      });
    }
    setShowDeleteDialog(false);
    setDeleteTargetId(null);
  }, [deleteTargetId]);

  // ===== 통계 카드 =====
  const statCards: StatCard[] = useMemo(() => {
    const totalSalesAmount = data.reduce((sum, d) => sum + d.totalAmount, 0);
    // 당월 매출 (현재 월 기준)
    const currentMonth = new Date().getMonth();
    const currentYear = new Date().getFullYear();
    const monthlyAmount = data
      .filter(d => {
        const date = new Date(d.salesDate);
        return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
      })
      .reduce((sum, d) => sum + d.totalAmount, 0);
    // 세금계산서 발행대기 (미발행 건수)
    const taxInvoicePendingCount = data.filter(d => !d.taxInvoiceIssued).length;
    // 거래명세서 발행대기 (미발행 건수)
    const transactionStatementPendingCount = data.filter(d => !d.transactionStatementIssued).length;

    return [
      { label: '총 매출', value: `${totalSalesAmount.toLocaleString()}원`, icon: Receipt, iconColor: 'text-blue-500' },
      { label: '당월 매출', value: `${monthlyAmount.toLocaleString()}원`, icon: Receipt, iconColor: 'text-green-500' },
      { label: '세금계산서 발행대기', value: `${taxInvoicePendingCount}건`, icon: Receipt, iconColor: 'text-orange-500' },
      { label: '거래명세서 발행대기', value: `${transactionStatementPendingCount}건`, icon: Receipt, iconColor: 'text-orange-500' },
    ];
  }, [data]);

  // ===== 테이블 컬럼 (스크린샷 기준) =====
  // 번호, 매출번호, 매출일, 거래처, 공급가액, 부가세, 합계금액, 매출유형, 세금계산서 발행완료, 거래명세서 발행완료, 작업
  const tableColumns: TableColumn[] = useMemo(() => [
    { key: 'no', label: '번호', className: 'text-center w-[60px]' },
    { key: 'salesNo', label: '매출번호' },
    { key: 'salesDate', label: '매출일' },
    { key: 'vendorName', label: '거래처' },
    { key: 'supplyAmount', label: '공급가액', className: 'text-right' },
    { key: 'vat', label: '부가세', className: 'text-right' },
    { key: 'totalAmount', label: '합계금액', className: 'text-right' },
    { key: 'salesType', label: '매출유형', className: 'text-center' },
    { key: 'taxInvoice', label: '세금계산서 발행완료', className: 'text-center' },
    { key: 'transactionStatement', label: '거래명세서 발행완료', className: 'text-center' },
    { key: 'actions', label: '작업', className: 'text-center w-[80px]' },
  ], []);

  // ===== 금액 포맷 =====
  const formatAmount = (amount: number): string => {
    return amount.toLocaleString() + '원';
  };

  // ===== 토글 핸들러 =====
  const handleTaxInvoiceToggle = useCallback((itemId: string, checked: boolean) => {
    console.log('세금계산서 발행완료 변경:', itemId, checked);
    setData(prev => prev.map(item =>
      item.id === itemId ? { ...item, taxInvoiceIssued: checked } : item
    ));
    // TODO: API 호출로 상태 저장
  }, []);

  const handleTransactionStatementToggle = useCallback((itemId: string, checked: boolean) => {
    console.log('거래명세서 발행완료 변경:', itemId, checked);
    setData(prev => prev.map(item =>
      item.id === itemId ? { ...item, transactionStatementIssued: checked } : item
    ));
    // TODO: API 호출로 상태 저장
  }, []);

  // ===== 테이블 행 렌더링 (스크린샷 기준 컬럼) =====
  // 번호, 매출번호, 매출일, 거래처, 공급가액, 부가세, 합계금액, 매출유형, 세금계산서(토글), 거래명세서(토글), 작업
  const renderTableRow = useCallback((item: SalesRecord, 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-center text-sm text-gray-500">{globalIndex}</TableCell>
        {/* 매출번호 */}
        <TableCell className="text-sm font-medium">{item.salesNo}</TableCell>
        {/* 매출일 */}
        <TableCell>{item.salesDate}</TableCell>
        {/* 거래처 */}
        <TableCell>{item.vendorName}</TableCell>
        {/* 공급가액 */}
        <TableCell className="text-right">{item.totalSupplyAmount.toLocaleString()}</TableCell>
        {/* 부가세 */}
        <TableCell className="text-right">{item.totalVat.toLocaleString()}</TableCell>
        {/* 합계금액 */}
        <TableCell className="text-right font-medium">{item.totalAmount.toLocaleString()}</TableCell>
        {/* 매출유형 */}
        <TableCell className="text-center">
          <Badge variant="outline">{SALES_TYPE_LABELS[item.salesType]}</Badge>
        </TableCell>
        {/* 세금계산서 발행완료 (토글) */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <div className="flex items-center justify-center gap-1">
            <Switch
              checked={item.taxInvoiceIssued}
              onCheckedChange={(checked) => handleTaxInvoiceToggle(item.id, checked)}
              className="data-[state=checked]:bg-orange-500"
            />
            {item.taxInvoiceIssued && <span className="text-xs text-orange-500 font-medium">발행</span>}
          </div>
        </TableCell>
        {/* 거래명세서 발행완료 (토글) */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          <div className="flex items-center justify-center gap-1">
            <Switch
              checked={item.transactionStatementIssued}
              onCheckedChange={(checked) => handleTransactionStatementToggle(item.id, checked)}
              className="data-[state=checked]:bg-orange-500"
            />
            {item.transactionStatementIssued && <span className="text-xs text-orange-500 font-medium">발행</span>}
          </div>
        </TableCell>
        {/* 작업 */}
        <TableCell className="text-center" onClick={(e) => e.stopPropagation()}>
          {isSelected && (
            <div className="flex items-center justify-center gap-1">
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-gray-600 hover:text-gray-700 hover:bg-gray-50"
                onClick={() => router.push(`/ko/accounting/sales/${item.id}?mode=edit`)}
              >
                <Pencil className="h-4 w-4" />
              </Button>
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50"
                onClick={() => handleDeleteClick(item.id)}
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            </div>
          )}
        </TableCell>
      </TableRow>
    );
  }, [selectedItems, toggleSelection, handleRowClick, handleTaxInvoiceToggle, handleTransactionStatementToggle, handleDeleteClick]);

  // ===== 모바일 카드 렌더링 =====
  const renderMobileCard = useCallback((
    item: SalesRecord,
    index: number,
    globalIndex: number,
    isSelected: boolean,
    onToggle: () => void
  ) => {
    return (
      <ListMobileCard
        id={item.id}
        title={item.vendorName}
        headerBadges={
          <>
            <Badge variant="outline">{SALES_TYPE_LABELS[item.salesType]}</Badge>
            <Badge className={SALES_STATUS_COLORS[item.status]}>
              {SALES_STATUS_LABELS[item.status]}
            </Badge>
          </>
        }
        isSelected={isSelected}
        onToggleSelection={onToggle}
        infoGrid={
          <div className="grid grid-cols-2 gap-3">
            <InfoField label="매출번호" value={item.salesNo} />
            <InfoField label="매출일" value={item.salesDate} />
            <InfoField label="매출금액" value={formatAmount(item.totalAmount)} />
            <InfoField
              label="미수금액"
              value={formatAmount(item.outstandingAmount)}
              className={item.outstandingAmount > 0 ? 'text-red-600' : ''}
            />
          </div>
        }
        actions={
          isSelected ? (
            <div className="flex gap-2 w-full">
              <Button variant="outline" className="flex-1" onClick={() => handleRowClick(item)}>
                <Pencil className="w-4 h-4 mr-2" /> 수정
              </Button>
              <Button
                variant="outline"
                className="flex-1 text-red-500 border-red-200 hover:bg-red-50 hover:text-red-600"
                onClick={() => handleDeleteClick(item.id)}
              >
                <Trash2 className="w-4 h-4 mr-2" /> 삭제
              </Button>
            </div>
          ) : undefined
        }
        onClick={() => handleRowClick(item)}
      />
    );
  }, [handleRowClick, handleDeleteClick]);

  // ===== 헤더 액션 =====
  const headerActions = (
    <>
      <DateRangeSelector
        startDate={startDate}
        endDate={endDate}
        onStartDateChange={setStartDate}
        onEndDateChange={setEndDate}
      />
      <Button className="ml-auto" onClick={handleNewSales}>
        <Plus className="h-4 w-4 mr-2" />
        매출 등록
      </Button>
    </>
  );

  // ===== 계정과목명 저장 핸들러 =====
  const handleSaveAccountSubject = useCallback(() => {
    if (selectedItems.size === 0) {
      alert('변경할 매출 항목을 선택해주세요.');
      return;
    }
    setShowSaveDialog(true);
  }, [selectedItems.size]);

  // 계정과목명 저장 확정
  const handleConfirmSaveAccountSubject = useCallback(() => {
    console.log('계정과목명 저장:', selectedAccountSubject, '선택된 항목:', Array.from(selectedItems));
    // TODO: API 호출로 저장
    setShowSaveDialog(false);
    setSelectedItems(new Set());
  }, [selectedAccountSubject, selectedItems]);

  // ===== 거래처 목록 (필터용) =====
  const vendorOptions = useMemo(() => {
    const uniqueVendors = [...new Set(data.map(d => d.vendorName))];
    return [
      { value: 'all', label: '거래처 전체' },
      ...uniqueVendors.map(v => ({ value: v, label: v }))
    ];
  }, [data]);

  // ===== 테이블 헤더 액션 (4개 필터: 거래처, 매출유형, 발행여부, 정렬) =====
  const tableHeaderActions = (
    <div className="flex items-center gap-2 flex-wrap">
      {/* 거래처 필터 */}
      <Select value={vendorFilter} onValueChange={setVendorFilter}>
        <SelectTrigger className="w-[140px]">
          <SelectValue placeholder="거래처" />
        </SelectTrigger>
        <SelectContent>
          {vendorOptions.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 매출유형 필터 */}
      <Select value={salesTypeFilter} onValueChange={setSalesTypeFilter}>
        <SelectTrigger className="w-[130px]">
          <SelectValue placeholder="매출유형" />
        </SelectTrigger>
        <SelectContent>
          {SALES_TYPE_FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 발행여부 필터 */}
      <Select value={issuanceFilter} onValueChange={(value) => setIssuanceFilter(value as IssuanceFilter)}>
        <SelectTrigger className="w-[150px]">
          <SelectValue placeholder="발행여부" />
        </SelectTrigger>
        <SelectContent>
          {ISSUANCE_FILTER_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>

      {/* 정렬 */}
      <Select value={sortOption} onValueChange={(value) => setSortOption(value as SortOption)}>
        <SelectTrigger className="w-[120px]">
          <SelectValue placeholder="정렬" />
        </SelectTrigger>
        <SelectContent>
          {SORT_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
    </div>
  );

  // ===== 테이블 합계 계산 =====
  const tableTotals = useMemo(() => {
    const totalSupplyAmount = filteredData.reduce((sum, item) => sum + item.totalSupplyAmount, 0);
    const totalVat = filteredData.reduce((sum, item) => sum + item.totalVat, 0);
    const totalAmount = filteredData.reduce((sum, item) => sum + item.totalAmount, 0);
    return { totalSupplyAmount, totalVat, totalAmount };
  }, [filteredData]);

  // ===== 테이블 하단 합계 행 =====
  const tableFooter = (
    <TableRow className="bg-muted/50 font-medium">
      <TableCell className="text-center"></TableCell>
      <TableCell className="text-center"></TableCell>
      <TableCell className="font-bold">합계</TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell className="text-right font-bold">{tableTotals.totalSupplyAmount.toLocaleString()}</TableCell>
      <TableCell className="text-right font-bold">{tableTotals.totalVat.toLocaleString()}</TableCell>
      <TableCell className="text-right font-bold">{tableTotals.totalAmount.toLocaleString()}</TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
      <TableCell></TableCell>
    </TableRow>
  );

  // ===== 상단 계정과목명 + 저장 버튼 =====
  const accountSubjectSelector = (
    <div className="flex items-center gap-2">
      <span className="text-sm font-medium text-gray-700">계정과목명</span>
      <Select value={selectedAccountSubject} onValueChange={setSelectedAccountSubject}>
        <SelectTrigger className="w-[150px]">
          <SelectValue placeholder="계정과목명 선택" />
        </SelectTrigger>
        <SelectContent>
          {ACCOUNT_SUBJECT_SELECTOR_OPTIONS.map((option) => (
            <SelectItem key={option.value} value={option.value}>
              {option.label}
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Button onClick={handleSaveAccountSubject} className="bg-orange-500 hover:bg-orange-600">
        <Save className="h-4 w-4 mr-2" />
        저장
      </Button>
    </div>
  );

  return (
    <>
      <IntegratedListTemplateV2
        title="매출관리"
        description="매출 내역을 등록하고 관리합니다"
        icon={Receipt}
        headerActions={headerActions}
        stats={statCards}
        searchValue={searchQuery}
        onSearchChange={setSearchQuery}
        searchPlaceholder="매출번호, 거래처명, 비고 검색..."
        beforeTableContent={accountSubjectSelector}
        tableHeaderActions={tableHeaderActions}
        tableColumns={tableColumns}
        tableFooter={tableFooter}
        data={paginatedData}
        totalCount={filteredData.length}
        allData={filteredData}
        selectedItems={selectedItems}
        onToggleSelection={toggleSelection}
        onToggleSelectAll={toggleSelectAll}
        getItemId={(item: SalesRecord) => item.id}
        renderTableRow={renderTableRow}
        renderMobileCard={renderMobileCard}
        pagination={{
          currentPage,
          totalPages,
          totalItems: filteredData.length,
          itemsPerPage,
          onPageChange: setCurrentPage,
        }}
      />

      {/* 계정과목명 저장 확인 다이얼로그 */}
      <Dialog open={showSaveDialog} onOpenChange={setShowSaveDialog}>
        <DialogContent className="sm:max-w-[425px]">
          <DialogHeader>
            <DialogTitle>계정과목명 변경</DialogTitle>
            <DialogDescription>
              {selectedItems.size}개의 매출유형을{' '}
              <span className="font-semibold text-orange-500">
                {ACCOUNT_SUBJECT_SELECTOR_OPTIONS.find(o => o.value === selectedAccountSubject)?.label}
              </span>
              (으)로 모두 변경하시겠습니까?
            </DialogDescription>
          </DialogHeader>
          <DialogFooter className="gap-2 sm:gap-0">
            <Button variant="outline" onClick={() => setShowSaveDialog(false)}>
              취소
            </Button>
            <Button
              onClick={handleConfirmSaveAccountSubject}
              className="bg-orange-500 hover:bg-orange-600"
            >
              확인
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 삭제 확인 다이얼로그 */}
      <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>매출 삭제</AlertDialogTitle>
            <AlertDialogDescription>
              이 매출 내역을 삭제하시겠습니까? 이 작업은 취소할 수 없습니다.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>취소</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-red-600 hover:bg-red-700"
            >
              삭제
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
}