'use client';

import { useState, useCallback, useMemo } from 'react';
import { Plus, Trash2, AlertTriangle, Info } from 'lucide-react';
import { PageLayout } from '@/components/organisms/PageLayout';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { DatePicker } from '@/components/ui/date-picker';
import { Label } from '@/components/ui/label';
import { CurrencyInput } from '@/components/ui/currency-input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Switch } from '@/components/ui/switch';
import {
  Select, SelectContent, SelectItem, SelectTrigger, SelectValue,
} from '@/components/ui/select';
import {
  Table, TableBody, TableCell, TableHead, TableHeader, TableRow,
} from '@/components/ui/table';

// =============================================
// 옵션 정의
// =============================================

const INSTRUMENT_TYPE_OPTIONS = [
  { value: 'promissory', label: '약속어음' },
  { value: 'exchange', label: '환어음' },
  { value: 'cashierCheck', label: '자기앞수표 (가게수표)' },
  { value: 'currentCheck', label: '당좌수표' },
];

const DIRECTION_OPTIONS = [
  { value: 'received', label: '수취 (받을어음)' },
  { value: 'issued', label: '발행 (지급어음)' },
];

const MEDIUM_OPTIONS = [
  { value: 'electronic', label: '전자' },
  { value: 'paper', label: '지류 (종이)' },
];

const ENDORSEMENT_OPTIONS = [
  { value: 'endorsable', label: '배서 가능' },
  { value: 'nonEndorsable', label: '배서 불가 (배서금지어음)' },
];

// 받을어음 - 어음구분 (엑셀)
const BILL_CATEGORY_OPTIONS = [
  { value: 'commercial', label: '상업어음 (매출채권)' },
  { value: 'other', label: '기타어음 (대여금/미수금)' },
];

// 받을어음 - 결제상태 (어음용)
const RECEIVED_STATUS_OPTIONS = [
  { value: 'stored', label: '보관중' },
  { value: 'endorsed', label: '배서양도' },
  { value: 'discounted', label: '할인' },
  { value: 'collected', label: '추심' },
  { value: 'maturityAlert', label: '만기임박 (7일전)' },
  { value: 'maturityDeposit', label: '만기입금' },
  { value: 'paymentComplete', label: '결제완료' },
  { value: 'renewed', label: '개서 (만기연장)' },
  { value: 'recourse', label: '소구 (배서어음 상환)' },
  { value: 'buyback', label: '환매 (할인어음 부도)' },
  { value: 'dishonored', label: '부도' },
];

// 받을수표 - 결제상태 (수표용: 일람출급이므로 만기/할인/개서/환매 없음)
const RECEIVED_CHECK_STATUS_OPTIONS = [
  { value: 'stored', label: '보관중' },
  { value: 'endorsed', label: '배서양도' },
  { value: 'collected', label: '추심' },
  { value: 'deposited', label: '추심입금' },
  { value: 'paymentComplete', label: '결제완료 (제시입금)' },
  { value: 'recourse', label: '소구 (수표법 제39조)' },
  { value: 'dishonored', label: '부도' },
];

// 지급어음 - 지급상태
const ISSUED_STATUS_OPTIONS = [
  { value: 'stored', label: '보관중' },
  { value: 'maturityAlert', label: '만기임박 (7일전)' },
  { value: 'maturityPayment', label: '만기결제' },
  { value: 'paid', label: '결제완료' },
  { value: 'renewed', label: '개서 (만기연장)' },
  { value: 'dishonored', label: '부도' },
];

// 지급수표 - 지급상태 (수표용)
const ISSUED_CHECK_STATUS_OPTIONS = [
  { value: 'stored', label: '미결제' },
  { value: 'paid', label: '결제완료 (제시출금)' },
  { value: 'dishonored', label: '부도' },
];

// 지급어음 - 결제방법 (엑셀)
const PAYMENT_METHOD_OPTIONS = [
  { value: 'autoTransfer', label: '만기자동이체' },
  { value: 'currentAccount', label: '당좌결제' },
  { value: 'other', label: '기타' },
];

// 부도사유
const DISHONOR_REASON_OPTIONS = [
  { value: 'insufficient_funds', label: '자금부족 (1호 부도)' },
  { value: 'trading_suspension', label: '거래정지처분 (2호 부도)' },
  { value: 'formal_defect', label: '형식불비' },
  { value: 'signature_mismatch', label: '서명/인감 불일치' },
  { value: 'expired', label: '제시기간 경과' },
  { value: 'other', label: '기타' },
];

// 이력 처리구분 (받을어음용 - 어음 생애주기 순)
const HISTORY_TYPE_OPTIONS = [
  { value: 'received', label: '수취' },
  { value: 'endorsement', label: '배서양도' },
  { value: 'splitEndorsement', label: '분할배서' },
  { value: 'collection', label: '추심의뢰' },
  { value: 'collectionDeposit', label: '추심입금' },
  { value: 'discount', label: '할인' },
  { value: 'maturityDeposit', label: '만기입금' },
  { value: 'dishonored', label: '부도' },
  { value: 'recourse', label: '소구' },
  { value: 'buyback', label: '환매' },
  { value: 'renewal', label: '개서' },
  { value: 'other', label: '기타' },
];

// 배서차수 (받을어음) - 지류: 실무상 4차까지, 전자: 법적 최대 20차
const ENDORSEMENT_ORDER_PAPER = [
  { value: '1', label: '1차 (발행인 직접수취)' },
  { value: '2', label: '2차 (1개 업체 경유)' },
  { value: '3', label: '3차 (2개 업체 경유)' },
  { value: '4', label: '4차 (3개 업체 경유)' },
];
const ENDORSEMENT_ORDER_ELECTRONIC = Array.from({ length: 20 }, (_, i) => ({
  value: String(i + 1),
  label: i === 0 ? '1차 (발행인 직접수취)' : `${i + 1}차 (${i}개 업체 경유)`,
}));

// 보관장소
const STORAGE_OPTIONS = [
  { value: 'safe', label: '금고' },
  { value: 'bank', label: '은행 보관' },
  { value: 'other', label: '기타' },
];

// 지급장소 (어음법 제75조 필수 기재사항)
const PAYMENT_PLACE_OPTIONS = [
  { value: 'issuerBank', label: '발행은행 본점' },
  { value: 'issuerBankBranch', label: '발행은행 지점' },
  { value: 'payerAddress', label: '지급인 주소지' },
  { value: 'designatedBank', label: '지정 은행' },
  { value: 'other', label: '기타' },
];

// 수표 지급장소 (수표법 제3조: 지급인은 반드시 은행)
const PAYMENT_PLACE_CHECK_OPTIONS = [
  { value: 'issuerBank', label: '발행은행 본점' },
  { value: 'issuerBankBranch', label: '발행은행 지점' },
  { value: 'designatedBank', label: '지정 은행' },
];

// 추심결과
const COLLECTION_RESULT_OPTIONS = [
  { value: 'success', label: '추심 성공 (입금완료)' },
  { value: 'partial', label: '일부 입금' },
  { value: 'failed', label: '추심 실패 (부도)' },
  { value: 'pending', label: '추심 진행중' },
];

