'use client';

import { ChevronDown, ChevronUp, GripVertical } from 'lucide-react';
import { CurrencyInput } from '@/components/ui/currency-input';
import { NumberInput } from '@/components/ui/number-input';
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 {
  TodayIssueSettings,
  DashboardSettings,
  EntertainmentLimitType,
  CompanyType,
  WelfareLimitType,
  WelfareCalculationType,
} from '../types';

// ─── 현황판 항목 라벨 ──────────────────────────────
export const STATUS_BOARD_LABELS: Record<keyof TodayIssueSettings, string> = {
  orders: '수주',
  debtCollection: '채권 추심',
  safetyStock: '안전 재고',
  taxReport: '세금 신고',
  newVendor: '신규 업체 등록',
  annualLeave: '연차',
  vehicle: '차량',
  equipment: '장비',
  purchase: '발주',  // [2026-03-03] 비활성화 — 설정 모달에서 숨김 처리 (STATUS_BOARD_HIDDEN_SETTINGS)
  approvalRequest: '결재 요청',
  fundStatus: '자금 현황',
};

// ─── 커스텀 스위치 ──────────────────────────────────
export function ToggleSwitch({
  checked,
  onCheckedChange,
}: {
  checked: boolean;
  onCheckedChange: (checked: boolean) => void;
}) {
  return (
    <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>
  );
}

// ─── 섹션 행 (Collapsible 래퍼) ─────────────────────
export function 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;
}) {
  return (
    <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>
  );
}

// [2026-03-03] 설정 모달에서 숨길 항목
// - purchase: 백엔드 path 오류 + 데이터 정합성 이슈 (API-SPEC N4 참조)
// - vehicle, equipment, fundStatus: 백엔드 API에서 미제공 (StatusBoard 응답에 없음)
const STATUS_BOARD_HIDDEN_SETTINGS = new Set<keyof TodayIssueSettings>([
  'purchase', 'vehicle', 'equipment', 'fundStatus',
]);

// ─── 현황판 항목 토글 리스트 ────────────────────────
export function StatusBoardItemsList({
  items,
  onToggle,
}: {
  items: TodayIssueSettings;
  onToggle: (key: keyof TodayIssueSettings, checked: boolean) => void;
}) {
  return (
    <div className="space-y-0">
      {(Object.keys(STATUS_BOARD_LABELS) as Array<keyof TodayIssueSettings>)
        .filter((itemKey) => !STATUS_BOARD_HIDDEN_SETTINGS.has(itemKey))
        .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={items[itemKey]}
              onCheckedChange={(checked) => onToggle(itemKey, checked)}
            />
          </div>
        )
      )}
    </div>
  );
}

// ─── 기업 구분 방법 설명 패널 ───────────────────────
function CompanyTypeInfoPanel({
  isExpanded,
  onToggle,
}: {
  isExpanded: boolean;
  onToggle: () => void;
}) {
  return (
    <Collapsible open={isExpanded} onOpenChange={onToggle}>
      <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>
          {isExpanded ? (
            <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>
  );
}

// ─── 접대비 설정 콘텐츠 ─────────────────────────────
export function EntertainmentContent({
  entertainment,
  onChange,
  companyTypeInfoExpanded,
  onToggleCompanyTypeInfo,
}: {
  entertainment: DashboardSettings['entertainment'];
  onChange: (
    key: 'limitType' | 'companyType' | 'highAmountThreshold',
    value: EntertainmentLimitType | CompanyType | number,
  ) => void;
  companyTypeInfoExpanded: boolean;
  onToggleCompanyTypeInfo: () => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-600">접대비 한도 관리</span>
        <Select
          value={entertainment.limitType}
          onValueChange={(value: EntertainmentLimitType) => onChange('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={entertainment.companyType}
          onValueChange={(value: CompanyType) => onChange('companyType', value)}
        >
          <SelectTrigger className="w-28 h-8">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="small">소기업</SelectItem>
            <SelectItem value="medium">중기업</SelectItem>
            <SelectItem value="large">대기업</SelectItem>
          </SelectContent>
        </Select>
      </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={entertainment.highAmountThreshold}
            onChange={(value) => onChange('highAmountThreshold', value ?? 0)}
            className="w-28 h-8"
          />
        </div>
      </div>
      <CompanyTypeInfoPanel
        isExpanded={companyTypeInfoExpanded}
        onToggle={onToggleCompanyTypeInfo}
      />
    </div>
  );
}

// ─── 복리후생비 설정 콘텐츠 ─────────────────────────
export function WelfareContent({
  welfare,
  onChange,
}: {
  welfare: DashboardSettings['welfare'];
  onChange: (
    key: keyof DashboardSettings['welfare'],
    value: WelfareLimitType | WelfareCalculationType | number,
  ) => void;
}) {
  return (
    <div className="space-y-3">
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-600">복리후생비 한도 관리</span>
        <Select
          value={welfare.limitType}
          onValueChange={(value: WelfareLimitType) => onChange('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={welfare.calculationType}
          onValueChange={(value: WelfareCalculationType) => onChange('calculationType', value)}
        >
          <SelectTrigger className="w-40 h-8">
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="fixed">직원당 정해 금액 방식</SelectItem>
            <SelectItem value="ratio">연봉 총액 X 비율 방식</SelectItem>
          </SelectContent>
        </Select>
      </div>
      {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={welfare.fixedAmountPerMonth}
              onChange={(value) => onChange('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={welfare.ratio}
              onChange={(value) => onChange('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>
        <span className="text-sm font-medium text-gray-800">
          ₩ {welfare.annualTotal.toLocaleString()}
        </span>
      </div>
      <div className="flex items-center justify-between">
        <span className="text-sm text-gray-600">1회 결제 기준 금액</span>
        <div className="flex items-center gap-1">
          <CurrencyInput
            value={welfare.singlePaymentThreshold}
            onChange={(value) => onChange('singlePaymentThreshold', value ?? 0)}
            className="w-32 h-8"
          />
        </div>
      </div>
    </div>
  );
}
