const { useState, useRef } = React;

const PLATFORMS = ['eBay', 'Facebook', 'Other'];

function OpenCard({ flip, onSell, onDelete }) {
  const [open, setOpen] = useState(false);
  const [sellPrice, setSellPrice] = useState('');
  const [platform, setPlatform] = useState('');
  const [fees, setFees] = useState('');
  const [shipping, setShipping] = useState('');
  const [showFees, setShowFees] = useState(false);
  const [selling, setSelling] = useState(false);

  const days = daysBetween(flip.buy_date, null);

  function handleSell() {
    if (!sellPrice) { alert('Enter a sell price'); return; }
    setSelling(true);
    setTimeout(() => {
      onSell(flip.id, {
        sell_price: parseFloat(sellPrice),
        sell_date: todayStr(),
        platform,
        fees: parseFloat(fees)||0,
        shipping: parseFloat(shipping)||0,
      });
    }, 300);
  }

  return (
    <div className="flip-card" style={{ opacity: selling ? 0 : 1, transform: selling ? 'translateX(40px)' : 'none', transition: 'all 0.3s ease' }}>
      <div className="flip-card-main" onClick={() => setOpen(o => !o)}>
        <div className="flip-icon" style={{background:catIconBg(flip.category),display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,lineHeight:1}}>{itemEmoji(flip.item_name)}</div>
        <div className="flip-info">
          <div className="flip-name">{flip.item_name}</div>
          <div className="flip-meta">Paid {fmt(flip.buy_price)} · {days}d ago</div>
        </div>
        <div className={`flip-chevron ${open ? 'rotated' : ''}`}>›</div>
      </div>
      <div className={`flip-expand ${open ? 'open' : ''}`}>
        <div className="expand-inner">
          <div className="form-group">
            <label>Sold for</label>
            <div className="input-prefix">
              <span>$</span>
              <input type="number" placeholder="0" step="1" min="0" inputMode="numeric"
                value={sellPrice} onChange={e => setSellPrice(e.target.value)} />
            </div>
          </div>
          <div className="form-group">
            <label>Platform</label>
            <div className="styled-select-wrap">
              <select value={platform} onChange={e => setPlatform(e.target.value)}>
                <option value="">Select platform</option>
                {PLATFORMS.map(p => <option key={p} value={p}>{p === 'Facebook' ? 'Facebook Marketplace' : p}</option>)}
              </select>
              <svg className="select-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
            </div>
          </div>
          <div className="expand-details-toggle" onClick={() => setShowFees(s => !s)}>
            {showFees ? '− Hide fees' : '+ Add fees & shipping'}
          </div>
          {showFees && (
            <div className="form-row" style={{marginTop:10}}>
              <div className="form-group">
                <label>Fees</label>
                <div className="input-prefix"><span>$</span><input type="number" placeholder="0" step="0.01" value={fees} onChange={e => setFees(e.target.value)} /></div>
              </div>
              <div className="form-group">
                <label>Shipping</label>
                <div className="input-prefix"><span>$</span><input type="number" placeholder="0" step="0.01" value={shipping} onChange={e => setShipping(e.target.value)} /></div>
              </div>
            </div>
          )}
          {sellPrice && parseFloat(sellPrice) > 0 && (
            <div style={{fontSize:13, color:'var(--text-muted)', padding:'4px 0'}}>
              Profit: <span style={{fontWeight:700, color: (parseFloat(sellPrice) - flip.buy_price - (parseFloat(fees)||0) - (parseFloat(shipping)||0)) >= 0 ? 'var(--green)' : 'var(--red)'}}>
                {fmtSigned(parseFloat(sellPrice) - flip.buy_price - (parseFloat(fees)||0) - (parseFloat(shipping)||0), 2)}
              </span>
            </div>
          )}
          <button className="log-btn" onClick={handleSell}>Confirm sale</button>
          <button className="delete-btn" onClick={() => onDelete(flip.id)}>Delete flip</button>
        </div>
      </div>
    </div>
  );
}