// 소구사유
const RECOURSE_REASON_OPTIONS = [
  { value: 'endorsedDishonor', label: '배서양도 어음 부도' },
  { value: 'discountDishonor', label: '할인 어음 부도 (환매)' },
  { value: 'other', label: '기타' },
];

// 환어음 인수거절 사유
const ACCEPTANCE_REFUSAL_REASON_OPTIONS = [
  { value: 'financialDifficulty', label: '자금 사정 곤란' },
  { value: 'disputeOfClaim', label: '채권 분쟁' },
  { value: 'amountDispute', label: '금액 이의' },
  { value: 'other', label: '기타' },
];

// 개서 사유
const RENEWAL_REASON_OPTIONS = [
  { value: 'maturityExtension', label: '만기일 연장' },
  { value: 'amountChange', label: '금액 변경' },
  { value: 'conditionChange', label: '조건 변경' },
  { value: 'other', label: '기타' },
];

// =============================================
// 타입 정의
// =============================================

interface InstallmentRecord {
  id: string;
  date: string;
  type: string;
  amount: number;
  counterparty: string;
  note: string;
}

interface BillFormData {
  // === 공통 ===
  billNumber: string;
  instrumentType: string;
  direction: string;         // received | issued
  medium: string;            // electronic | paper
  amount: number;
  issueDate: string;
  maturityDate: string;
  note: string;
  // === 전자어음 (조건: medium=electronic) ===
  electronicBillNo: string;
  registrationOrg: string;
  // === 환어음 (조건: instrumentType=exchange) ===
  drawee: string;
  acceptanceStatus: string;
  acceptanceDate: string;
  // === 받을어음 전용 ===
  vendor: string;            // 거래처(발행인)
  billCategory: string;      // 상업어음/기타어음
  issuerBank: string;        // 발행은행
  endorsement: string;       // 배서 가능/불가
  endorsementOrder: string;  // 배서차수 (1차~4차)
  storagePlace: string;      // 보관장소
  receivedStatus: string;    // 결제상태
  isDiscounted: boolean;     // 할인여부
  discountDate: string;
  discountBank: string;
  discountRate: number;
  discountAmount: number;
  // 배서양도 (조건: receivedStatus=endorsed)
  endorsementDate: string;
  endorsee: string;
  endorsementReason: string;
  // 추심 (조건: receivedStatus=collected)
  collectionBank: string;
  collectionRequestDate: string;
  collectionFee: number;
  collectionCompleteDate: string;  // 추심완료일
  collectionResult: string;        // 추심결과
  collectionDepositDate: string;   // 추심입금일
  collectionDepositAmount: number; // 추심입금액(수수료 차감후)
  // === 지급어음 전용 ===
  payee: string;             // 수취인(거래처)
  settlementBank: string;    // 결제은행
  paymentMethod: string;     // 결제방법
  issuedStatus: string;      // 지급상태
  actualPaymentDate: string; // 실제결제일
  // === 공통 ===
  paymentPlace: string;      // 지급장소 (어음법 필수)
  paymentPlaceDetail: string; // 지급장소 상세 (기타 선택 시)
  // === 개서 (공통 조건부: 상태=개서) ===
  renewalDate: string;        // 개서일자
  renewalNewBillNo: string;   // 신어음번호
  renewalReason: string;      // 개서사유
  // === 소구/환매 (받을어음 조건부) ===
  recourseDate: string;          // 소구일자
  recourseAmount: number;        // 소구금액
  recourseTarget: string;        // 소구대상 (배서인/발행인)
  recourseReason: string;        // 소구사유
  buybackDate: string;           // 환매일자
  buybackAmount: number;         // 환매금액
  buybackBank: string;           // 환매요청 은행
  // === 환어음 인수거절 (조건: acceptanceStatus=refused) ===
  acceptanceRefusalDate: string;  // 인수거절일
  acceptanceRefusalReason: string; // 인수거절사유
  // === 공통 조건부 ===
  isSplit: boolean;
  splitCount: number;
  splitAmount: number;
  dishonoredDate: string;
  dishonoredReason: string;
  // 부도 법적 프로세스
  hasProtest: boolean;            // 거절증서 작성 여부
  protestDate: string;            // 거절증서 작성일
  recourseNoticeDate: string;     // 소구 통지일
  recourseNoticeDeadline: string; // 소구 통지 기한 (자동: 부도일+4영업일)
  // === 이력 관리 (받을어음만) ===
  installments: InstallmentRecord[];
  // === 입출금 계좌 ===
  bankAccountInfo: string;
}

const INITIAL_FORM: BillFormData = {
  billNumber: '', instrumentType: 'promissory', direction: 'received',
  medium: 'paper', amount: 0, issueDate: '', maturityDate: '', note: '',
  electronicBillNo: '', registrationOrg: '',
  drawee: '', acceptanceStatus: '', acceptanceDate: '',
  vendor: '', billCategory: 'commercial', issuerBank: '', endorsement: 'endorsable', endorsementOrder: '1',
  storagePlace: '', receivedStatus: 'stored', isDiscounted: false,
  discountDate: '', discountBank: '', discountRate: 0, discountAmount: 0,
  endorsementDate: '', endorsee: '', endorsementReason: '',
  collectionBank: '', collectionRequestDate: '', collectionFee: 0,
  collectionCompleteDate: '', collectionResult: '', collectionDepositDate: '', collectionDepositAmount: 0,
  payee: '', settlementBank: '', paymentMethod: 'autoTransfer',
  issuedStatus: 'stored', actualPaymentDate: '',
  paymentPlace: '', paymentPlaceDetail: '',
  renewalDate: '', renewalNewBillNo: '', renewalReason: '',
  recourseDate: '', recourseAmount: 0, recourseTarget: '', recourseReason: '',
  buybackDate: '', buybackAmount: 0, buybackBank: '',
  acceptanceRefusalDate: '', acceptanceRefusalReason: '',
  isSplit: false, splitCount: 0, splitAmount: 0,
  dishonoredDate: '', dishonoredReason: '',
  hasProtest: false, protestDate: '', recourseNoticeDate: '', recourseNoticeDeadline: '',
  installments: [], bankAccountInfo: '',
};

// =============================================
// 뱃지 컴포넌트
// =============================================

function NewBadge() {
  return <Badge variant="outline" className="ml-2 text-[10px] px-1.5 py-0 bg-orange-50 text-orange-600 border-orange-200">NEW</Badge>;
}
function CondBadge({ label }: { label: string }) {
  return <Badge variant="outline" className="ml-2 text-[10px] px-1.5 py-0 bg-purple-50 text-purple-600 border-purple-200">{label}</Badge>;
}
function RecvBadge() {
  return <Badge variant="outline" className="ml-2 text-[10px] px-1.5 py-0 bg-blue-50 text-blue-600 border-blue-200">받을어음</Badge>;
}
function IssuBadge() {
  return <Badge variant="outline" className="ml-2 text-[10px] px-1.5 py-0 bg-green-50 text-green-600 border-green-200">지급어음</Badge>;
}

