import React, { useEffect, useMemo, useState } from 'react';
import { deleteHistory, getHistory, getLatest, recommend } from '../../api';

const fmtKST = (value) => value?.replace('T', ' ') ?? '';

const ballClass = (n) => {
    if (n <= 10) return 'lotto-ball range-a';
    if (n <= 20) return 'lotto-ball range-b';
    if (n <= 30) return 'lotto-ball range-c';
    if (n <= 40) return 'lotto-ball range-d';
    return 'lotto-ball range-e';
};

const Ball = ({ n }) => <span className={ballClass(n)}>{n}</span>;

const NumberRow = ({ nums }) => (
    <div className="lotto-row">
        {nums.map((n) => (
            <Ball key={n} n={n} />
        ))}
    </div>
);

export default function Functions() {
    const [latest, setLatest] = useState(null);
    const [params, setParams] = useState({
        recent_window: 200,
        recent_weight: 2.0,
        avoid_recent_k: 5,
    });
    const presets = useMemo(
        () => [
            { name: '기본', recent_window: 200, recent_weight: 2.0, avoid_recent_k: 5 },
            { name: '최근 가중치↑', recent_window: 100, recent_weight: 3.0, avoid_recent_k: 10 },
            { name: '안전(분산)', recent_window: 300, recent_weight: 1.6, avoid_recent_k: 8 },
            { name: '공격(최근)', recent_window: 80, recent_weight: 3.5, avoid_recent_k: 12 },
        ],
        []
    );

    const [result, setResult] = useState(null);
    const [history, setHistory] = useState([]);
    const [loading, setLoading] = useState({
        latest: false,
        recommend: false,
        history: false,
    });
    const [error, setError] = useState('');

    const refreshLatest = async () => {
        setLoading((s) => ({ ...s, latest: true }));
        setError('');
        try {
            const data = await getLatest();
            setLatest(data);
        } catch (e) {
            setError(e?.message ?? String(e));
        } finally {
            setLoading((s) => ({ ...s, latest: false }));
        }
    };

    const refreshHistory = async () => {
        setLoading((s) => ({ ...s, history: true }));
        setError('');
        try {
            const data = await getHistory(30);
            setHistory(data.items ?? []);
        } catch (e) {
            setError(e?.message ?? String(e));
        } finally {
            setLoading((s) => ({ ...s, history: false }));
        }
    };

    const onRecommend = async () => {
        setLoading((s) => ({ ...s, recommend: true }));
        setError('');
        try {
            const data = await recommend(params);
            setResult(data);
            await refreshHistory();
        } catch (e) {
            setError(e?.message ?? String(e));
        } finally {
            setLoading((s) => ({ ...s, recommend: false }));
        }
    };

    const onDelete = async (id) => {
        const ok = confirm(`히스토리 #${id}를 삭제할까요?`);
        if (!ok) return;

        setError('');
        try {
            await deleteHistory(id);
            setHistory((prev) => prev.filter((item) => item.id !== id));
        } catch (e) {
            setError(e?.message ?? String(e));
        }
    };

    const copyNumbers = async (nums) => {
        const text = nums.join(', ');
        try {
            await navigator.clipboard.writeText(text);
            alert(`복사 완료: ${text}`);
        } catch {
            prompt('복사해서 사용하세요:', text);
        }
    };

    useEffect(() => {
        refreshLatest();
        refreshHistory();
    }, []);

    return (
        <div className="lotto-functions">
            {error ? (
                <div className="lotto-alert">
                    <div>
                        <p className="lotto-alert__title">오류</p>
                        <p className="lotto-alert__message">{error}</p>
                    </div>
                    <button className="button ghost small" onClick={() => setError('')}>
                        닫기
                    </button>
                </div>
            ) : null}

            <div className="lotto-grid">
                <section className="lotto-panel">
                    <div className="lotto-panel__head">
                        <div>
                            <p className="lotto-panel__eyebrow">Latest Draw</p>
                            <h3>최신 회차</h3>
                            <p className="lotto-panel__sub">
                                최신 회차와 번호를 빠르게 확인할 수 있습니다.
                            </p>
                        </div>
                        <div className="lotto-panel__actions">
                            {loading.latest ? <span className="lotto-chip">로딩 중</span> : null}
                            <button
                                className="button ghost small"
                                onClick={refreshLatest}
                                disabled={loading.latest}
                            >
                                새로고침
                            </button>
                        </div>
                    </div>

                    {latest ? (
                        <>
                            <div className="lotto-meta">
                                <div>
                                    <p className="lotto-meta__title">{latest.drawNo}회</p>
                                    <p className="lotto-meta__date">{latest.date}</p>
                                </div>
                                <button
                                    className="button small"
                                    onClick={() => copyNumbers(latest.numbers)}
                                >
                                    번호 복사
                                </button>
                            </div>
                            <NumberRow nums={latest.numbers} />
                            <p className="lotto-bonus">
                                보너스 <strong>{latest.bonus}</strong>
                            </p>
                        </>
                    ) : (
                        <p className="lotto-empty">최신 회차 데이터가 없습니다.</p>
                    )}
                </section>

                <section className="lotto-panel">
                    <div className="lotto-panel__head">
                        <div>
                            <p className="lotto-panel__eyebrow">Recommendation</p>
                            <h3>추천 생성</h3>
                            <p className="lotto-panel__sub">
                                파라미터를 조정해 다른 추천 전략을 만들 수 있습니다.
                            </p>
                        </div>
                        <div className="lotto-panel__actions">
                            {loading.recommend ? <span className="lotto-chip">계산 중</span> : null}
                        </div>
                    </div>

                    <div className="lotto-presets">
                        {presets.map((preset) => (
                            <button
                                key={preset.name}
                                className="button ghost small"
                                onClick={() =>
                                    setParams({
                                        recent_window: preset.recent_window,
                                        recent_weight: preset.recent_weight,
                                        avoid_recent_k: preset.avoid_recent_k,
                                    })
                                }
                            >
                                {preset.name}
                            </button>
                        ))}
                    </div>

                    <div className="lotto-form">
                        <label className="lotto-field">
                            recent_window
                            <span>최근 N회차 가중치 범위</span>
                            <input
                                type="number"
                                min={20}
                                max={1000}
                                value={params.recent_window}
                                onChange={(e) =>
                                    setParams((s) => ({
                                        ...s,
                                        recent_window: Number(e.target.value),
                                    }))
                                }
                            />
                        </label>

                        <label className="lotto-field">
                            recent_weight
                            <span>최근 회차 가중치</span>
                            <input
                                type="number"
                                step="0.1"
                                min={0.5}
                                max={10}
                                value={params.recent_weight}
                                onChange={(e) =>
                                    setParams((s) => ({
                                        ...s,
                                        recent_weight: Number(e.target.value),
                                    }))
                                }
                            />
                        </label>

                        <label className="lotto-field">
                            avoid_recent_k
                            <span>최근 K회차 중복 회피</span>
                            <input
                                type="number"
                                min={0}
                                max={50}
                                value={params.avoid_recent_k}
                                onChange={(e) =>
                                    setParams((s) => ({
                                        ...s,
                                        avoid_recent_k: Number(e.target.value),
                                    }))
                                }
                            />
                        </label>
                    </div>

                    <button
                        className="button primary"
                        onClick={onRecommend}
                        disabled={loading.recommend}
                    >
                        추천 받기
                    </button>

                    {result ? (
                        <div className="lotto-result">
                            <div className="lotto-result__meta">
                                <div>
                                    <p className="lotto-result__id">추천 ID #{result.id}</p>
                                    <p className="lotto-result__based">
                                        기준 회차 {result.based_on_latest_draw ?? '-'}
                                    </p>
                                </div>
                                <button
                                    className="button small"
                                    onClick={() => copyNumbers(result.numbers)}
                                >
                                    번호 복사
                                </button>
                            </div>
                            <NumberRow nums={result.numbers} />
                            <details className="lotto-details">
                                <summary>설명 보기</summary>
                                <pre>{JSON.stringify(result.explain, null, 2)}</pre>
                            </details>
                        </div>
                    ) : (
                        <p className="lotto-empty">아직 추천 결과가 없습니다.</p>
                    )}
                </section>
            </div>

            <section className="lotto-panel">
                <div className="lotto-panel__head">
                    <div>
                        <p className="lotto-panel__eyebrow">History</p>
                        <h3>추천 히스토리</h3>
                        <p className="lotto-panel__sub">
                            최근 추천 결과를 모아서 확인할 수 있습니다.
                        </p>
                    </div>
                    <div className="lotto-panel__actions">
                        <span className="lotto-chip">{history.length}건</span>
                        <button
                            className="button ghost small"
                            onClick={refreshHistory}
                            disabled={loading.history}
                        >
                            새로고침
                        </button>
                    </div>
                </div>

                {loading.history ? <p className="lotto-empty">불러오는 중...</p> : null}

                {history.length === 0 ? (
                    <p className="lotto-empty">저장된 히스토리가 없습니다.</p>
                ) : (
                    <div className="lotto-history">
                        {history.map((item) => (
                            <div key={item.id} className="lotto-history__item">
                                <div className="lotto-history__meta">
                                    <p>#{item.id}</p>
                                    <p>{fmtKST(item.created_at)}</p>
                                    <p>기준 회차 {item.based_on_draw ?? '-'}</p>
                                </div>
                                <div className="lotto-history__body">
                                    <NumberRow nums={item.numbers} />
                                    <p className="lotto-history__params">
                                        window={item.params?.recent_window}, weight=
                                        {item.params?.recent_weight}, avoid_k=
                                        {item.params?.avoid_recent_k}
                                    </p>
                                </div>
                                <div className="lotto-history__actions">
                                    <button
                                        className="button ghost small"
                                        onClick={() => copyNumbers(item.numbers)}
                                    >
                                        복사
                                    </button>
                                    <button
                                        className="button danger small"
                                        onClick={() => onDelete(item.id)}
                                    >
                                        삭제
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>
                )}
            </section>

            <footer className="lotto-foot">
                backend: FastAPI / nginx proxy / DB: sqlite
            </footer>
        </div>
    );
}
