import React from 'react';
import Loading from '../../../components/Loading';
import { formatNumber, formatPercent, profitColorClass } from '../stockUtils';

const SellHistoryDrawer = ({
    sell, sellHistoryBrokers, filteredSellHistory, sellHistorySummary,
}) => (
    <>
        {/* Floating 토글 버튼 */}
        {!sell.sellDrawerOpen && (
            <button
                type="button"
                className="sh-floating-toggle"
                onClick={() => {
                    sell.setSellDrawerOpen(true);
                    sell.loadSellHistory();
                }}
                title="실현손익 내역"
            >
                <span className="sh-floating-toggle__icon">💹</span>
                <span className="sh-floating-toggle__label">실현손익</span>
                {sell.sellHistory.length > 0 && (
                    <span className="sh-floating-toggle__badge">{sell.sellHistory.length}</span>
                )}
            </button>
        )}

        {/* Backdrop */}
        {sell.sellDrawerOpen && (
            <div
                className="sh-backdrop"
                onClick={() => { sell.setSellDrawerOpen(false); sell.handleSellFormClose(); }}
            />
        )}

        {/* Drawer */}
        <aside className={`sh-drawer ${sell.sellDrawerOpen ? 'is-open' : ''}`}>
            <div className="sh-drawer__header">
                <div>
                    <p className="sh-drawer__eyebrow">실현손익</p>
                    <h3 className="sh-drawer__title">매도 거래 내역</h3>
                </div>
                <div className="sh-drawer__header-actions">
                    {sell.sellHistoryLoading && <Loading type="spinner" message="" />}
                    <button
                        className="button ghost small"
                        onClick={sell.loadSellHistory}
                        disabled={sell.sellHistoryLoading}
                    >
                        새로고침
                    </button>
                    <button
                        className="button primary small"
                        onClick={sell.sellFormOpen && sell.sellEditId == null ? sell.handleSellFormClose : sell.handleSellFormOpen}
                    >
                        {sell.sellFormOpen && sell.sellEditId == null ? '취소' : '+ 추가'}
                    </button>
                    <button
                        className="sh-drawer__close"
                        type="button"
                        onClick={() => { sell.setSellDrawerOpen(false); sell.handleSellFormClose(); }}
                        aria-label="닫기"
                    >
                        ✕
                    </button>
                </div>
            </div>

            {/* 수동 추가 / 수정 폼 */}
            {sell.sellFormOpen && (
                <form className="sh-form" onSubmit={sell.handleSellFormSubmit}>
                    <div className="sh-form__title">
                        {sell.sellEditId != null ? '거래 내역 수정' : '매도 내역 수동 추가'}
                    </div>
                    <div className="sh-form__grid">
                        <label>
                            증권사
                            <input
                                type="text"
                                value={sell.sellForm.broker}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, broker: e.target.value }))}
                                placeholder="KB증권"
                                required
                            />
                        </label>
                        <label>
                            종목코드
                            <input
                                type="text"
                                value={sell.sellForm.ticker}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, ticker: e.target.value }))}
                                placeholder="005930"
                            />
                        </label>
                        <label>
                            종목명
                            <input
                                type="text"
                                value={sell.sellForm.name}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, name: e.target.value }))}
                                placeholder="삼성전자"
                                required
                            />
                        </label>
                        <label>
                            수량
                            <input
                                type="number"
                                min={1}
                                step={1}
                                value={sell.sellForm.quantity}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, quantity: e.target.value }))}
                                placeholder="10"
                                required
                            />
                        </label>
                        <label>
                            평균 매입가 (원)
                            <input
                                type="number"
                                min={0}
                                step={1}
                                value={sell.sellForm.avg_price}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, avg_price: e.target.value }))}
                                placeholder="58000"
                                required
                            />
                        </label>
                        <label>
                            매도가 (원)
                            <input
                                type="number"
                                min={0}
                                step={1}
                                value={sell.sellForm.sell_price}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, sell_price: e.target.value }))}
                                placeholder="62000"
                                required
                            />
                        </label>
                        <label>
                            수수료 & 세금 (원)
                            <input
                                type="number"
                                min={0}
                                step={1}
                                value={sell.sellForm.commission}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, commission: e.target.value }))}
                                placeholder="0"
                            />
                        </label>
                        <label className="sh-form__datetime">
                            매도 일시
                            <input
                                type="datetime-local"
                                value={sell.sellForm.sold_at}
                                onChange={(e) => sell.setSellForm((p) => ({ ...p, sold_at: e.target.value }))}
                                required
                            />
                        </label>
                    </div>
                    {sell.sellForm.quantity && sell.sellForm.avg_price && sell.sellForm.sell_price && (() => {
                        const qty = Number(sell.sellForm.quantity);
                        const buy = Number(sell.sellForm.avg_price) * qty;
                        const sellAmt = Number(sell.sellForm.sell_price) * qty;
                        const commission = Number(sell.sellForm.commission) || 0;
                        const profit = sellAmt - buy - commission;
                        const rate = buy > 0 ? (profit / buy) * 100 : 0;
                        return (
                            <div className="sh-form__preview">
                                <span>매도금액 <strong>{formatNumber(Math.round(sellAmt))}원</strong></span>
                                {commission > 0 && (
                                    <span>수수료 & 세금 <strong className="stock-profit is-negative">-{formatNumber(Math.round(commission))}원</strong></span>
                                )}
                                <span>실현손익 <strong className={`stock-profit ${profitColorClass(profit)}`}>{formatNumber(Math.round(profit))}원</strong></span>
                                <span>수익률 <strong className={`stock-profit ${profitColorClass(rate)}`}>{formatPercent(rate)}</strong></span>
                            </div>
                        );
                    })()}
                    <div className="sh-form__actions">
                        <button className="button primary" type="submit" disabled={sell.sellFormSaving}>
                            {sell.sellFormSaving ? '저장 중...' : (sell.sellEditId != null ? '수정 저장' : '추가')}
                        </button>
                        <button className="button ghost" type="button" onClick={sell.handleSellFormClose} disabled={sell.sellFormSaving}>
                            취소
                        </button>
                        {sell.sellFormError && <p className="stock-error">{sell.sellFormError}</p>}
                    </div>
                </form>
            )}

            {/* 필터 바 */}
            <div className="sell-history__filters">
                <div className="sell-history__filter-group">
                    <span className="sell-history__filter-label">계좌</span>
                    {sellHistoryBrokers.map((b) => (
                        <button
                            key={b}
                            type="button"
                            className={`sell-history__filter-btn ${sell.sellHistoryBroker === b ? 'is-active' : ''}`}
                            onClick={() => sell.setSellHistoryBroker(b)}
                        >
                            {b === 'ALL' ? '전체' : b}
                        </button>
                    ))}
                </div>
                <div className="sell-history__filter-group">
                    <span className="sell-history__filter-label">기간</span>
                    {[
                        { label: '1개월', value: '1M' },
                        { label: '3개월', value: '3M' },
                        { label: '6개월', value: '6M' },
                        { label: '1년', value: '1Y' },
                        { label: '전체', value: 'ALL' },
                    ].map(({ label, value }) => (
                        <button
                            key={value}
                            type="button"
                            className={`sell-history__filter-btn ${sell.sellHistoryPeriod === value ? 'is-active' : ''}`}
                            onClick={() => sell.setSellHistoryPeriod(value)}
                        >
                            {label}
                        </button>
                    ))}
                </div>
            </div>

            {/* 요약 카드 */}
            {filteredSellHistory.length > 0 && (
                <div className="sell-history__summary">
                    <div className="sell-history__summary-card">
                        <span>거래 횟수</span>
                        <strong>{sellHistorySummary.count}건</strong>
                    </div>
                    <div className="sell-history__summary-card">
                        <span>총 매도금액</span>
                        <strong>{formatNumber(sellHistorySummary.totalSell)}원</strong>
                    </div>
                    <div className="sell-history__summary-card">
                        <span>총 수수료 & 세금</span>
                        <strong className="stock-profit is-negative">
                            -{formatNumber(Math.round(sellHistorySummary.totalCommission))}원
                        </strong>
                    </div>
                    <div className="sell-history__summary-card">
                        <span>실현손익 합계</span>
                        <strong className={`stock-profit ${profitColorClass(sellHistorySummary.totalProfit)}`}>
                            {formatNumber(Math.round(sellHistorySummary.totalProfit))}원
                        </strong>
                    </div>
                    <div className="sell-history__summary-card">
                        <span>평균 수익률</span>
                        <strong className={`stock-profit ${profitColorClass(sellHistorySummary.rate)}`}>
                            {formatPercent(sellHistorySummary.rate)}
                        </strong>
                    </div>
                </div>
            )}

            {/* 거래 내역 목록 */}
            {filteredSellHistory.length > 0 ? (
                <div className="sh-drawer__list">
                    {filteredSellHistory.map((r) => {
                        const profitN = r.realized_profit ?? 0;
                        const rateN = r.realized_rate ?? 0;
                        return (
                            <div key={r.id} className="sh-drawer__item">
                                <div className="sh-drawer__item-top">
                                    <div className="sh-drawer__item-name">
                                        <span>{r.name}</span>
                                        {r.ticker && <code>{r.ticker}</code>}
                                    </div>
                                    <div className="sh-drawer__item-actions">
                                        <button
                                            type="button"
                                            className="button ghost small"
                                            onClick={() => sell.handleSellEditStart(r)}
                                            title="수정"
                                        >
                                            ✏️
                                        </button>
                                        <button
                                            type="button"
                                            className="button ghost small pf-btn-danger"
                                            onClick={() => sell.handleDeleteSellRecord(r.id)}
                                            title="삭제"
                                        >
                                            🗑️
                                        </button>
                                    </div>
                                </div>
                                <div className="sh-drawer__item-meta">
                                    <span className="sell-history__broker">{r.broker}</span>
                                    <span className="sell-history__date">
                                        {new Date(r.sold_at).toLocaleString('ko-KR', {
                                            year: 'numeric', month: '2-digit', day: '2-digit',
                                            hour: '2-digit', minute: '2-digit',
                                        })}
                                    </span>
                                </div>
                                <div className="sh-drawer__item-metrics">
                                    <div>
                                        <span>수량</span>
                                        <strong>{formatNumber(r.quantity)}</strong>
                                    </div>
                                    <div>
                                        <span>매입가</span>
                                        <strong>{formatNumber(r.avg_price)}</strong>
                                    </div>
                                    <div>
                                        <span>매도가</span>
                                        <strong>{formatNumber(r.sell_price)}</strong>
                                    </div>
                                    <div>
                                        <span>매도금액</span>
                                        <strong>{formatNumber(Math.round(r.sell_amount))}</strong>
                                    </div>
                                    {(r.commission > 0) && (
                                        <div>
                                            <span>수수료 & 세금</span>
                                            <strong className="stock-profit is-negative">
                                                -{formatNumber(Math.round(r.commission))}
                                            </strong>
                                        </div>
                                    )}
                                    <div>
                                        <span>실현손익</span>
                                        <strong className={`stock-profit ${profitColorClass(profitN)}`}>
                                            {formatNumber(Math.round(profitN))}
                                        </strong>
                                    </div>
                                    <div>
                                        <span>수익률</span>
                                        <strong className={`stock-profit ${profitColorClass(rateN)}`}>
                                            {formatPercent(rateN)}
                                        </strong>
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>
            ) : (
                <p className="stock-empty sh-drawer__empty">
                    {sell.sellHistory.length === 0
                        ? '아직 매도 기록이 없습니다.'
                        : '필터 조건에 맞는 기록이 없습니다.'}
                </p>
            )}
        </aside>
    </>
);

export default SellHistoryDrawer;