function SoldCard({ flip, onDelete, onUpdate }) {
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState(false);
  const [editData, setEditData] = useState({});
  const profit = flipProfit(flip);
  const hourly = flip.hours_spent > 0 && profit > 0 ? profit / flip.hours_spent : null;

  function startEdit() {
    setEditData({
      sell_price: flip.sell_price,
      sell_date: flip.sell_date,
      platform: flip.platform || '',
      fees: flip.fees || 0,
      shipping: flip.shipping || 0,
      hours_spent: flip.hours_spent || 0
    });
    setEditing(true);
    setOpen(false);
  }

  function saveEdit() {
    onUpdate(flip.id, editData);
    setEditing(false);
  }

  function cancelEdit() {
    setEditing(false);
    setEditData({});
  }

  if (editing) {
    return (
      <div className="flip-card" style={{border: '2px solid var(--text)'}}>
        <div className="flip-card-main">
          <div className="flip-icon" style={{background:catIconBg(flip.category),display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,lineHeight:1}}>{itemEmoji(flip.item_name)}</div>
          <div className="flip-info">
            <div className="flip-name">{flip.item_name}</div>
            <div className="flip-meta">Editing sold item</div>
          </div>
        </div>
        <div className="flip-expand open">
          <div className="expand-inner">
            <div className="form-group">
              <label>Sold for</label>
              <div className="input-prefix">
                <span>$</span>
                <input type="number" placeholder="0" step="1" min="0" inputMode="numeric"
                  value={editData.sell_price || ''} onChange={e => setEditData({...editData, sell_price: parseFloat(e.target.value) || 0})} />
              </div>
            </div>
            <div className="form-group">
              <label>Date sold</label>
              <input type="date" value={editData.sell_date || ''} onChange={e => setEditData({...editData, sell_date: e.target.value})} />
            </div>
            <div className="form-group">
              <label>Platform</label>
              <div className="styled-select-wrap">
                <select value={editData.platform || ''} onChange={e => setEditData({...editData, platform: e.target.value})}>
                  <option value="">Select platform</option>
                  {PLATFORMS.map(p => <option key={p} value={p}>{p === 'Facebook' ? 'Facebook Marketplace' : p}</option>)}
                </select>
                <svg className="select-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M6 9l6 6 6-6"/></svg>
              </div>
            </div>
            <div className="form-row">
              <div className="form-group">
                <label>Fees</label>
                <div className="input-prefix"><span>$</span><input type="number" placeholder="0" step="0.01" value={editData.fees || ''} onChange={e => setEditData({...editData, fees: parseFloat(e.target.value) || 0})} /></div>
              </div>
              <div className="form-group">
                <label>Shipping</label>
                <div className="input-prefix"><span>$</span><input type="number" placeholder="0" step="0.01" value={editData.shipping || ''} onChange={e => setEditData({...editData, shipping: parseFloat(e.target.value) || 0})} /></div>
              </div>
            </div>
            <div className="form-group">
              <label>Hours spent</label>
              <input type="number" placeholder="0" step="0.5" min="0" value={editData.hours_spent || ''} onChange={e => setEditData({...editData, hours_spent: parseFloat(e.target.value) || 0})} />
            </div>
            <div style={{display:'flex', gap:10, marginTop:8}}>
              <button className="log-btn" onClick={saveEdit}>Save changes</button>
              <button className="delete-btn" onClick={cancelEdit}>Cancel</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="flip-card">
      <div className="flip-card-main" onClick={() => setOpen(o => !o)}>
        <div className="flip-icon" style={{background:catIconBg(flip.category),display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,lineHeight:1}}>{itemEmoji(flip.item_name)}</div>
        <div className="flip-info">
          <div className="flip-name">{flip.item_name}</div>
          <div className="flip-meta">{flip.platform || '—'} · {fmt(flip.buy_price)} → {fmt(flip.sell_price)}</div>
        </div>
        <div className="flip-right">
          <div className={`flip-profit ${profit >= 0 ? 'fp-pos' : 'fp-neg'}`}>{fmtSigned(profit)}</div>
          {hourly ? <div className="flip-hourly">{fmt(hourly)}/hr</div> : <div className="flip-date">{flip.sell_date}</div>}
        </div>
      </div>
      <div className={`flip-expand ${open ? 'open' : ''}`}>
        <div className="expand-inner">
          <div className="sold-detail-row"><span className="sold-detail-label">Bought</span><span className="sold-detail-val">{fmt(flip.buy_price, 2)} · {flip.buy_date}</span></div>
          <div className="sold-detail-row"><span className="sold-detail-label">Sold</span><span className="sold-detail-val">{fmt(flip.sell_price, 2)} · {flip.sell_date}</span></div>
          <div className="sold-detail-row"><span className="sold-detail-label">Platform</span><span className="sold-detail-val">{flip.platform || '—'}</span></div>
          <div className="sold-detail-row"><span className="sold-detail-label">Fees</span><span className="sold-detail-val">{fmt(flip.fees||0, 2)}</span></div>
          <div className="sold-detail-row"><span className="sold-detail-label">Shipping</span><span className="sold-detail-val">{fmt(flip.shipping||0, 2)}</span></div>
          {flip.hours_spent > 0 && (
            <div className="sold-detail-row">
              <span className="sold-detail-label">Hours</span>
              <span className="sold-detail-val">{flip.hours_spent}h{hourly ? ` · ${fmt(hourly)}/hr` : ''}</span>
            </div>
          )}
          <div className="sold-detail-row">
            <span className="sold-detail-label" style={{fontWeight:600}}>Net profit</span>
            <span className={`sold-detail-val ${profit >= 0 ? 'fp-pos' : 'fp-neg'}`} style={{fontWeight:700}}>{fmtSigned(profit, 2)}</span>
          </div>
          <div style={{display:'flex', gap:10, marginTop:8}}>
            <button className="log-btn" style={{flex:1, textAlign:'center', padding:'12px', border:'1.5px solid #e5e5ea', borderRadius:14, fontSize:14, cursor:'pointer'}}
              onClick={startEdit}>Edit</button>
            <button className="delete-btn" style={{flex:1, textAlign:'center', padding:'12px', border:'1.5px solid #ffe5e5', borderRadius:14, fontSize:14, cursor:'pointer'}}
              onClick={() => onDelete(flip.id)}>Delete</button>
          </div>
        </div>
      </div>
    </div>
  );
}

function FlipsScreen({ navigate }) {
  const { state, dispatch } = useStore();
  const [tab, setTab] = useState(() => {
    const t = window._initialTab;
    if (t) { window._initialTab = null; return t; }
    return 'open';
  });

  const openFlips = state.flips.filter(f => f.status === 'open');
  const soldFlips = state.flips.filter(f => f.status === 'sold');

  function handleSell(id, data) {
    dispatch({ type: 'SELL_FLIP', id, data });
    setTimeout(() => setTab('sold'), 400);
  }
  function handleDelete(id) {
    if (confirm('Delete this flip?')) dispatch({ type: 'DELETE_FLIP', id });
  }
  function handleUpdate(id, data) {
    dispatch({ type: 'UPDATE_FLIP', id, data });
  }

  return (
    <div className="content">
      <div className="tabs-row">
        <button className={`tab ${tab === 'open' ? 'active' : ''}`} onClick={() => setTab('open')}>
          Open <span className="tab-count">{openFlips.length}</span>
        </button>
        <button className={`tab ${tab === 'sold' ? 'active' : ''}`} onClick={() => setTab('sold')}>
          Sold <span className="tab-count">{soldFlips.length}</span>
        </button>
      </div>

      {tab === 'open' && (
        openFlips.length === 0 ? (
          <div className="empty-state">
            <p>No open flips.</p>
            <button className="log-btn" onClick={() => navigate('log')}>Log your first trade</button>
          </div>
        ) : (
          <div className="flips-list">
            {openFlips.map(f => <OpenCard key={f.id} flip={f} onSell={handleSell} onDelete={handleDelete} />)}
          </div>
        )
      )}

      {tab === 'sold' && (
        soldFlips.length === 0 ? (
          <div className="empty-state"><p>No sold flips yet.</p></div>
        ) : (
          <div className="flips-list">
            {soldFlips.map(f => <SoldCard key={f.id} flip={f} onDelete={handleDelete} onUpdate={handleUpdate} />)}
          </div>
        )
      )}
    </div>
  );
}

Object.assign(window, { FlipsScreen });