// =============================================
// 메인 컴포넌트
// =============================================

export default function BillPrototypePage() {
  const [formData, setFormData] = useState<BillFormData>(INITIAL_FORM);

  const updateField = useCallback(<K extends keyof BillFormData>(field: K, value: BillFormData[K]) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  }, []);

  const isReceived = formData.direction === 'received';
  const isIssued = formData.direction === 'issued';
  // 증권종류 분류
  const isCheck = formData.instrumentType === 'cashierCheck' || formData.instrumentType === 'currentCheck';
  const isBill = !isCheck; // 약속어음 또는 환어음
  const canBeElectronic = formData.instrumentType === 'promissory'; // 전자어음법: 약속어음만

  const currentStatus = isReceived ? formData.receivedStatus : formData.issuedStatus;

  // 조건부 플래그
  const showElectronic = formData.medium === 'electronic';
  const showExchangeBill = formData.instrumentType === 'exchange';
  const showDiscount = isReceived && formData.isDiscounted && isBill; // 수표 할인 불가
  const showEndorsement = isReceived && formData.receivedStatus === 'endorsed';
  const showCollection = isReceived && formData.receivedStatus === 'collected';
  const showDishonored = currentStatus === 'dishonored';
  const showRenewal = currentStatus === 'renewed' && isBill; // 수표 개서 불가
  const showRecourse = isReceived && formData.receivedStatus === 'recourse';
  const showBuyback = isReceived && formData.receivedStatus === 'buyback' && isBill; // 수표 환매 불가
  const showAcceptanceRefusal = showExchangeBill && formData.acceptanceStatus === 'refused';

  // 현재 증권종류에 맞는 상태 옵션
  const receivedStatusOptions = isCheck ? RECEIVED_CHECK_STATUS_OPTIONS : RECEIVED_STATUS_OPTIONS;
  const issuedStatusOptions = isCheck ? ISSUED_CHECK_STATUS_OPTIONS : ISSUED_STATUS_OPTIONS;
  // 현재 증권종류에 맞는 지급장소 옵션
  const paymentPlaceOptions = isCheck ? PAYMENT_PLACE_CHECK_OPTIONS : PAYMENT_PLACE_OPTIONS;

  // 할인 실수령액
  const calcNetReceived = useMemo(() => {
    if (formData.amount > 0 && formData.discountAmount > 0) return formData.amount - formData.discountAmount;
    return 0;
  }, [formData.amount, formData.discountAmount]);

  // 전자어음 여부
  const isElectronic = formData.medium === 'electronic';

  // 이력에서 분할배서 건수 & 금액 합계 계산
  const splitEndorsementStats = useMemo(() => {
    const splits = formData.installments.filter(inst => inst.type === 'splitEndorsement');
    const totalAmount = splits.reduce((sum, inst) => sum + inst.amount, 0);
    return { count: splits.length, totalAmount, remaining: formData.amount - totalAmount };
  }, [formData.installments, formData.amount]);

  // 분할배서 최대 횟수 (전자: 5회 미만=최대4, 지류: 실무상 10)
  const maxSplitCount = isElectronic ? 4 : 10;

  // 이력 관리 핸들러
  const handleAddInstallment = useCallback(() => {
    setFormData(prev => ({
      ...prev,
      installments: [...prev.installments, { id: `inst-${Date.now()}`, date: '', type: 'payment', amount: 0, counterparty: '', note: '' }],
    }));
  }, []);

  const handleRemoveInstallment = useCallback((id: string) => {
    setFormData(prev => ({ ...prev, installments: prev.installments.filter(inst => inst.id !== id) }));
  }, []);

  const handleUpdateInstallment = useCallback((id: string, field: keyof InstallmentRecord, value: string | number) => {
    setFormData(prev => ({
      ...prev,
      installments: prev.installments.map(inst => inst.id === id ? { ...inst, [field]: value } : inst),
    }));
  }, []);

  return (
    <PageLayout>
      {/* 헤더 */}
      <div className="mb-6">
        <h1 className="text-2xl font-bold">어음 등록 (개선안 프로토타입 v8)</h1>
        <p className="text-sm text-muted-foreground mt-1">v7 + 분할/배서차수 관리 + 차수 관리 → &quot;이력 관리&quot; 단일 테이블로 통합</p>
      </div>

      {/* 안내 */}
      <Card className="mb-6 border-blue-200 bg-blue-50">
        <CardContent className="py-3">
          <div className="flex flex-col gap-1.5 text-sm">
            <div className="flex items-center gap-2 text-blue-700">
              <Info className="h-4 w-4 flex-shrink-0" />
              <span>프로토타입입니다. 실제 저장되지 않습니다.</span>
            </div>
            <div className="flex flex-wrap items-center gap-3 ml-6 text-xs text-gray-600">
              <span className="flex items-center gap-1"><NewBadge /> 신규 필드</span>
              <span className="flex items-center gap-1"><CondBadge label="조건부" /> 특정 조건 시 표시</span>
              <span className="flex items-center gap-1"><RecvBadge /> 받을어음 전용</span>
              <span className="flex items-center gap-1"><IssuBadge /> 지급어음 전용</span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* ===== 1. 공통 기본 정보 ===== */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle className="text-lg">기본 정보</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {/* 어음번호 */}
            <div className="space-y-2">
              <Label>어음번호 <span className="text-red-500">*</span></Label>
              <Input value={formData.billNumber} onChange={(e) => updateField('billNumber', e.target.value)} placeholder="자동생성 또는 직접입력" />
            </div>

            {/* 증권종류 */}
            <div className="space-y-2">
              <Label>증권종류 <span className="text-red-500">*</span><NewBadge /></Label>
              <Select value={formData.instrumentType} onValueChange={(v) => {
                updateField('instrumentType', v);
                const isCheckType = v === 'cashierCheck' || v === 'currentCheck';
                // 약속어음 외에는 전자 불가 → 지류로 리셋
                if (v !== 'promissory' && formData.medium === 'electronic') {
                  updateField('medium', 'paper');
                }
                // 수표 전환 시: 만기일, 할인, 개서 관련 필드 리셋
                if (isCheckType) {
                  updateField('maturityDate', '');
                  updateField('isDiscounted', false);
                  // 수표에 없는 상태가 선택되어 있으면 리셋
                  const validCheckRecvStatuses = ['stored', 'endorsed', 'collected', 'deposited', 'paymentComplete', 'recourse', 'dishonored'];
                  const validCheckIssuStatuses = ['stored', 'paid', 'dishonored'];
                  if (!validCheckRecvStatuses.includes(formData.receivedStatus)) updateField('receivedStatus', 'stored');
                  if (!validCheckIssuStatuses.includes(formData.issuedStatus)) updateField('issuedStatus', 'stored');
                  // 수표 지급장소: 주소지 선택되어 있으면 리셋
                  if (formData.paymentPlace === 'payerAddress' || formData.paymentPlace === 'other') updateField('paymentPlace', '');
                }
              }}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {INSTRUMENT_TYPE_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>

            {/* 거래방향 */}
            <div className="space-y-2">
              <Label>거래방향 <span className="text-red-500">*</span></Label>
              <Select value={formData.direction} onValueChange={(v) => {
                updateField('direction', v);
                updateField('receivedStatus', 'stored');
                updateField('issuedStatus', 'stored');
              }}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {DIRECTION_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>

            {/* 전자/지류 */}
            <div className="space-y-2">
              <Label>전자/지류 <span className="text-red-500">*</span><NewBadge />
                {!canBeElectronic && <span className="text-xs text-muted-foreground ml-1">(전자어음법: 약속어음만 전자 가능)</span>}
              </Label>
              <Select value={formData.medium} onValueChange={(v) => {
                updateField('medium', v);
              }} disabled={!canBeElectronic}>
                <SelectTrigger><SelectValue /></SelectTrigger>
                <SelectContent>
                  {MEDIUM_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>

            {/* 거래처 - 라벨 분기 */}
            <div className="space-y-2">
              <Label>
                {isReceived ? '거래처 (발행인)' : '수취인 (거래처)'} <span className="text-red-500">*</span>
              </Label>
              <Select
                value={isReceived ? formData.vendor : formData.payee}
                onValueChange={(v) => updateField(isReceived ? 'vendor' : 'payee', v)}
              >
                <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">삼성전자</SelectItem>
                  <SelectItem value="2">LG전자</SelectItem>
                  <SelectItem value="3">현대건설</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 금액 */}
            <div className="space-y-2">
              <Label>금액 <span className="text-red-500">*</span></Label>
              <CurrencyInput value={formData.amount} onChange={(v) => updateField('amount', v ?? 0)} />
            </div>

            {/* 발행일 */}
            <div className="space-y-2">
              <Label>발행일 <span className="text-red-500">*</span></Label>
              <DatePicker value={formData.issueDate} onChange={(d) => updateField('issueDate', d)} />
            </div>

            {/* 만기일 (수표는 일람출급이므로 만기일 없음 - 수표법 제28조) */}
            {isBill && (
              <div className="space-y-2">
                <Label>만기일 <span className="text-red-500">*</span></Label>
                <DatePicker value={formData.maturityDate} onChange={(d) => updateField('maturityDate', d)} />
              </div>
            )}

            {/* 은행 - 라벨 분기 */}
            <div className="space-y-2">
              <Label>
                {isReceived ? '발행은행' : '결제은행'}<NewBadge />
                {isReceived && showElectronic && <span className="text-red-500 ml-1">* (전자 시 필수)</span>}
              </Label>
              <Input
                value={isReceived ? formData.issuerBank : formData.settlementBank}
                onChange={(e) => updateField(isReceived ? 'issuerBank' : 'settlementBank', e.target.value)}
                placeholder={isReceived ? '예: 국민은행' : '예: 신한은행'}
              />
            </div>

            {/* 지급장소 (어음법 제75조 / 수표법 제2조 필수 기재사항) */}
            <div className="space-y-2">
              <Label>지급장소 <span className="text-red-500">*</span><NewBadge />
                {isCheck && <span className="text-xs text-muted-foreground ml-1">(수표: 은행만)</span>}
              </Label>
              <Select value={formData.paymentPlace} onValueChange={(v) => updateField('paymentPlace', v)}>
                <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                <SelectContent>
                  {paymentPlaceOptions.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                </SelectContent>
              </Select>
            </div>

            {/* 지급장소 상세 (기타 선택 시) */}
            {formData.paymentPlace === 'other' && (
              <div className="space-y-2">
                <Label>지급장소 상세<CondBadge label="기타 시" /></Label>
                <Input value={formData.paymentPlaceDetail} onChange={(e) => updateField('paymentPlaceDetail', e.target.value)} placeholder="지급장소를 직접 입력" />
              </div>
            )}

            {/* ===== 어음구분 (어음만, 수표 제외, 받을/지급 공통) ===== */}
            {isBill && (
              <div className="space-y-2">
                <Label>어음구분<NewBadge /></Label>
                <Select value={formData.billCategory} onValueChange={(v) => updateField('billCategory', v)}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {BILL_CATEGORY_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            )}

            {/* ===== 받을어음 전용 필드 ===== */}
            {isReceived && (
              <>

                {/* 배서 여부 */}
                <div className="space-y-2">
                  <Label>배서 여부<NewBadge /><RecvBadge /></Label>
                  <Select value={formData.endorsement} onValueChange={(v) => updateField('endorsement', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {ENDORSEMENT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                {/* 배서차수 (엑셀 신규) */}
                <div className="space-y-2">
                  <Label>배서차수<NewBadge /><RecvBadge /></Label>
                  <Select value={formData.endorsementOrder} onValueChange={(v) => updateField('endorsementOrder', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {(isElectronic ? ENDORSEMENT_ORDER_ELECTRONIC : ENDORSEMENT_ORDER_PAPER).map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                {/* 보관장소 */}
                <div className="space-y-2">
                  <Label>보관장소<NewBadge /><RecvBadge /></Label>
                  <Select value={formData.storagePlace} onValueChange={(v) => updateField('storagePlace', v)}>
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      {STORAGE_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                {/* 결제상태 */}
                <div className="space-y-2">
                  <Label>결제상태 <span className="text-red-500">*</span><RecvBadge /></Label>
                  <Select value={formData.receivedStatus} onValueChange={(v) => updateField('receivedStatus', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {receivedStatusOptions.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                {/* 할인여부 (인라인 토글) - 수표는 일람출급이므로 할인 불가 */}
                {isBill && (
                  <div className="space-y-2">
                    <Label>할인여부<NewBadge /><RecvBadge /></Label>
                    <div className="h-10 flex items-center gap-3 px-3 border rounded-md bg-gray-50">
                      <Switch checked={formData.isDiscounted} onCheckedChange={(c) => {
                        updateField('isDiscounted', c);
                        if (c) updateField('receivedStatus', 'discounted');
                      }} />
                      <span className="text-sm">{formData.isDiscounted ? '할인 적용' : '미적용'}</span>
                    </div>
                  </div>
                )}
              </>
            )}

            {/* ===== 지급어음 전용 필드 ===== */}
            {isIssued && (
              <>
                {/* 결제방법 */}
                <div className="space-y-2">
                  <Label>결제방법<NewBadge /><IssuBadge /></Label>
                  <Select value={formData.paymentMethod} onValueChange={(v) => updateField('paymentMethod', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {PAYMENT_METHOD_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                {/* 지급상태 */}
                <div className="space-y-2">
                  <Label>지급상태 <span className="text-red-500">*</span><IssuBadge /></Label>
                  <Select value={formData.issuedStatus} onValueChange={(v) => updateField('issuedStatus', v)}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      {issuedStatusOptions.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>

                {/* 실제결제일 */}
                <div className="space-y-2">
                  <Label>실제결제일<NewBadge /><IssuBadge /></Label>
                  <DatePicker value={formData.actualPaymentDate} onChange={(d) => updateField('actualPaymentDate', d)} />
                </div>
              </>
            )}

            {/* 입금/출금 계좌 (공통) */}
            <div className="space-y-2">
              <Label>입금/출금 계좌<NewBadge /></Label>
              <Select value={formData.bankAccountInfo} onValueChange={(v) => updateField('bankAccountInfo', v)}>
                <SelectTrigger><SelectValue placeholder="계좌 선택" /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="1">국민은행 123-456-789 (보통예금)</SelectItem>
                  <SelectItem value="2">신한은행 987-654-321 (당좌예금)</SelectItem>
                </SelectContent>
              </Select>
            </div>

            {/* 비고 */}
            <div className="space-y-2 lg:col-span-2">
              <Label>비고</Label>
              <Input value={formData.note} onChange={(e) => updateField('note', e.target.value)} placeholder="비고를 입력해주세요" />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* ===== 2. 전자어음 정보 (조건: 전자) ===== */}
      {showElectronic && (
        <Card className="mb-6 border-purple-200">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">전자어음 정보<CondBadge label="전자 선택 시" /></CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label>전자어음 관리번호<NewBadge /></Label>
                <Input value={formData.electronicBillNo} onChange={(e) => updateField('electronicBillNo', e.target.value)} placeholder="전자어음시스템 발급번호" />
              </div>
              <div className="space-y-2">
                <Label>등록기관<NewBadge /></Label>
                <Select value={formData.registrationOrg} onValueChange={(v) => updateField('registrationOrg', v)}>
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="kftc">금융결제원</SelectItem>
                    <SelectItem value="bank">거래은행</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 3. 환어음 정보 (조건: 환어음) ===== */}
      {showExchangeBill && (
        <Card className="mb-6 border-purple-200">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">환어음 정보<CondBadge label="환어음 선택 시" /></CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label>지급인 (Drawee) <span className="text-red-500">*</span><NewBadge /></Label>
                  <Input value={formData.drawee} onChange={(e) => updateField('drawee', e.target.value)} placeholder="지급 의무자" />
                </div>
                <div className="space-y-2">
                  <Label>인수 여부<NewBadge /></Label>
                  <Select value={formData.acceptanceStatus} onValueChange={(v) => updateField('acceptanceStatus', v)}>
                    <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="accepted">인수 완료</SelectItem>
                      <SelectItem value="pending">인수 대기</SelectItem>
                      <SelectItem value="refused">인수 거절</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>{formData.acceptanceStatus === 'refused' ? '인수거절일' : '인수일자'}<NewBadge /></Label>
                  <DatePicker value={formData.acceptanceStatus === 'refused' ? formData.acceptanceRefusalDate : formData.acceptanceDate} onChange={(d) => updateField(formData.acceptanceStatus === 'refused' ? 'acceptanceRefusalDate' : 'acceptanceDate', d)} />
                </div>
              </div>
              {/* 인수거절 시 추가 필드 */}
              {showAcceptanceRefusal && (
                <div className="border-t pt-4">
                  <div className="flex items-center gap-2 text-xs text-red-600 bg-red-50 border border-red-200 rounded-md px-3 py-2 mb-4">
                    <AlertTriangle className="h-3.5 w-3.5 flex-shrink-0" />
                    <span>인수거절 시 만기 전 소구권 행사 가능 (어음법 제43조). 거절증서 작성이 필요할 수 있습니다.</span>
                  </div>
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div className="space-y-2">
                      <Label>인수거절 사유<NewBadge /></Label>
                      <Select value={formData.acceptanceRefusalReason} onValueChange={(v) => updateField('acceptanceRefusalReason', v)}>
                        <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                        <SelectContent>
                          {ACCEPTANCE_REFUSAL_REASON_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                        </SelectContent>
                      </Select>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 4. 할인 정보 (받을어음 + 할인여부 ON) ===== */}
      {showDiscount && (
        <Card className="mb-6 border-purple-200">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">할인 정보<CondBadge label="할인여부 ON 시" /><RecvBadge /></CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label>할인일자 <span className="text-red-500">*</span></Label>
                <DatePicker value={formData.discountDate} onChange={(d) => updateField('discountDate', d)} />
              </div>
              <div className="space-y-2">
                <Label>할인처 (은행) <span className="text-red-500">*</span></Label>
                <Input value={formData.discountBank} onChange={(e) => updateField('discountBank', e.target.value)} placeholder="예: 국민은행 강남지점" />
              </div>
              <div className="space-y-2">
                <Label>할인율 (%)</Label>
                <Input type="number" step="0.01" min={0} max={100} value={formData.discountRate || ''} onChange={(e) => {
                  const rate = parseFloat(e.target.value) || 0;
                  updateField('discountRate', rate);
                  if (formData.amount > 0 && rate > 0) updateField('discountAmount', Math.round(formData.amount * rate / 100));
                }} placeholder="예: 3.5" />
              </div>
              <div className="space-y-2">
                <Label>할인금액</Label>
                <CurrencyInput value={formData.discountAmount} onChange={(v) => updateField('discountAmount', v ?? 0)} />
              </div>
              <div className="space-y-2">
                <Label>실수령액 (자동계산)</Label>
                <div className="h-10 flex items-center px-3 border rounded-md bg-gray-50 text-sm font-semibold">
                  {calcNetReceived > 0
                    ? <span className="text-green-700">₩ {calcNetReceived.toLocaleString()}</span>
                    : <span className="text-gray-400">어음금액 - 할인금액</span>}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 5. 배서양도 정보 (받을어음 + 결제상태=배서양도) ===== */}
      {showEndorsement && (
        <Card className="mb-6 border-purple-200">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">배서양도 정보<CondBadge label="결제상태=배서양도 시" /><RecvBadge /></CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label>배서일자 <span className="text-red-500">*</span></Label>
                <DatePicker value={formData.endorsementDate} onChange={(d) => updateField('endorsementDate', d)} />
              </div>
              <div className="space-y-2">
                <Label>피배서인 (양수인) <span className="text-red-500">*</span></Label>
                <Input value={formData.endorsee} onChange={(e) => updateField('endorsee', e.target.value)} placeholder="어음을 넘겨받는 자" />
              </div>
              <div className="space-y-2">
                <Label>배서 사유</Label>
                <Select value={formData.endorsementReason} onValueChange={(v) => updateField('endorsementReason', v)}>
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="payment">대금결제</SelectItem>
                    <SelectItem value="guarantee">담보제공</SelectItem>
                    <SelectItem value="collection">추심위임</SelectItem>
                    <SelectItem value="other">기타</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 6. 추심 정보 (받을어음 + 결제상태=추심) ===== */}
      {showCollection && (
        <Card className="mb-6 border-purple-200">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2">추심 정보<CondBadge label="결제상태=추심 시" /><RecvBadge /></CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {/* 추심 의뢰 */}
              <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide">추심 의뢰</p>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div className="space-y-2">
                  <Label>추심은행 <span className="text-red-500">*</span></Label>
                  <Input value={formData.collectionBank} onChange={(e) => updateField('collectionBank', e.target.value)} placeholder="추심 의뢰 은행" />
                </div>
                <div className="space-y-2">
                  <Label>추심의뢰일 <span className="text-red-500">*</span></Label>
                  <DatePicker value={formData.collectionRequestDate} onChange={(d) => updateField('collectionRequestDate', d)} />
                </div>
                <div className="space-y-2">
                  <Label>추심수수료</Label>
                  <CurrencyInput value={formData.collectionFee} onChange={(v) => updateField('collectionFee', v ?? 0)} />
                </div>
              </div>
              {/* 추심 결과 */}
              <div className="border-t pt-4">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-4">추심 결과</p>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                  <div className="space-y-2">
                    <Label>추심결과<NewBadge /></Label>
                    <Select value={formData.collectionResult} onValueChange={(v) => updateField('collectionResult', v)}>
                      <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                      <SelectContent>
                        {COLLECTION_RESULT_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                      </SelectContent>
                    </Select>
                  </div>
                  <div className="space-y-2">
                    <Label>추심완료일<NewBadge /></Label>
                    <DatePicker value={formData.collectionCompleteDate} onChange={(d) => updateField('collectionCompleteDate', d)} />
                  </div>
                  <div className="space-y-2">
                    <Label>추심입금일<NewBadge /></Label>
                    <DatePicker value={formData.collectionDepositDate} onChange={(d) => updateField('collectionDepositDate', d)} />
                  </div>
                  <div className="space-y-2">
                    <Label>추심입금액 (수수료 차감후)<NewBadge /></Label>
                    <CurrencyInput value={formData.collectionDepositAmount} onChange={(v) => updateField('collectionDepositAmount', v ?? 0)} />
                  </div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 7. 이력 관리 (받을어음 전용) ===== */}
      {isReceived && (
        <Card className="mb-6">
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-lg flex items-center gap-2">이력 관리<NewBadge /><RecvBadge /></CardTitle>
            <Button variant="outline" size="sm" onClick={handleAddInstallment} className="text-orange-500 border-orange-300 hover:bg-orange-50">
              <Plus className="h-4 w-4 mr-1" />추가
            </Button>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              {/* 분할배서 토글 + 요약 */}
              <div className="flex flex-col gap-2">
                <div className="flex items-center gap-3">
                  <Switch
                    checked={formData.isSplit}
                    onCheckedChange={(c) => updateField('isSplit', c)}
                  />
                  <Label>분할배서 허용</Label>
                  {formData.isSplit && (
                    <Badge variant="outline" className="text-xs text-amber-600 border-amber-300 bg-amber-50">
                      최대 {maxSplitCount}회
                    </Badge>
                  )}
                </div>
                {formData.isSplit && isElectronic && (
                  <div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 border border-amber-200 rounded-md px-3 py-2">
                    <AlertTriangle className="h-3.5 w-3.5 flex-shrink-0" />
                    <span>전자어음 분할배서: 최초 배서인에 한해 5회 미만 가능 (전자어음법 제6조)</span>
                  </div>
                )}
                {/* 분할배서 잔액 요약 */}
                {formData.isSplit && splitEndorsementStats.count > 0 && (
                  <div className="flex items-center gap-4 text-sm bg-gray-50 rounded-md px-3 py-2">
                    <span className="text-muted-foreground">원금액:</span>
                    <span className="font-semibold">₩ {formData.amount.toLocaleString()}</span>
                    <span className="text-muted-foreground">| 분할배서 합계:</span>
                    <span className="font-semibold text-blue-600">₩ {splitEndorsementStats.totalAmount.toLocaleString()}</span>
                    <span className="text-muted-foreground">| 잔액:</span>
                    <span className={`font-semibold ${splitEndorsementStats.remaining < 0 ? 'text-red-600' : 'text-green-600'}`}>
                      ₩ {splitEndorsementStats.remaining.toLocaleString()}
                    </span>
                    {splitEndorsementStats.remaining < 0 && (
                      <span className="text-red-500 text-xs flex items-center gap-1"><AlertTriangle className="h-3 w-3" />금액 초과</span>
                    )}
                  </div>
                )}
              </div>

              {/* 이력 테이블 */}
              <div className="overflow-x-auto">
                <Table>
                  <TableHeader>
                    <TableRow>
                      <TableHead className="w-[50px]">No</TableHead>
                      <TableHead className="min-w-[130px]">일자</TableHead>
                      <TableHead className="min-w-[130px]">처리구분</TableHead>
                      <TableHead className="min-w-[120px]">금액</TableHead>
                      <TableHead className="min-w-[120px]">상대처</TableHead>
                      <TableHead className="min-w-[120px]">비고</TableHead>
                      <TableHead className="w-[60px]">삭제</TableHead>
                    </TableRow>
                  </TableHeader>
                  <TableBody>
                    {formData.installments.length === 0 ? (
                      <TableRow>
                        <TableCell colSpan={7} className="text-center text-gray-500 py-8">등록된 이력이 없습니다</TableCell>
                      </TableRow>
                    ) : formData.installments.map((inst, idx) => (
                      <TableRow key={inst.id} className={inst.type === 'splitEndorsement' ? 'bg-amber-50/50' : ''}>
                        <TableCell className="text-center">{idx + 1}</TableCell>
                        <TableCell><DatePicker value={inst.date} onChange={(d) => handleUpdateInstallment(inst.id, 'date', d)} size="sm" /></TableCell>
                        <TableCell>
                          <Select value={inst.type} onValueChange={(v) => handleUpdateInstallment(inst.id, 'type', v)}>
                            <SelectTrigger className="h-8 text-sm"><SelectValue /></SelectTrigger>
                            <SelectContent>
                              {HISTORY_TYPE_OPTIONS
                                .filter(o => {
                                  // 분할배서는 토글 ON일 때만 선택 가능
                                  if (o.value === 'splitEndorsement' && !formData.isSplit) return false;
                                  return true;
                                })
                                .map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)
                              }
                            </SelectContent>
                          </Select>
                        </TableCell>
                        <TableCell><CurrencyInput value={inst.amount} onChange={(v) => handleUpdateInstallment(inst.id, 'amount', v ?? 0)} className="h-8 text-sm" /></TableCell>
                        <TableCell><Input value={inst.counterparty} onChange={(e) => handleUpdateInstallment(inst.id, 'counterparty', e.target.value)} placeholder="거래처/은행" className="h-8 text-sm" /></TableCell>
                        <TableCell><Input value={inst.note} onChange={(e) => handleUpdateInstallment(inst.id, 'note', e.target.value)} className="h-8 text-sm" /></TableCell>
                        <TableCell>
                          <Button variant="ghost" size="icon" className="h-8 w-8 text-red-500 hover:text-red-600 hover:bg-red-50" onClick={() => handleRemoveInstallment(inst.id)}>
                            <Trash2 className="h-4 w-4" />
                          </Button>
                        </TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 8. 개서 정보 (공통, 상태=개서 시) ===== */}
      {showRenewal && (
        <Card className="mb-6 border-amber-200 bg-amber-50/30">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2 text-amber-700">
              개서 정보<CondBadge label="상태=개서 시" /><Badge variant="outline" className="text-xs border-amber-400 text-amber-700 bg-amber-50">만기연장</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label>개서일자 <span className="text-red-500">*</span></Label>
                <DatePicker value={formData.renewalDate} onChange={(d) => updateField('renewalDate', d)} />
              </div>
              <div className="space-y-2">
                <Label>신어음번호</Label>
                <Input value={formData.renewalNewBillNo} onChange={(e) => updateField('renewalNewBillNo', e.target.value)} placeholder="교체 발행된 신어음 번호" />
              </div>
              <div className="space-y-2">
                <Label>개서 사유 <span className="text-red-500">*</span></Label>
                <Select value={formData.renewalReason} onValueChange={(v) => updateField('renewalReason', v)}>
                  <SelectTrigger><SelectValue placeholder="사유 선택" /></SelectTrigger>
                  <SelectContent>
                    {RENEWAL_REASON_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 9. 소구 정보 (받을어음, 상태=소구 시) ===== */}
      {showRecourse && (
        <Card className="mb-6 border-orange-200 bg-orange-50/30">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2 text-orange-700">
              소구 (상환) 정보<CondBadge label="상태=소구 시" /><RecvBadge /><NewBadge />
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-xs text-muted-foreground mb-4">배서양도한 어음이 부도나 피배서인이 소구권을 행사하여 상환을 요구한 경우</p>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
              <div className="space-y-2">
                <Label>소구일자 <span className="text-red-500">*</span></Label>
                <DatePicker value={formData.recourseDate} onChange={(d) => updateField('recourseDate', d)} />
              </div>
              <div className="space-y-2">
                <Label>소구금액 <span className="text-red-500">*</span></Label>
                <CurrencyInput value={formData.recourseAmount} onChange={(v) => updateField('recourseAmount', v ?? 0)} />
              </div>
              <div className="space-y-2">
                <Label>소구대상 (청구인)</Label>
                <Input value={formData.recourseTarget} onChange={(e) => updateField('recourseTarget', e.target.value)} placeholder="피배서인(양수인)명" />
              </div>
              <div className="space-y-2">
                <Label>소구사유</Label>
                <Select value={formData.recourseReason} onValueChange={(v) => updateField('recourseReason', v)}>
                  <SelectTrigger><SelectValue placeholder="선택" /></SelectTrigger>
                  <SelectContent>
                    {RECOURSE_REASON_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 10. 환매 정보 (받을어음, 상태=환매 시) ===== */}
      {showBuyback && (
        <Card className="mb-6 border-orange-200 bg-orange-50/30">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2 text-orange-700">
              환매 정보<CondBadge label="상태=환매 시" /><RecvBadge /><NewBadge />
            </CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-xs text-muted-foreground mb-4">할인한 어음이 부도나 금융기관이 할인 의뢰인에게 어음금액을 청구(환매)한 경우</p>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label>환매일자 <span className="text-red-500">*</span></Label>
                <DatePicker value={formData.buybackDate} onChange={(d) => updateField('buybackDate', d)} />
              </div>
              <div className="space-y-2">
                <Label>환매금액 <span className="text-red-500">*</span></Label>
                <CurrencyInput value={formData.buybackAmount} onChange={(v) => updateField('buybackAmount', v ?? 0)} />
              </div>
              <div className="space-y-2">
                <Label>환매요청 은행</Label>
                <Input value={formData.buybackBank} onChange={(e) => updateField('buybackBank', e.target.value)} placeholder="환매 청구 금융기관" />
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* ===== 11. 부도 정보 (공통, 상태=부도 시) ===== */}
      {showDishonored && (
        <Card className="mb-6 border-red-200 bg-red-50/30">
          <CardHeader>
            <CardTitle className="text-lg flex items-center gap-2 text-red-700">
              부도 정보<CondBadge label="상태=부도 시" /><Badge variant="destructive" className="text-xs">부도</Badge>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-4">
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div className="space-y-2">
                  <Label>부도일자 <span className="text-red-500">*</span></Label>
                  <DatePicker value={formData.dishonoredDate} onChange={(d) => {
                    updateField('dishonoredDate', d);
                    if (d) {
                      const dt = new Date(d);
                      dt.setDate(dt.getDate() + 6);
                      updateField('recourseNoticeDeadline', dt.toISOString().split('T')[0]);
                    }
                  }} />
                </div>
                <div className="space-y-2">
                  <Label>부도사유 <span className="text-red-500">*</span></Label>
                  <Select value={formData.dishonoredReason} onValueChange={(v) => updateField('dishonoredReason', v)}>
                    <SelectTrigger><SelectValue placeholder="사유 선택" /></SelectTrigger>
                    <SelectContent>
                      {DISHONOR_REASON_OPTIONS.map(o => <SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>)}
                    </SelectContent>
                  </Select>
                </div>
              </div>
              {/* 법적 프로세스 */}
              <div className="border-t pt-4">
                <p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-4">법적 프로세스 (어음법 제44조·제45조)</p>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                  <div className="space-y-2">
                    <Label>거절증서 작성<NewBadge /></Label>
                    <div className="h-10 flex items-center gap-3 px-3 border rounded-md bg-gray-50">
                      <Switch checked={formData.hasProtest} onCheckedChange={(c) => updateField('hasProtest', c)} />
                      <span className="text-sm">{formData.hasProtest ? '작성 완료' : '미작성'}</span>
                    </div>
                  </div>
                  {formData.hasProtest && (
                    <div className="space-y-2">
                      <Label>거절증서 작성일<NewBadge /></Label>
                      <DatePicker value={formData.protestDate} onChange={(d) => updateField('protestDate', d)} />
                    </div>
                  )}
                  <div className="space-y-2">
                    <Label>소구 통지일<NewBadge /></Label>
                    <DatePicker value={formData.recourseNoticeDate} onChange={(d) => updateField('recourseNoticeDate', d)} />
                  </div>
                  <div className="space-y-2">
                    <Label>통지 기한 (자동: 부도일+4영업일)<NewBadge /></Label>
                    <div className="h-10 flex items-center px-3 border rounded-md bg-gray-50 text-sm">
                      {formData.recourseNoticeDeadline ? (
                        <span className={
                          formData.recourseNoticeDate && formData.recourseNoticeDate <= formData.recourseNoticeDeadline
                            ? 'text-green-700' : 'text-red-600 font-medium'
                        }>
                          {formData.recourseNoticeDeadline}
                          {formData.recourseNoticeDate && formData.recourseNoticeDate > formData.recourseNoticeDeadline && ' (기한 초과!)'}
                        </span>
                      ) : <span className="text-gray-400">부도일자 입력 시 자동계산</span>}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* (기존 "차수 관리" → "이력 관리"로 통합 완료, 제거) */}

      {/* ===== 10. 조건부 필드 가이드 ===== */}
      <Card className="border-gray-300 bg-gray-50">
        <CardHeader>
          <CardTitle className="text-lg">조건부 필드 가이드 (실무자 확인용)</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3 text-sm">
            <p className="text-gray-600 mb-4">거래방향, 상태 등을 변경하면 관련 섹션이 자동으로 나타납니다.</p>
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[220px]">조건</TableHead>
                  <TableHead className="w-[150px]">섹션</TableHead>
                  <TableHead>필드</TableHead>
                  <TableHead className="w-[80px]">현재</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                <TableRow className={isReceived ? 'bg-blue-50' : ''}>
                  <TableCell className="font-medium">거래방향 = 받을어음</TableCell>
                  <TableCell>받을어음 전용 필드</TableCell>
                  <TableCell>어음구분, 배서여부, 배서차수, 보관장소, 결제상태, 할인여부, 이력관리</TableCell>
                  <TableCell>{isReceived ? <Badge className="bg-blue-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={isIssued ? 'bg-green-50' : ''}>
                  <TableCell className="font-medium">거래방향 = 지급어음</TableCell>
                  <TableCell>지급어음 전용 필드</TableCell>
                  <TableCell>결제방법, 지급상태, 실제결제일</TableCell>
                  <TableCell>{isIssued ? <Badge className="bg-green-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={isCheck ? 'bg-yellow-50' : ''}>
                  <TableCell className="font-medium">증권종류 = 수표</TableCell>
                  <TableCell>수표 제한</TableCell>
                  <TableCell>만기일 숨김, 전자 불가(지류 고정), 할인/개서/환매 불가, 전용 상태 옵션, 지급장소 은행만</TableCell>
                  <TableCell>{isCheck ? <Badge className="bg-yellow-600 text-xs">적용중</Badge> : <span className="text-gray-400">해당없음</span>}</TableCell>
                </TableRow>
                <TableRow className={showElectronic ? 'bg-purple-50' : ''}>
                  <TableCell className="font-medium">전자/지류 = 전자 (약속어음만)</TableCell>
                  <TableCell>전자어음 정보</TableCell>
                  <TableCell>전자어음관리번호, 등록기관</TableCell>
                  <TableCell>{showElectronic ? <Badge className="bg-purple-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showExchangeBill ? 'bg-purple-50' : ''}>
                  <TableCell className="font-medium">증권종류 = 환어음</TableCell>
                  <TableCell>환어음 정보</TableCell>
                  <TableCell>지급인, 인수여부, 인수일자</TableCell>
                  <TableCell>{showExchangeBill ? <Badge className="bg-purple-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showDiscount ? 'bg-purple-50' : ''}>
                  <TableCell className="font-medium">할인여부 ON (받을어음)</TableCell>
                  <TableCell>할인 정보</TableCell>
                  <TableCell>할인일자, 할인처, 할인율, 할인금액, 실수령액(자동)</TableCell>
                  <TableCell>{showDiscount ? <Badge className="bg-purple-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showEndorsement ? 'bg-purple-50' : ''}>
                  <TableCell className="font-medium">결제상태 = 배서양도</TableCell>
                  <TableCell>배서양도 정보</TableCell>
                  <TableCell>배서일자, 피배서인, 배서사유</TableCell>
                  <TableCell>{showEndorsement ? <Badge className="bg-purple-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showCollection ? 'bg-purple-50' : ''}>
                  <TableCell className="font-medium">결제상태 = 추심</TableCell>
                  <TableCell>추심 정보</TableCell>
                  <TableCell>추심의뢰(은행/의뢰일/수수료) + 추심결과(결과/완료일/입금일/입금액)</TableCell>
                  <TableCell>{showCollection ? <Badge className="bg-purple-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showRecourse ? 'bg-orange-50' : ''}>
                  <TableCell className="font-medium">결제상태 = 소구 (받을어음)</TableCell>
                  <TableCell>소구(상환) 정보</TableCell>
                  <TableCell>소구일자, 소구금액, 소구대상, 소구사유</TableCell>
                  <TableCell>{showRecourse ? <Badge className="bg-orange-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showBuyback ? 'bg-orange-50' : ''}>
                  <TableCell className="font-medium">결제상태 = 환매 (받을어음)</TableCell>
                  <TableCell>환매 정보</TableCell>
                  <TableCell>환매일자, 환매금액, 환매요청 은행</TableCell>
                  <TableCell>{showBuyback ? <Badge className="bg-orange-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showRenewal ? 'bg-amber-50' : ''}>
                  <TableCell className="font-medium">상태 = 개서 (공통)</TableCell>
                  <TableCell>개서 정보</TableCell>
                  <TableCell>개서일자, 신어음번호, 개서사유</TableCell>
                  <TableCell>{showRenewal ? <Badge className="bg-amber-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showDishonored ? 'bg-red-50' : ''}>
                  <TableCell className="font-medium">상태 = 부도 (공통)</TableCell>
                  <TableCell>부도 정보 + 법적 프로세스</TableCell>
                  <TableCell>부도일자, 부도사유, 거절증서 작성, 소구통지일, 통지기한(자동)</TableCell>
                  <TableCell>{showDishonored ? <Badge variant="destructive" className="text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={showAcceptanceRefusal ? 'bg-red-50' : ''}>
                  <TableCell className="font-medium">환어음 인수 = 거절</TableCell>
                  <TableCell>인수거절 상세</TableCell>
                  <TableCell>인수거절일, 인수거절사유, 소구권 안내</TableCell>
                  <TableCell>{showAcceptanceRefusal ? <Badge variant="destructive" className="text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow className={formData.isSplit && isReceived ? 'bg-orange-50' : ''}>
                  <TableCell className="font-medium">분할배서 토글 ON (받을어음)</TableCell>
                  <TableCell>분할배서 허용</TableCell>
                  <TableCell>이력에서 &quot;분할배서&quot; 처리구분 선택 가능 + 잔액 자동계산 — 전자: 최대4회, 지류: 실무10회</TableCell>
                  <TableCell>{formData.isSplit && isReceived ? <Badge className="bg-orange-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
                <TableRow>
                  <TableCell className="font-medium">지급장소 = 기타</TableCell>
                  <TableCell>지급장소 상세</TableCell>
                  <TableCell>지급장소 직접 입력 필드</TableCell>
                  <TableCell>{formData.paymentPlace === 'other' ? <Badge className="bg-purple-600 text-xs">표시중</Badge> : <span className="text-gray-400">숨김</span>}</TableCell>
                </TableRow>
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 하단 버튼 */}
      <div className="flex items-center justify-between mt-6 pt-4 border-t">
        <Button variant="outline">취소</Button>
        <Button className="bg-blue-600 hover:bg-blue-700" onClick={() => alert('프로토타입입니다. 실제 저장되지 않습니다.')}>
          등록 (데모)
        </Button>
      </div>
    </PageLayout>
  );
}
