import { useState } from 'react'
import { useStore } from '@/store'
import { useTradingStore } from '@/store/tradingStore'
import { Icons } from '@/Components/icons'

const CATEGORIES = ['Forex', 'Crypto', 'Commodities', 'Indices']

export function catGrad(cat) {
  const map = {
    Forex:       'linear-gradient(135deg,#4f8cff,#7a5cff)',
    Crypto:      'linear-gradient(135deg,#ff9d5c,#ff5e7e)',
    Commodities: 'linear-gradient(135deg,#ffd05c,#ff9b3d)',
    Indices:     'linear-gradient(135deg,#34e0c4,#23b6e6)',
  }
  return map[cat] || 'linear-gradient(135deg,#1FE07A,#0fce8f)'
}

export function AssetPicker({ pop }) {
  const { setPickerOpen, favorites, toggleFav, setScreen } = useStore()
  const { assets, selectedAsset, selectAsset } = useTradingStore()
  const [q, setQ] = useState('')
  const [tab, setTab] = useState('All')

  const tabs = ['All', ...CATEGORIES]

  const filtered = assets.filter((a) => {
    const matchTab = tab === 'All' || a.category === tab
    const matchQ =
      a.symbol.toLowerCase().includes(q.toLowerCase()) ||
      a.display_name.toLowerCase().includes(q.toLowerCase())
    return matchTab && matchQ
  })

  const groups = {}
  filtered.forEach((a) => {
    ;(groups[a.category] = groups[a.category] || []).push(a)
  })

  function pick(a) {
    selectAsset(a)
    setPickerOpen(false)
    setScreen('trade')
  }

  return (
    <>
      <div className="sheet-scrim" onClick={() => setPickerOpen(false)} />
      <div className={'sheet' + (pop ? ' pop' : '')}>
        {!pop && <div className="sheet-grab" />}
        <div className="sheet-head">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <h2 className="disp" style={{ fontSize: 20 }}>Select Asset</h2>
            <button onClick={() => setPickerOpen(false)} style={{ color: 'var(--muted)' }}><Icons.x /></button>
          </div>
          <div className="search">
            <Icons.search style={{ color: 'var(--muted)' }} />
            <input
              placeholder="Search assets..."
              value={q}
              onChange={(e) => setQ(e.target.value)}
              autoFocus
            />
          </div>
          <div className="chip-row">
            {tabs.map((c) => (
              <button key={c} className={'pill' + (tab === c ? ' active' : '')} onClick={() => setTab(c)}>{c}</button>
            ))}
          </div>
        </div>

        <div className="sheet-body">
          {Object.keys(groups).map((g) => (
            <div key={g}>
              <div className="cat-head">{g}</div>
              {groups[g].map((a) => {
                const isSelected = selectedAsset?.symbol === a.symbol
                const isClosed = a.is_open === false
                return (
                  <div
                    key={a.symbol}
                    className="row"
                    onClick={() => pick(a)}
                    style={isSelected ? { background: 'rgba(31,224,122,0.06)' } : undefined}
                  >
                    <div className="ic" style={{ background: catGrad(a.category), color: '#06140b' }}>
                      {a.symbol.slice(0, 2)}
                    </div>
                    <div>
                      <div className="name" style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        {a.symbol}
                        {isClosed && (
                          <span style={{
                            fontSize: '10px',
                            fontWeight: '700',
                            color: '#FF3D57',
                            background: 'rgba(255,61,87,0.1)',
                            border: '1px solid rgba(255,61,87,0.3)',
                            borderRadius: '4px',
                            padding: '1px 5px',
                            letterSpacing: '0.05em',
                          }}>
                            CLOSED
                          </span>
                        )}
                      </div>
                      <div className="meta">{a.display_name}</div>
                    </div>
                    <div className="right" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                      <div style={{ fontSize: 11, color: 'var(--green)' }}>
                        {a.payout_percentage}%
                      </div>
                    </div>
                    <button
                      className={'star' + (favorites.includes(a.symbol) ? ' on' : '')}
                      onClick={(e) => { e.stopPropagation(); toggleFav(a.symbol) }}
                    >★</button>
                  </div>
                )
              })}
            </div>
          ))}

          {!filtered.length && (
            <div className="empty">No assets match &ldquo;{q}&rdquo;</div>
          )}
        </div>
      </div>
    </>
  )
}
