'use client';

/**
 * Task G: Disambiguation UX — 8케이스 처리 패널
 * Spec: docs/specs/260225-insuwiki-rag-spec-v2.md § 6
 *
 * Case 1. PRODUCT_AMBIGUOUS   — 담보명 중복: 상품 목록 선택
 * Case 2. VERSION_CONFLICT    — 개정 이력 존재: 버전 선택
 * Case 3. NO_COMPANY          — 비교 기준 없음: 기준 입력
 * Case 4. MISSING_PARAMS      — 고객 조건 미입력: 강제 폼
 * Case 5. INTENT_AMBIGUOUS    — 청구조건 혼재: 의도 선택
 * Case 6. TERM_AMBIGUOUS      — 용어 동음이의: 의미 선택
 * Case 7. DB_NOT_FOUND        — 약관 DB 미등록: 안내 카드
 * Case 8. SALES_STOPPED       — 판매 중단: 조회 허용 + 배지
 */

export type DisambiguationCase =
    | 'PRODUCT_AMBIGUOUS'
    | 'VERSION_CONFLICT'
    | 'NO_COMPANY'
    | 'MISSING_PARAMS'
    | 'INTENT_AMBIGUOUS'
    | 'TERM_AMBIGUOUS'
    | 'DB_NOT_FOUND'
    | 'SALES_STOPPED';

export interface DisambiguationPayload {
    case: DisambiguationCase;
    message: string;
    candidates?: string[];           // Case 1, 2, 5, 6: 선택지 목록
    missingParams?: ParamField[];    // Case 4: 필요한 파라미터
}

export interface ParamField {
    key: string;
    label: string;
    type: 'number' | 'select';
    options?: string[];
}

interface Props {
    payload: DisambiguationPayload;
    onResolve: (resolved: Record<string, string>) => void;
    onDismiss?: () => void;
}

const REQUIRED_PARAMS: ParamField[] = [
    { key: 'age',           label: '나이 (세)',    type: 'number' },
    { key: 'gender',        label: '성별',         type: 'select', options: ['남성', '여성'] },
    { key: 'smokingStatus', label: '흡연 여부',    type: 'select', options: ['비흡연', '흡연'] },
    { key: 'paymentPeriod', label: '납입 기간 (년)', type: 'number' },
];

import { useState } from 'react';

export default function DisambiguationPanel({ payload, onResolve, onDismiss }: Props) {
    const [params, setParams] = useState<Record<string, string>>({});

    // ── Case 7: DB 미등록 안내 ─────────────────────────────────────
    if (payload.case === 'DB_NOT_FOUND') {
        return (
            <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm">
                <div className="font-semibold text-amber-800 mb-1">📂 약관이 등록되어 있지 않습니다</div>
                <p className="text-amber-700">{payload.message}</p>
                <p className="text-amber-600 mt-1">관리자에게 해당 약관 PDF를 Google Drive에 업로드해 달라고 요청하세요.</p>
            </div>
        );
    }

    // ── Case 8: 판매 중단 안내 (조회 계속 허용) ──────────────────────
    if (payload.case === 'SALES_STOPPED') {
        return (
            <div className="rounded-xl border border-gray-200 bg-gray-50 p-4 text-sm">
                <div className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-gray-200 text-gray-600 text-xs font-medium mb-2">
                    🔖 판매 종료 상품
                </div>
                <p className="text-gray-600">{payload.message}</p>
                <p className="text-gray-500 mt-1">판매는 종료됐으나 유지 중인 계약 조회는 계속 가능합니다.</p>
                <button
                    onClick={() => onResolve({ confirmed: 'true' })}
                    className="mt-3 px-4 py-1.5 rounded-lg bg-gray-700 text-white text-xs hover:bg-gray-800 transition-colors"
                >
                    계속 조회하기
                </button>
            </div>
        );
    }

    // ── Case 4: 고객 조건 미입력 — 인라인 폼 ─────────────────────────
    if (payload.case === 'MISSING_PARAMS') {
        const fields = payload.missingParams || REQUIRED_PARAMS;
        return (
            <div className="rounded-xl border border-blue-200 bg-blue-50 p-4 text-sm space-y-3">
                <div className="font-semibold text-blue-800">📋 보험료 조회에 필요한 정보를 입력해 주세요</div>
                {fields.map(f => (
                    <div key={f.key} className="flex flex-col gap-1">
                        <label className="text-gray-600 text-xs font-medium">{f.label}</label>
                        {f.type === 'select' ? (
                            <select
                                className="border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400"
                                onChange={e => setParams(p => ({ ...p, [f.key]: e.target.value }))}
                            >
                                <option value="">선택</option>
                                {f.options?.map(o => <option key={o} value={o}>{o}</option>)}
                            </select>
                        ) : (
                            <input
                                type="number"
                                className="border border-gray-300 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400"
                                onChange={e => setParams(p => ({ ...p, [f.key]: e.target.value }))}
                                placeholder={f.label}
                            />
                        )}
                    </div>
                ))}
                <button
                    onClick={() => onResolve(params)}
                    disabled={fields.some(f => !params[f.key])}
                    className="w-full mt-2 py-2 rounded-xl bg-blue-600 text-white font-medium text-sm hover:bg-blue-700 disabled:opacity-40 transition-colors"
                >
                    조회하기
                </button>
            </div>
        );
    }

    // ── Case 1,2,5,6: 선택지 목록 (라디오 버튼) ──────────────────────
    if (payload.candidates && payload.candidates.length > 0) {
        const [selected, setSelected] = useState('');
        return (
            <div className="rounded-xl border border-gray-200 bg-white p-4 text-sm space-y-3">
                <div className="font-semibold text-gray-800">🔍 {payload.message}</div>
                <div className="space-y-2">
                    {payload.candidates.map((c, i) => (
                        <label key={i} className="flex items-start gap-3 p-2.5 rounded-lg border cursor-pointer hover:border-blue-400 hover:bg-blue-50 transition-all has-[:checked]:border-blue-500 has-[:checked]:bg-blue-50">
                            <input
                                type="radio"
                                name="disambiguation"
                                value={c}
                                className="mt-0.5"
                                onChange={() => setSelected(c)}
                            />
                            <span className="text-gray-700">{c}</span>
                        </label>
                    ))}
                </div>
                <button
                    onClick={() => onResolve({ selected })}
                    disabled={!selected}
                    className="w-full py-2 rounded-xl bg-blue-600 text-white font-medium text-sm hover:bg-blue-700 disabled:opacity-40 transition-colors"
                >
                    이 내용으로 검색
                </button>
            </div>
        );
    }

    // ── Case 3: 비교 기준 없음 ────────────────────────────────────────
    return (
        <div className="rounded-xl border border-gray-200 bg-white p-4 text-sm">
            <div className="font-semibold text-gray-800 mb-2">❓ {payload.message}</div>
            <input
                type="text"
                className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400"
                placeholder="예: 뇌혈관 보장 기준, 보험료 30만원 이하 등"
                onKeyDown={e => {
                    if (e.key === 'Enter') onResolve({ criteria: (e.target as HTMLInputElement).value });
                }}
            />
            <p className="text-gray-400 text-xs mt-1">Enter 키로 검색</p>
        </div>
    );
}
