import React, { useState } from 'react';
import { NumberRow } from '../lottoUtils';
import ConfidenceRing from './ConfidenceRing';

const ReportPanel = ({ report, history, loading, onRefresh, onSelectDrw }) => {
    const [histExpand, setHistExpand] = useState(false);

    return (
        <section className="lotto-panel lotto-panel--wide">
            <div className="lotto-panel__head">
                <div>
                    <p className="lotto-panel__eyebrow">Weekly Report</p>
                    <h3>이번 주 공략 리포트</h3>
                    {report && (
                        <p className="lotto-panel__sub">
                            {report.target_drw_no}회 대상 · {report.based_on_draw}회 기준
                        </p>
                    )}
                </div>
                <div className="lotto-panel__actions">
                    {loading && <span className="lotto-chip">로딩 중</span>}
                    <button className="button ghost small" onClick={onRefresh} disabled={loading}>
                        새로고침
                    </button>
                    {history?.length > 0 && (
                        <button className="button ghost small" onClick={() => setHistExpand((p) => !p)}>
                            지난 리포트 {histExpand ? '▲' : '▼'}
                        </button>
                    )}
                </div>
            </div>

            {/* 지난 리포트 목록 */}
            {histExpand && history?.length > 0 && (
                <div className="lotto-report-history">
                    {history.map((h) => (
                        <button
                            key={h.drw_no}
                            className="button ghost small"
                            onClick={() => { onSelectDrw(h.drw_no); setHistExpand(false); }}
                        >
                            {h.drw_no}회
                        </button>
                    ))}
                </div>
            )}

            {!report && !loading && (
                <p className="lotto-empty">리포트 데이터가 없습니다.</p>
            )}
            {loading && !report && (
                <p className="lotto-empty">불러오는 중...</p>
            )}

            {report && (
                <>
                    {/* 신뢰도 + 패턴 요약 */}
                    <div className="lotto-report-top">
                        <div className="lotto-report-confidence">
                            <ConfidenceRing score={report.confidence_score ?? 0} />
                            <div>
                                <p className="lotto-report-confidence__title">신뢰도 점수</p>
                                <div className="lotto-report-confidence__factors">
                                    {Object.entries(report.confidence_factors ?? {}).map(([k, v]) => (
                                        <div key={k} className="lotto-report-confidence__factor">
                                            <span className="lotto-report-confidence__factor-lbl">
                                                {k === 'data_volume' ? '데이터 충분도'
                                                    : k === 'pattern_consistency' ? '패턴 안정성'
                                                    : k === 'recent_trend' ? '최근 트렌드' : k}
                                            </span>
                                            <div className="lotto-pick__bar">
                                                <span style={{ width: `${v}%` }} />
                                            </div>
                                            <span className="lotto-report-confidence__factor-val">{v}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        </div>

                        <div className="lotto-report-pattern">
                            <p className="lotto-report-pattern__title">최근 패턴</p>
                            <div className="lotto-report-pattern__stats">
                                <div className="lotto-report-pattern__stat">
                                    <span>합계 평균</span>
                                    <strong>{report.recent_pattern?.recent_sum_avg?.toFixed(1) ?? '-'}</strong>
                                </div>
                                <div className="lotto-report-pattern__stat">
                                    <span>홀수 평균</span>
                                    <strong>{report.recent_pattern?.recent_odd_avg?.toFixed(1) ?? '-'}</strong>
                                </div>
                                {(report.recent_pattern?.triple_appear ?? []).length > 0 && (
                                    <div className="lotto-report-pattern__stat">
                                        <span>3회 연속 출현</span>
                                        <NumberRow nums={report.recent_pattern.triple_appear} />
                                    </div>
                                )}
                            </div>
                        </div>
                    </div>

                    {/* 핫 / 콜드 / 오버듀 */}
                    <div className="lotto-analysis__row">
                        <div className="lotto-analysis__group">
                            <p className="lotto-analysis__label">
                                🔥 핫 번호 <span>최근 10회 과출현</span>
                            </p>
                            <NumberRow nums={report.hot_numbers ?? []} />
                        </div>
                        <div className="lotto-analysis__group">
                            <p className="lotto-analysis__label">
                                🧊 콜드 번호 <span>역대 저빈도 10개</span>
                            </p>
                            <NumberRow nums={report.cold_numbers ?? []} />
                        </div>
                        <div className="lotto-analysis__group">
                            <p className="lotto-analysis__label">
                                ⏰ 오버듀 <span>가장 오래 미출현</span>
                            </p>
                            <NumberRow nums={report.overdue_numbers ?? []} />
                        </div>
                    </div>

                    {/* 전략 추천 세트 */}
                    {(report.recommended_sets ?? []).length > 0 && (
                        <div className="lotto-strategy-cards">
                            {report.recommended_sets.map((set, i) => (
                                <div key={i} className="lotto-strategy-card">
                                    <p className="lotto-strategy-card__name">{set.strategy}</p>
                                    <NumberRow nums={set.numbers} />
                                    <p className="lotto-strategy-card__desc">{set.description}</p>
                                </div>
                            ))}
                        </div>
                    )}
                </>
            )}
        </section>
    );
};

export default ReportPanel;
