'use client';

import { useState, useCallback, useEffect } from 'react';
import { ChevronDown, ChevronUp, GripVertical } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { CurrencyInput } from '@/components/ui/currency-input';
import { NumberInput } from '@/components/ui/number-input';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from '@/components/ui/collapsible';
import { cn } from '@/lib/utils';
import type {
  DashboardSettings,
  TodayIssueSettings,
  EntertainmentLimitType,
  CompanyType,
  WelfareLimitType,
  WelfareCalculationType,
  SectionKey,
} from '../types';
import { DEFAULT_DASHBOARD_SETTINGS, DEFAULT_SECTION_ORDER, SECTION_LABELS } from '../types';

// 현황판 항목 라벨 (구 오늘의 이슈)
const STATUS_BOARD_LABELS: Record<keyof TodayIssueSettings, string> = {
  orders: '수주',
  debtCollection: '채권 추심',
  safetyStock: '안전 재고',
  taxReport: '세금 신고',
  newVendor: '신규 업체 등록',
  annualLeave: '연차',
  lateness: '지각',
  absence: '결근',
  purchase: '발주',
  approvalRequest: '결재 요청',
};

interface DashboardSettingsDialogProps {
  isOpen: boolean;
  onClose: () => void;
  settings: DashboardSettings;
  onSave: (settings: DashboardSettings) => void;
}

