import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import api from '../../api/client';

const STATUS_LABEL = {
  pending:  { label: '결제 대기', color: 'var(--warn)' },
  paid:     { label: '결제 완료', color: 'var(--success)' },
  refunded: { label: '환불됨',   color: 'var(--text2)' },
  cancelled:{ label: '취소됨',   color: 'var(--text2)' },
};

export default function MyOrders() {
  const [orders, setOrders]   = useState([]);
  const [loading, setLoading] = useState(true);
  const navigate = useNavigate();

  useEffect(() => {
    api.get('/orders/me')
      .then(r => setOrders(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  async function handleRefund(orderId) {
    if (!confirm('환불 요청하시겠습니까?\n플래시 완료 후에는 환불이 불가능합니다.')) return;
    try {
      await api.post(`/orders/${orderId}/refund`, { reason: '사용자 요청' });
      setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: 'refunded' } : o));
    } catch (err) {
      alert(err.response?.data?.error || '환불 처리 실패');
    }
  }

  if (loading) return <div className="spinner" />;

  return (
    <div className="container page">
      <h2 style={{ marginBottom: 24 }}>구매 내역</h2>

      {orders.length === 0 ? (
        <div className="card text-center" style={{ padding: 48 }}>
          <p className="text-muted">구매 내역이 없습니다.</p>
          <Link to="/shop" className="btn btn-primary" style={{ marginTop: 16 }}>상점 둘러보기</Link>
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {orders.map(order => {
            const st = STATUS_LABEL[order.status] || { label: order.status, color: 'var(--text2)' };
            const thumb = order.product?.project?.files?.[0];
            const ft    = order.flashToken;

            return (
              <div key={order.id} className="card" style={{ display: 'grid', gridTemplateColumns: '60px 1fr auto', gap: 16, alignItems: 'center' }}>
                {/* 썸네일 */}
                {thumb
                  ? <img src={thumb.thumbnailUrl || thumb.url} alt="" style={{ width: 60, height: 60, objectFit: 'cover', borderRadius: 4 }} />
                  : <div style={{ width: 60, height: 60, background: 'var(--bg3)', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 20 }}>📦</div>
                }

                {/* 정보 */}
                <div>
                  <div style={{ fontWeight: 600, marginBottom: 2 }}>
                    {order.product?.project?.title || '상품'}
                  </div>
                  <div className="text-muted" style={{ fontSize: 12, marginBottom: 4 }}>
                    ₩{order.amount.toLocaleString()} · {new Date(order.orderedAt).toLocaleDateString('ko-KR')}
                    {' · '}<span style={{ color: st.color }}>{st.label}</span>
                  </div>
                  {ft && (
                    <div style={{ fontSize: 12 }}>
                      {ft.isUsed
                        ? <span style={{ color: 'var(--text2)' }}>✅ 플래시 완료</span>
                        : new Date() > new Date(ft.expiresAt)
                          ? <span style={{ color: 'var(--danger)' }}>⏰ 토큰 만료</span>
                          : <span style={{ color: 'var(--success)' }}>
                              🔑 토큰 유효 · 만료: {new Date(ft.expiresAt).toLocaleDateString('ko-KR')}
                            </span>
                      }
                    </div>
                  )}
                </div>

                {/* 액션 버튼 */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end' }}>
                  {ft && !ft.isUsed && order.status === 'paid' && new Date() <= new Date(ft.expiresAt) && (
                    <Link to={`/flash/${ft.token}`} className="btn btn-primary btn-sm">
                      ⚡ 플래시
                    </Link>
                  )}
                  {order.status === 'paid' && !ft?.isUsed && (
                    <button className="btn btn-outline btn-sm" onClick={() => handleRefund(order.id)}>
                      환불
                    </button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}
