import { useStore } from '@/store'
import { useTradingStore } from '@/store/tradingStore'
import { Icons } from '@/Components/icons'
import { ChartArea } from '@/Components/ChartArea'
import { AssetPicker, catGrad } from '@/Components/AssetPicker'
import { ToastHost, ResultModal } from '@/Components/ui/Overlays'
import { TradeResultToast } from '@/Components/ui/TradeResultToast'
import { AmountStepper, TimeStepper, UpButton, DownButton, OrderButton, ProfitLine, MarketClosedOverlay } from '@/Components/ui/TradeControls'
import { AccountSwitcherSheet } from '@/Components/ui/AccountSwitcher'
import { MarketsScreen } from '@/Components/screens/MarketsScreen'
import { PortfolioScreen } from '@/Components/screens/PortfolioScreen'
import { TournamentScreen } from '@/Components/screens/TournamentScreen'
import { DepositScreen } from '@/Components/screens/DepositScreen'
import { ProfileScreen } from '@/Components/screens/ProfileScreen'

function MTop() {
  const { setScreen } = useStore()
  return (
    <div className="m-top">
      <button className="avatar-sm" onClick={() => setScreen('profile')}>
        <Icons.user width={20} height={20} />
        <span className="on" />
      </button>
      <div className="center">
        <AccountSwitcherSheet />
      </div>
      <button className="m-app-btn" onClick={() => setScreen('markets')}>
        <Icons.grid width={20} height={20} />
      </button>
    </div>
  )
}

function AssetRow() {
  const { setPickerOpen } = useStore()
  const { selectedAsset, timeframe, setTimeframe } = useTradingStore()

  if (!selectedAsset) {
    return (
      <div className="m-asset-row">
        <button className="asset-pill" onClick={() => setPickerOpen(true)}>
          <span style={{ color: 'var(--muted)', fontSize: 14 }}>Select an asset</span>
          <Icons.chevD style={{ opacity: 0.6 }} />
        </button>
      </div>
    )
  }

  return (
    <div className="m-asset-row">
      <button className="asset-pill" onClick={() => setPickerOpen(true)}>
        <span className="asset-ic" style={{ background: catGrad(selectedAsset.category) }}>
          {selectedAsset.symbol.slice(0, 2)}
        </span>
        <span style={{ flex: 1, textAlign: 'left', minWidth: 0 }}>
          <span className="nm" style={{ display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {selectedAsset.symbol} <span className="up" style={{ fontSize: 12 }}>· {selectedAsset.payout_percentage}%</span>
          </span>
        </span>
        <Icons.chevD style={{ opacity: 0.6 }} />
      </button>
      <button className="mini-tool"><Icons.fx /></button>
      <button
        className="mini-tool"
        onClick={() => setTimeframe(timeframe === '1m' ? '5m' : '1m')}
        style={{ fontFamily: 'var(--font-mono)', color: '#FFFFFF' }}
      >
        {timeframe}
      </button>
      <button className="mini-tool"><Icons.signal /></button>
    </div>
  )
}

function MControls() {
  const { selectedAsset } = useTradingStore()
  const isMarketOpen = selectedAsset ? selectedAsset.is_open !== false : true
  return (
    <div className="m-controls" style={{ position: 'relative' }}>
      <div className="mode-row">
        <span className="mode">Fixed Time mode</span>
        <ProfitLine />
      </div>
      <div className="m-steppers">
        <TimeStepper />
        <AmountStepper />
      </div>
      <div className="m-actions">
        <DownButton />
        <OrderButton compact />
        <UpButton />
      </div>
      {!isMarketOpen && <MarketClosedOverlay asset={selectedAsset} />}
    </div>
  )
}

function MNav() {
  const { screen, setScreen } = useStore()
  const items = [
    { k: 'trade',       ic: Icons.area },
    { k: 'markets',     ic: Icons.swap },
    { k: 'portfolio',   ic: Icons.analytics, dot: true },
    { k: 'deposit',     ic: Icons.bag },
    { k: 'tournaments', ic: Icons.trophy },
    { k: 'profile',     ic: Icons.help },
  ]
  return (
    <div className="m-nav">
      {items.map((it) => {
        const I = it.ic
        return (
          <button key={it.k} className={'nav-item' + (screen === it.k ? ' active' : '')} onClick={() => setScreen(it.k)}>
            <I />
            {it.dot && screen !== it.k && <span className="gdot" />}
          </button>
        )
      })}
    </div>
  )
}

const SCREENS = {
  markets:     <MarketsScreen />,
  portfolio:   <PortfolioScreen />,
  tournaments: <TournamentScreen />,
  deposit:     <DepositScreen />,
  profile:     <ProfileScreen />,
}

export function MobileLayout() {
  const { screen, pickerOpen, result, setResult, toasts, tradeResults, removeTradeResult } = useStore()
  return (
    <div className="q-mobile">
      <MTop />
      {screen === 'trade' ? (
        <>
          <AssetRow />
          <ChartArea count={56} />
          <MControls />
        </>
      ) : (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', minHeight: 0 }} key={screen}>
          {SCREENS[screen]}
        </div>
      )}
      <MNav />
      {pickerOpen && <AssetPicker />}
      <ToastHost toasts={toasts} />
      {result && <ResultModal result={result} onClose={() => setResult(null)} />}
      {tradeResults.map((r) => (
        <TradeResultToast key={r.id} result={r} onDismiss={() => removeTradeResult(r.id)} />
      ))}
    </div>
  )
}
