'use client'

import { useState } from 'react'
import { useAccount, useSignMessage } from 'wagmi'
import type { BotPerformance } from '@/types'
import { useDashboardStore } from '@/store/dashboard'
import { setHlApiKey, subscribe } from '@/lib/api'
import { signRequest } from '@/lib/signedRequest'

// Action names must match backend/app/api/{user,subscribe}.py
const ACTION_SET_API_KEY = 'set_hl_api_key'
const ACTION_SUBSCRIBE = 'subscribe'

interface Props {
  performance?: BotPerformance | null
}

type SaveState = 'idle' | 'signing' | 'saving' | 'success' | 'error'

function fmtHold(s: number) {
  if (s < 60) return s + 's'
  const m = Math.floor(s / 60)
  if (m < 60) return m + 'm'
  return Math.floor(m / 60) + 'h ' + (m % 60) + 'm'
}

export default function BotPanel({ performance }: Props) {
  const { isSubscribed, hlApiKeySet, hlApiKeyMasked, setHlApiKeySet, setSubscribed } = useDashboardStore()
  const { address, isConnected } = useAccount()
  const { signMessageAsync } = useSignMessage()

  const [apiKey, setApiKey] = useState('')
  const [saveState, setSaveState] = useState<SaveState>('idle')
  const [errorMsg, setErrorMsg] = useState('')
  const [subState, setSubState] = useState<'idle' | 'signing' | 'saving' | 'error'>('idle')
  const [subError, setSubError] = useState('')

  async function handleSubscribe() {
    if (!address) return
    setSubError('')
    try {
      setSubState('signing')
      const env = await signRequest({
        action: ACTION_SUBSCRIBE,
        wallet: address,
        body: null,
        signMessageAsync,
      })
      setSubState('saving')
      await subscribe(env)
      setSubscribed(true)
      setSubState('idle')
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Unknown error'
      setSubError(msg.includes('User rejected') || msg.includes('denied') ? 'Signature cancelled' : msg.slice(0, 120))
      setSubState('error')
    }
  }

  async function handleSaveKey() {
    if (!address || !apiKey.trim()) return
    if (!apiKey.trim().startsWith('0x') || apiKey.trim().length !== 66) {
      setErrorMsg('Key must start with 0x and be 66 characters')
      setSaveState('error')
      return
    }
    setErrorMsg('')
    try {
      setSaveState('signing')
      const trimmed = apiKey.trim()
      const env = await signRequest({
        action: ACTION_SET_API_KEY,
        wallet: address,
        body: { api_key: trimmed },
        signMessageAsync,
      })
      setSaveState('saving')
      const res = await setHlApiKey(env, trimmed)
      setHlApiKeySet(true, res.masked_key)
      setApiKey('')
      setSaveState('success')
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : 'Unknown error'
      if (msg.includes('User rejected') || msg.includes('denied')) {
        setErrorMsg('Signature cancelled')
      } else {
        setErrorMsg(msg.slice(0, 120))
      }
      setSaveState('error')
    }
  }

  const saveLabel =
    saveState === 'signing' ? 'Waiting for signature…'
    : saveState === 'saving' ? 'Saving…'
    : saveState === 'success' ? '✓ Saved'
    : 'Save key'

  return (
    <>
      {/* Bot status card — dark design */}
      <div className="bot-status">
        <div className="bot-head">
          <h3>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: isSubscribed ? 'var(--amber)' : 'oklch(70% 0.01 85)', display: 'inline-block' }} />
            Auto-trader
          </h3>
          <span style={{ fontSize: 11, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em' }}>30 days</span>
        </div>

        <div className="bot-stats">
          <div className="bot-stat">
            <div className="k">Net P&amp;L</div>
            <div className="v amber">
              {performance ? (performance.net_pnl_usd >= 0 ? '+$' : '-$') + Math.abs(performance.net_pnl_usd).toLocaleString(undefined, { maximumFractionDigits: 0 }) : '—'}
            </div>
          </div>
          <div className="bot-stat">
            <div className="k">Win rate</div>
            <div className="v up">
              {performance ? (performance.win_rate * 100).toFixed(1) + '%' : '—'}
            </div>
          </div>
          <div className="bot-stat">
            <div className="k">Trades</div>
            <div className="v">{performance?.total_trades ?? '—'}</div>
          </div>
          <div className="bot-stat">
            <div className="k">Avg hold</div>
            <div className="v">{performance ? fmtHold(performance.avg_hold_seconds) : '—'}</div>
          </div>
        </div>

        <div className="bot-cta">
          {!isConnected && (
            <button className="btn amber" style={{ width: '100%' }}
              onClick={() => document.querySelector<HTMLButtonElement>('.connect-btn')?.click()}>
              Connect wallet
            </button>
          )}
          {isConnected && !isSubscribed && (
            <div style={{ width: '100%' }}>
              <button
                className="btn amber"
                style={{ width: '100%' }}
                onClick={handleSubscribe}
                disabled={subState === 'signing' || subState === 'saving'}
              >
                {subState === 'signing' ? 'Waiting for signature…' : subState === 'saving' ? 'Activating…' : 'Start trading'}
              </button>
              {subState === 'error' && subError && (
                <p style={{ fontSize: 11, color: 'var(--down)', marginTop: 6, textAlign: 'center' }}>{subError}</p>
              )}
            </div>
          )}
          {isConnected && isSubscribed && !hlApiKeySet && (
            <div style={{ width: '100%', textAlign: 'center', fontSize: 12, color: 'oklch(75% 0.01 85)', padding: '6px 0' }}>
              ↓ Paste your Hyperliquid API key below to activate
            </div>
          )}
          {isConnected && isSubscribed && hlApiKeySet && (
            <div style={{ width: '100%', textAlign: 'center', fontSize: 12, color: 'var(--amber)', padding: '6px 0', fontWeight: 500 }}>
              ✓ Bot active · waiting for next signal
            </div>
          )}
        </div>
      </div>

      {/* HL API Key card — only when subscribed */}
      {isConnected && isSubscribed && (
        <div className="card" style={{ padding: 20 }}>
          <div className="section-title">
            <h2 style={{ fontSize: 14 }}>Hyperliquid API key</h2>
            {hlApiKeySet && <span style={{ fontSize: 11, color: 'var(--up)', fontWeight: 500 }}>✓ Connected</span>}
          </div>

          {hlApiKeySet && !apiKey && (
            <div className="row between" style={{ padding: '10px 12px', background: 'var(--bg-sunk)', borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', marginBottom: 12 }}>
              <span style={{ fontSize: 12, color: 'var(--up)', fontFamily: 'var(--mono)' }}>
                {hlApiKeyMasked ?? '···'}
              </span>
              <button
                style={{ fontSize: 11, color: 'var(--ink-3)' }}
                onClick={() => { setSaveState('idle'); setApiKey(' ') }}
              >
                Update
              </button>
            </div>
          )}

          {(!hlApiKeySet || apiKey) && (
            <>
              <div className="field" style={{ marginBottom: 12 }}>
                <label>API wallet private key</label>
                <input
                  value={apiKey.trim() === '' && hlApiKeySet ? '' : apiKey}
                  onChange={(e) => {
                    setApiKey(e.target.value)
                    if (saveState === 'error' || saveState === 'success') setSaveState('idle')
                  }}
                  placeholder="0x…"
                />
                <div className="hint">
                  From{' '}
                  <a href="https://app.hyperliquid.xyz/API" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--amber-ink)' }}>
                    app.hyperliquid.xyz/API
                  </a>
                </div>
              </div>

              {saveState === 'error' && errorMsg && (
                <p style={{ fontSize: 11, color: 'var(--down)', marginBottom: 8 }}>{errorMsg}</p>
              )}

              <button
                className={`btn ${saveState === 'success' ? 'ghost' : 'amber'}`}
                style={{ width: '100%' }}
                onClick={handleSaveKey}
                disabled={saveState === 'signing' || saveState === 'saving' || !apiKey.trim()}
              >
                {saveLabel}
              </button>
            </>
          )}

          {!hlApiKeySet && (
            <details style={{ marginTop: 12 }}>
              <summary style={{ fontSize: 11, color: 'var(--ink-3)', cursor: 'pointer' }}>
                How to get your API key
              </summary>
              <ol style={{ marginTop: 8, fontSize: 11, color: 'var(--ink-3)', paddingLeft: 16, lineHeight: 1.7 }}>
                <li>Deposit USDC at app.hyperliquid.xyz</li>
                <li>Go to app.hyperliquid.xyz/API</li>
                <li>Click <strong>Generate API Wallet</strong></li>
                <li>Sign with MetaMask (no gas)</li>
                <li>Copy the private key → paste above</li>
              </ol>
            </details>
          )}
        </div>
      )}
    </>
  )
}
