import React, { useState } from 'react';
import Loading from '../../../components/Loading';
import { kindMeta, conditionLabel, relativeTime, formatDetail } from '../watchlistUtils';
import { formatNumber } from '../stockUtils';

const DAYS_OPTIONS = [
  { value: 1, label: '1D' },
  { value: 7, label: '7D' },
  { value: 30, label: '30D' },
];

const AlertCard = ({ a }) => {
  const meta = kindMeta(a.kind);
  const detailText = formatDetail(a.detail);
  return (
    <div className="wl-alert">
      <div className="wl-alert__head">
        <span className="wl-kind-badge" style={{ color: meta.color, background: meta.bg }}>{meta.label}</span>
        <strong className="wl-alert__name">{a.name || a.ticker}</strong>
        <span className="wl-alert__ticker">{a.ticker}</span>
        <span className="wl-alert__time">{relativeTime(a.fired_at)}</span>
      </div>
      <div className="wl-alert__body">
        <span className="wl-cond">{conditionLabel(a.condition)}</span>
        {a.price != null && <span className="wl-alert__price">{formatNumber(a.price)}원</span>}
      </div>
      {a.reason && <div className="wl-alert__reason">{a.reason}</div>}
      {detailText && <div className="wl-alert__detail">{detailText}</div>}
    </div>
  );
};

const WatchlistTab = ({ wl }) => {
  const [form, setForm] = useState({ ticker: '', name: '', note: '' });

  const submit = async (e) => {
    e.preventDefault();
    if (!form.ticker.trim()) return;
    const ok = await wl.add(form);
    if (ok) setForm({ ticker: '', name: '', note: '' });
  };

  return (
    <>
      {/* 관심종목 관리 */}
      <section className="stock-panel stock-panel--wide wl-panel">
        <div className="stock-panel__head">
          <div>
            <p className="stock-panel__eyebrow">관심종목</p>
            <h3>관심종목 관리</h3>
            <p className="stock-panel__sub">등록한 종목은 매매 시그널 감시 유니버스에 포함됩니다.</p>
          </div>
          <div className="stock-panel__actions">{wl.loading && <Loading type="spinner" message="" />}</div>
        </div>

        <form className="wl-form" onSubmit={submit}>
          <input
            className="wl-form__input"
            placeholder="종목코드 (예: 005930)"
            value={form.ticker}
            onChange={(e) => setForm((f) => ({ ...f, ticker: e.target.value }))}
          />
          <input
            className="wl-form__input"
            placeholder="종목명 (선택)"
            value={form.name}
            onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
          />
          <input
            className="wl-form__input"
            placeholder="메모 (선택)"
            value={form.note}
            onChange={(e) => setForm((f) => ({ ...f, note: e.target.value }))}
          />
          <button className="button" type="submit" disabled={!form.ticker.trim() || wl.adding}>
            {wl.adding ? '추가 중…' : '추가'}
          </button>
        </form>

        {wl.error && <p className="stock-error">{wl.error}</p>}

        {wl.items.length === 0 ? (
          <p className="stock-empty">아직 관심종목이 없습니다. 종목코드를 추가해 보세요.</p>
        ) : (
          <ul className="wl-list">
            {wl.items.map((it) => (
              <li key={it.ticker} className="wl-row">
                <div className="wl-row__meta">
                  <strong className="wl-row__name">{it.name || it.ticker}</strong>
                  <span className="wl-row__ticker">{it.ticker}</span>
                  {it.note && <span className="wl-row__note">{it.note}</span>}
                </div>
                <button
                  className="wl-del"
                  type="button"
                  aria-label={`${it.ticker} 삭제`}
                  onClick={() => wl.remove(it.ticker)}
                >
                  ✕
                </button>
              </li>
            ))}
          </ul>
        )}
      </section>

      {/* 최근 시그널 알림 */}
      <section className="stock-panel stock-panel--wide wl-panel">
        <div className="stock-panel__head">
          <div>
            <p className="stock-panel__eyebrow">시그널</p>
            <h3>최근 매매 알림</h3>
            <p className="stock-panel__sub">감시 종목에서 발생한 매수·매도 시그널 이력입니다.</p>
          </div>
          <div className="wl-period-toggle">
            {DAYS_OPTIONS.map((o) => (
              <button
                key={o.value}
                type="button"
                className={`wl-period ${wl.alertDays === o.value ? 'is-active' : ''}`}
                onClick={() => wl.setAlertDays(o.value)}
              >
                {o.label}
              </button>
            ))}
          </div>
        </div>

        {wl.alertError && <p className="stock-error">{wl.alertError}</p>}

        {wl.alerts.length === 0 ? (
          <p className="stock-empty">해당 기간에 발생한 알림이 없습니다.</p>
        ) : (
          <div className="wl-alerts">
            {wl.alerts.map((a) => (
              <AlertCard key={a.id ?? `${a.ticker}-${a.fired_at}`} a={a} />
            ))}
          </div>
        )}

        <p className="hi-disclaimer">※ 어드바이저리 알림이며 자동매매가 아닙니다. 최종 판단은 본인 책임입니다.</p>
      </section>
    </>
  );
};

export default WatchlistTab;