export function DashboardSettingsDialog({
  isOpen,
  onClose,
  settings,
  onSave,
}: DashboardSettingsDialogProps) {
  const [localSettings, setLocalSettings] = useState<DashboardSettings>(settings);
  const [expandedSections, setExpandedSections] = useState<Record<string, boolean>>({
    entertainment: false,
    welfare: false,
    statusBoard: false,
    companyTypeInfo: false,
  });

  // DnD 상태
  const [draggedSection, setDraggedSection] = useState<SectionKey | null>(null);
  const [dragOverSection, setDragOverSection] = useState<SectionKey | null>(null);

  // 섹션 순서
  const sectionOrder = localSettings.sectionOrder ?? DEFAULT_SECTION_ORDER;

  // settings가 변경될 때 로컬 상태 업데이트
  useEffect(() => {
    setLocalSettings(settings);
  }, [settings]);

  // 섹션 펼침/접힘 토글
  const toggleSection = useCallback((section: string) => {
    setExpandedSections((prev) => ({
      ...prev,
      [section]: !prev[section],
    }));
  }, []);

  // 오늘의 이슈 (리스트 형태) 토글
  const handleTodayIssueListToggle = useCallback((enabled: boolean) => {
    setLocalSettings((prev) => ({
      ...prev,
      todayIssueList: enabled,
    }));
  }, []);

  // 현황판 전체 토글 (구 오늘의 이슈)
  const handleStatusBoardToggle = useCallback((enabled: boolean) => {
    setLocalSettings((prev) => {
      const statusBoardItems = prev.statusBoard?.items ?? prev.todayIssue.items;
      return {
        ...prev,
        statusBoard: {
          enabled,
          items: enabled
            ? statusBoardItems
            : Object.keys(statusBoardItems).reduce(
                (acc, key) => ({ ...acc, [key]: false }),
                {} as TodayIssueSettings
              ),
        },
        todayIssue: {
          enabled,
          items: enabled
            ? statusBoardItems
            : Object.keys(statusBoardItems).reduce(
                (acc, key) => ({ ...acc, [key]: false }),
                {} as TodayIssueSettings
              ),
        },
      };
    });
  }, []);

  // 현황판 개별 항목 토글
  const handleStatusBoardItemToggle = useCallback(
    (key: keyof TodayIssueSettings, enabled: boolean) => {
      setLocalSettings((prev) => {
        const statusBoardItems = prev.statusBoard?.items ?? prev.todayIssue.items;
        const newItems = {
          ...statusBoardItems,
          [key]: enabled,
        };
        return {
          ...prev,
          statusBoard: {
            ...prev.statusBoard,
            enabled: prev.statusBoard?.enabled ?? prev.todayIssue.enabled,
            items: newItems,
          },
          todayIssue: {
            ...prev.todayIssue,
            items: newItems,
          },
        };
      });
    },
    []
  );

  // 메인 섹션 토글
  const handleSectionToggle = useCallback(
    (
      section:
        | 'dailyReport'
        | 'monthlyExpense'
        | 'cardManagement'
        | 'debtCollection'
        | 'vat'
        | 'calendar'
        | 'production'
        | 'shipment'
        | 'unshipped'
        | 'construction'
        | 'attendance',
      enabled: boolean
    ) => {
      setLocalSettings((prev) => ({
        ...prev,
        [section]: enabled,
      }));
    },
    []
  );

  // 매출/매입/미수금 현황 토글 (단순 boolean)
  const handleSimpleSectionToggle = useCallback(
    (section: 'salesStatus' | 'purchaseStatus' | 'receivable', enabled: boolean) => {
      setLocalSettings((prev) => ({
        ...prev,
        [section]: enabled,
      }));
    },
    []
  );

  // 접대비 설정 변경
  const handleEntertainmentChange = useCallback(
    (
      key: 'enabled' | 'limitType' | 'companyType',
      value: boolean | EntertainmentLimitType | CompanyType
    ) => {
      setLocalSettings((prev) => ({
        ...prev,
        entertainment: {
          ...prev.entertainment,
          [key]: value,
        },
      }));
    },
    []
  );

  // 복리후생비 설정 변경
  const handleWelfareChange = useCallback(
    (
      key: keyof typeof localSettings.welfare,
      value: boolean | WelfareLimitType | WelfareCalculationType | number
    ) => {
      setLocalSettings((prev) => ({
        ...prev,
        welfare: {
          ...prev.welfare,
          [key]: value,
        },
      }));
    },
    []
  );

  // 섹션 순서 변경 (DnD)
  const handleReorder = useCallback((sourceKey: SectionKey, targetKey: SectionKey) => {
    setLocalSettings((prev) => {
      const order = [...(prev.sectionOrder ?? DEFAULT_SECTION_ORDER)];
      const sourceIdx = order.indexOf(sourceKey);
      const targetIdx = order.indexOf(targetKey);
      if (sourceIdx === -1 || targetIdx === -1) return prev;
      order.splice(sourceIdx, 1);
      order.splice(targetIdx, 0, sourceKey);
      return { ...prev, sectionOrder: order };
    });
  }, []);

  // 저장
  const handleSave = useCallback(() => {
    onSave(localSettings);
    onClose();
  }, [localSettings, onSave, onClose]);

  // 취소
  const handleCancel = useCallback(() => {
    setLocalSettings(settings);
    onClose();
  }, [settings, onClose]);

  // 커스텀 스위치 (라이트 테마용)
  const ToggleSwitch = ({
    checked,
    onCheckedChange,
  }: {
    checked: boolean;
    onCheckedChange: (checked: boolean) => void;
  }) => (
    <button
      type="button"
      onClick={() => onCheckedChange(!checked)}
      className={cn(
        'relative inline-flex h-6 w-11 items-center rounded-full transition-colors',
        checked ? 'bg-blue-500' : 'bg-gray-300'
      )}
    >
      <span
        className={cn(
          'inline-block h-4 w-4 transform rounded-full bg-white shadow-md transition-transform',
          checked ? 'translate-x-6' : 'translate-x-1'
        )}
      />
    </button>
  );

  // 섹션 행 컴포넌트 (라이트 테마)
  const SectionRow = ({
    label,
    checked,
    onCheckedChange,
    hasExpand,
    isExpanded,
    onToggleExpand,
    children,
    showGrip,
  }: {
    label: string;
    checked: boolean;
    onCheckedChange: (checked: boolean) => void;
    hasExpand?: boolean;
    isExpanded?: boolean;
    onToggleExpand?: () => void;
    children?: React.ReactNode;
    showGrip?: boolean;
  }) => (
    <Collapsible open={isExpanded} onOpenChange={onToggleExpand}>
      <div
        className={cn(
          'flex items-center justify-between py-3 px-4 bg-gray-200',
          children && isExpanded ? 'rounded-t-lg' : 'rounded-lg'
        )}
      >
        <div className="flex items-center gap-2">
          {showGrip && (
            <GripVertical className="h-4 w-4 text-gray-400 cursor-grab flex-shrink-0" />
          )}
          {hasExpand && (
            <CollapsibleTrigger asChild>
              <button type="button" className="p-1 hover:bg-gray-300 rounded">
                {isExpanded ? (
                  <ChevronUp className="h-4 w-4 text-gray-500" />
                ) : (
                  <ChevronDown className="h-4 w-4 text-gray-500" />
                )}
              </button>
            </CollapsibleTrigger>
          )}
          <span className="text-sm font-medium text-gray-800">{label}</span>
        </div>
        <ToggleSwitch checked={checked} onCheckedChange={onCheckedChange} />
      </div>
      {children && (
        <CollapsibleContent className="px-4 py-3 space-y-3 bg-gray-50 rounded-b-lg">
          {children}
        </CollapsibleContent>
      )}
    </Collapsible>
  );

  // 섹션 렌더링 함수
  const renderSection = (key: SectionKey): React.ReactNode => {
    switch (key) {
      case 'todayIssueList':
        return (
          <SectionRow
            label={SECTION_LABELS.todayIssueList}
            checked={localSettings.todayIssueList}
            onCheckedChange={handleTodayIssueListToggle}
            showGrip
          />
        );

      case 'dailyReport':
        return (
          <SectionRow
            label={SECTION_LABELS.dailyReport}
            checked={localSettings.dailyReport}
            onCheckedChange={(checked) => handleSectionToggle('dailyReport', checked)}
            showGrip
          />
        );

      case 'statusBoard':
        return (
          <SectionRow
            label={SECTION_LABELS.statusBoard}
            checked={localSettings.statusBoard?.enabled ?? localSettings.todayIssue.enabled}
            onCheckedChange={handleStatusBoardToggle}
            hasExpand
            isExpanded={expandedSections.statusBoard}
            onToggleExpand={() => toggleSection('statusBoard')}
            showGrip
          >
            <div className="space-y-0">
              {(Object.keys(STATUS_BOARD_LABELS) as Array<keyof TodayIssueSettings>).map(
                (itemKey) => (
                  <div
                    key={itemKey}
                    className="flex items-center justify-between py-2.5 px-2"
                  >
                    <span className="text-sm text-gray-600">
                      {STATUS_BOARD_LABELS[itemKey]}
                    </span>
                    <ToggleSwitch
                      checked={(localSettings.statusBoard?.items ?? localSettings.todayIssue.items)[itemKey]}
                      onCheckedChange={(checked) =>
                        handleStatusBoardItemToggle(itemKey, checked)
                      }
                    />
                  </div>
                )
              )}
            </div>
          </SectionRow>
        );

      case 'monthlyExpense':
        return (
          <SectionRow
            label={SECTION_LABELS.monthlyExpense}
            checked={localSettings.monthlyExpense}
            onCheckedChange={(checked) => handleSectionToggle('monthlyExpense', checked)}
            showGrip
          />
        );

      case 'cardManagement':
        return (
          <SectionRow
            label={SECTION_LABELS.cardManagement}
            checked={localSettings.cardManagement}
            onCheckedChange={(checked) => handleSectionToggle('cardManagement', checked)}
            showGrip
          />
        );

      case 'entertainment':
        return (
          <SectionRow
            label={SECTION_LABELS.entertainment}
            checked={localSettings.entertainment.enabled}
            onCheckedChange={(checked) => handleEntertainmentChange('enabled', checked)}
            hasExpand
            isExpanded={expandedSections.entertainment}
            onToggleExpand={() => toggleSection('entertainment')}
            showGrip
          >
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">접대비 한도 관리</span>
                <Select
                  value={localSettings.entertainment.limitType}
                  onValueChange={(value: EntertainmentLimitType) =>
                    handleEntertainmentChange('limitType', value)
                  }
                >
                  <SelectTrigger className="w-24 h-8">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="annual">연간</SelectItem>
                    <SelectItem value="quarterly">분기</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">기업 구분</span>
                <Select
                  value={localSettings.entertainment.companyType}
                  onValueChange={(value: CompanyType) =>
                    handleEntertainmentChange('companyType', value)
                  }
                >
                  <SelectTrigger className="w-28 h-8">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="large">대기업</SelectItem>
                    <SelectItem value="medium">중견기업</SelectItem>
                    <SelectItem value="small">중소기업</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {/* 기업 구분 방법 설명 패널 */}
              <Collapsible
                open={expandedSections.companyTypeInfo}
                onOpenChange={() => toggleSection('companyTypeInfo')}
              >
                <CollapsibleTrigger asChild>
                  <button
                    type="button"
                    className="flex items-center justify-between w-full py-2 px-3 text-sm text-gray-600 bg-gray-100 rounded hover:bg-gray-200"
                  >
                    <span>기업 구분 방법</span>
                    {expandedSections.companyTypeInfo ? (
                      <ChevronUp className="h-4 w-4" />
                    ) : (
                      <ChevronDown className="h-4 w-4" />
                    )}
                  </button>
                </CollapsibleTrigger>
                <CollapsibleContent className="mt-2 p-3 bg-white border border-gray-200 rounded text-xs space-y-4">
                  {/* ■ 중소기업 판단 기준표 */}
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="font-bold text-gray-800">■</span>
                      <span className="text-sm font-medium text-gray-800">중소기업 판단 기준표</span>
                    </div>
                    <table className="w-full border-collapse text-xs">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">조건</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">기준</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">충족 요건</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">① 매출액</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">업종별 상이</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">업종별 기준 금액 이하</td>
                        </tr>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">② 자산총액</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">5,000억원</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">미만</td>
                        </tr>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">③ 독립성</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">소유·경영</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">대기업 계열 아님</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>

                  {/* ① 업종별 매출액 기준 */}
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-sm font-medium text-gray-800">① 업종별 매출액 기준 (최근 3개년 평균)</span>
                    </div>
                    <table className="w-full border-collapse text-xs">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">업종 분류</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">기준 매출액</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">제조업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">1,500억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">건설업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">1,000억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">운수업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">1,000억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">도매업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">1,000억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">소매업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">600억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">정보통신업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">600억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">전문서비스업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">600억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">숙박·음식점업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">400억원 이하</td></tr>
                        <tr><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">기타 서비스업</td><td className="border border-gray-200 px-2 py-1 text-center text-gray-600">400억원 이하</td></tr>
                      </tbody>
                    </table>
                  </div>

                  {/* ② 자산총액 기준 */}
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-sm font-medium text-gray-800">② 자산총액 기준</span>
                    </div>
                    <table className="w-full border-collapse text-xs">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">구분</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">기준</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">5,000억원 미만</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">직전 사업연도 말 자산총액</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>

                  {/* ③ 독립성 기준 */}
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="text-sm font-medium text-gray-800">③ 독립성 기준</span>
                    </div>
                    <table className="w-full border-collapse text-xs">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">구분</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">내용</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">판정</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">독립기업</td>
                          <td className="border border-gray-200 px-2 py-1 text-gray-600">아래 항목에 모두 해당하지 않음</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">충족</td>
                        </tr>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">기업집단 소속</td>
                          <td className="border border-gray-200 px-2 py-1 text-gray-600">공정거래법상 상호출자제한 기업집단 소속</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">미충족</td>
                        </tr>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">대기업 지분</td>
                          <td className="border border-gray-200 px-2 py-1 text-gray-600">대기업이 발행주식 30% 이상 보유</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">미충족</td>
                        </tr>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">관계기업 합산</td>
                          <td className="border border-gray-200 px-2 py-1 text-gray-600">관계기업 포함 시 매출액·자산 기준 초과</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">미충족</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>

                  {/* ■ 판정 결과 */}
                  <div>
                    <div className="flex items-center gap-2 mb-2">
                      <span className="font-bold text-gray-800">■</span>
                      <span className="text-sm font-medium text-gray-800">판정 결과</span>
                    </div>
                    <table className="w-full border-collapse text-xs">
                      <thead>
                        <tr className="bg-gray-100">
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">판정</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">조건</th>
                          <th className="border border-gray-300 px-2 py-1 text-center text-gray-700">접대비 기본한도</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">중소기업</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">①②③ 모두 충족</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">3,600만원</td>
                        </tr>
                        <tr>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">일반법인</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">①②③ 중 하나라도 미충족</td>
                          <td className="border border-gray-200 px-2 py-1 text-center text-gray-600">1,200만원</td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </CollapsibleContent>
              </Collapsible>
            </div>
          </SectionRow>
        );

      case 'welfare':
        return (
          <SectionRow
            label={SECTION_LABELS.welfare}
            checked={localSettings.welfare.enabled}
            onCheckedChange={(checked) => handleWelfareChange('enabled', checked)}
            hasExpand
            isExpanded={expandedSections.welfare}
            onToggleExpand={() => toggleSection('welfare')}
            showGrip
          >
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">복리후생비 한도 관리</span>
                <Select
                  value={localSettings.welfare.limitType}
                  onValueChange={(value: WelfareLimitType) =>
                    handleWelfareChange('limitType', value)
                  }
                >
                  <SelectTrigger className="w-24 h-8">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="annual">연간</SelectItem>
                    <SelectItem value="quarterly">분기</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">계산 방식</span>
                <Select
                  value={localSettings.welfare.calculationType}
                  onValueChange={(value: WelfareCalculationType) =>
                    handleWelfareChange('calculationType', value)
                  }
                >
                  <SelectTrigger className="w-40 h-8">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="fixed">직원당 정해 금액 방식</SelectItem>
                    <SelectItem value="ratio">연봉 총액 X 비율 방식</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              {localSettings.welfare.calculationType === 'fixed' ? (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">직원당 정해 금액/월</span>
                  <div className="flex items-center gap-1">
                    <CurrencyInput
                      value={localSettings.welfare.fixedAmountPerMonth}
                      onChange={(value) =>
                        handleWelfareChange(
                          'fixedAmountPerMonth',
                          value ?? 0
                        )
                      }
                      className="w-28 h-8"
                    />
                  </div>
                </div>
              ) : (
                <div className="flex items-center justify-between">
                  <span className="text-sm text-gray-600">비율</span>
                  <div className="flex items-center gap-1">
                    <NumberInput
                      step={0.1}
                      allowDecimal
                      value={localSettings.welfare.ratio}
                      onChange={(value) =>
                        handleWelfareChange('ratio', value ?? 0)
                      }
                      className="w-20 h-8 text-right"
                    />
                    <span className="text-sm text-gray-500">%</span>
                  </div>
                </div>
              )}
              <div className="flex items-center justify-between">
                <span className="text-sm text-gray-600">연간 복리후생비총액</span>
                <div className="flex items-center gap-1">
                  <CurrencyInput
                    value={localSettings.welfare.annualTotal}
                    onChange={(value) =>
                      handleWelfareChange('annualTotal', value ?? 0)
                    }
                    className="w-32 h-8"
                  />
                </div>
              </div>
            </div>
          </SectionRow>
        );

      case 'receivable':
        return (
          <SectionRow
            label={SECTION_LABELS.receivable}
            checked={localSettings.receivable ?? true}
            onCheckedChange={(checked) => handleSimpleSectionToggle('receivable', checked)}
            showGrip
          />
        );

      case 'debtCollection':
        return (
          <SectionRow
            label={SECTION_LABELS.debtCollection}
            checked={localSettings.debtCollection}
            onCheckedChange={(checked) => handleSectionToggle('debtCollection', checked)}
            showGrip
          />
        );

      case 'vat':
        return (
          <SectionRow
            label={SECTION_LABELS.vat}
            checked={localSettings.vat}
            onCheckedChange={(checked) => handleSectionToggle('vat', checked)}
            showGrip
          />
        );

      case 'calendar':
        return (
          <SectionRow
            label={SECTION_LABELS.calendar}
            checked={localSettings.calendar}
            onCheckedChange={(checked) => handleSectionToggle('calendar', checked)}
            showGrip
          />
        );

      case 'salesStatus':
        return (
          <SectionRow
            label={SECTION_LABELS.salesStatus}
            checked={localSettings.salesStatus ?? true}
            onCheckedChange={(checked) => handleSimpleSectionToggle('salesStatus', checked)}
            showGrip
          />
        );

      case 'purchaseStatus':
        return (
          <SectionRow
            label={SECTION_LABELS.purchaseStatus}
            checked={localSettings.purchaseStatus ?? true}
            onCheckedChange={(checked) => handleSimpleSectionToggle('purchaseStatus', checked)}
            showGrip
          />
        );

      case 'production':
        return (
          <SectionRow
            label={SECTION_LABELS.production}
            checked={localSettings.production ?? true}
            onCheckedChange={(checked) => handleSectionToggle('production', checked)}
            showGrip
          />
        );

      case 'shipment':
        return (
          <SectionRow
            label={SECTION_LABELS.shipment}
            checked={localSettings.shipment ?? true}
            onCheckedChange={(checked) => handleSectionToggle('shipment', checked)}
            showGrip
          />
        );

      case 'unshipped':
        return (
          <SectionRow
            label={SECTION_LABELS.unshipped}
            checked={localSettings.unshipped ?? true}
            onCheckedChange={(checked) => handleSectionToggle('unshipped', checked)}
            showGrip
          />
        );

      case 'construction':
        return (
          <SectionRow
            label={SECTION_LABELS.construction}
            checked={localSettings.construction ?? true}
            onCheckedChange={(checked) => handleSectionToggle('construction', checked)}
            showGrip
          />
        );

      case 'attendance':
        return (
          <SectionRow
            label={SECTION_LABELS.attendance}
            checked={localSettings.attendance ?? true}
            onCheckedChange={(checked) => handleSectionToggle('attendance', checked)}
            showGrip
          />
        );

      default:
        return null;
    }
  };

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleCancel()}>
      <DialogContent className="w-[95vw] max-w-[450px] sm:max-w-[450px] max-h-[85vh] overflow-y-auto bg-white border-gray-200 p-0">
        <DialogHeader className="p-4 border-b border-gray-200">
          <DialogTitle className="text-lg font-bold text-gray-900">항목 설정</DialogTitle>
        </DialogHeader>

        <div className="space-y-3 p-4">
          {sectionOrder.map((key) => (
            <div
              key={key}
              draggable
              onDragStart={(e) => {
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData(
                  'application/json',
                  JSON.stringify({ type: 'dashboard-section', key })
                );
                setDraggedSection(key);
              }}
              onDragEnd={() => {
                setDraggedSection(null);
                setDragOverSection(null);
              }}
              onDragOver={(e) => {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';
                if (key !== draggedSection) {
                  setDragOverSection(key);
                }
              }}
              onDragLeave={() => setDragOverSection(null)}
              onDrop={(e) => {
                e.preventDefault();
                try {
                  const data = JSON.parse(e.dataTransfer.getData('application/json'));
                  if (data.type !== 'dashboard-section') return;
                  const sourceKey = data.key as SectionKey;
                  if (sourceKey !== key) handleReorder(sourceKey, key);
                } catch {
                  // ignore
                }
                setDraggedSection(null);
                setDragOverSection(null);
              }}
              className={cn(
                'transition-all',
                draggedSection === key && 'opacity-50',
                dragOverSection === key && draggedSection !== key && 'border-t-2 border-blue-500'
              )}
            >
              {renderSection(key)}
            </div>
          ))}
        </div>

        <DialogFooter className="flex flex-row gap-3 p-4 border-t border-gray-200 justify-center">
          <Button
            variant="outline"
            onClick={handleCancel}
            className="w-20 bg-gray-100 hover:bg-gray-200 text-gray-700 border-gray-300 rounded-full"
          >
            취소
          </Button>
          <Button
            onClick={handleSave}
            className="w-20 bg-gray-500 hover:bg-gray-600 text-white rounded-full"
          >
            저장
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
