'use client';

import { useState, useEffect, useCallback } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { api } from '@/lib/api';

interface BourseData {
  cours: number;
  variation: number;
  history: Array<{ timestamp: string; cours: number }>;
}

export function BourseView() {
  const { balances, setMainView } = useGameStore();
  const [data, setData] = useState<BourseData | null>(null);
  const [amount, setAmount] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  useEffect(() => {
    loadBourseData();
  }, []);

  const loadBourseData = async () => {
    try {
      const [cours, history] = await Promise.all([
        api.bourse.cours(),
        api.bourse.history(7).catch(() => ({ points: [] } as any)),
      ]);
      const points = (history as any).points ?? [];
      const first = points.length > 0 ? Number(points[0]?.cours) : Number(cours.quintessence.cours);
      const last = Number(cours.quintessence.cours);
      const variation = first > 0 ? ((last - first) / first) * 100 : 0;
      setData({
        cours: last,
        variation,
        history: points.map((p: any) => ({ timestamp: p.timestamp, cours: Number(p.cours) })),
      });
    } catch { /* ignore */ }
  };

  const handleTrade = useCallback(async (action: 'buy' | 'sell') => {
    const qty = parseFloat(amount);
    if (!qty || qty <= 0) return setError('Montant invalide');
    setLoading(true);
    setError('');
    setSuccess('');
    try {
      // Phase 16 (2026-04-22) — wiring api.bourse
      if (action === 'buy') await api.bourse.buy(qty, 'infinite_light');
      else await api.bourse.sell(qty, 'infinite_light');
      setSuccess(`${action === 'buy' ? 'Achat' : 'Vente'} de ${qty} Quintessence effectué`);
      setAmount('');
      loadBourseData();
    } catch (err: any) {
      setError(err.message || 'Erreur');
    } finally {
      setLoading(false);
    }
  }, [amount]);

  return (
    <div style={{
      flex: 1,
      display: 'flex',
      flexDirection: 'column',
      background: 'var(--bg-primary)',
      color: 'var(--text-primary)',
      overflow: 'auto',
    }}>
      {/* Header */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        gap: 16,
        padding: '16px 24px',
        borderBottom: '1px solid var(--border-subtle)',
        background: 'var(--bg-secondary)',
      }}>
        <button
          onClick={() => setMainView('map')}
          style={{
            background: 'none',
            border: '1px solid var(--border-subtle)',
            color: 'var(--text-muted)',
            padding: '6px 12px',
            borderRadius: 6,
            cursor: 'pointer',
            fontSize: 13,
          }}
        >
          Retour Carte
        </button>
        <h2 style={{ margin: 0, fontSize: 20, fontWeight: 700, fontFamily: 'var(--font-heading)' }}>
          Bourse Quintessence
        </h2>
      </div>

      {/* Content */}
      <div style={{ padding: 24, display: 'flex', gap: 24, flexWrap: 'wrap' }}>
        {/* Cours actuel */}
        <div style={{
          flex: '1 1 300px',
          background: 'var(--bg-card)',
          borderRadius: 12,
          padding: 24,
          border: '1px solid var(--border-subtle)',
        }}>
          <h3 style={{ margin: '0 0 16px', fontSize: 16, color: 'var(--text-muted)' }}>
            Cours actuel
          </h3>
          <div style={{ fontSize: 48, fontWeight: 800, fontFamily: 'var(--font-mono, monospace)' }}>
            {data?.cours?.toFixed(2) ?? '---'} <span style={{ fontSize: 18, color: 'var(--text-muted)' }}>I par Q</span>
          </div>
          <div style={{
            marginTop: 8,
            fontSize: 14,
            color: (data?.variation ?? 0) >= 0 ? '#22c55e' : '#ef4444',
          }}>
            {(data?.variation ?? 0) >= 0 ? '+' : ''}{data?.variation?.toFixed(2) ?? '0'}%
          </div>

          {/* Balances */}
          <div style={{ marginTop: 24, display: 'flex', gap: 16 }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Lumiere</div>
              <div style={{ fontSize: 18, fontWeight: 600 }}>{balances?.infinite_light?.toLocaleString() ?? 0}</div>
            </div>
            <div>
              <div style={{ fontSize: 11, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: 1 }}>Quintessence</div>
              <div style={{ fontSize: 18, fontWeight: 600 }}>{Number(balances?.quintessence ?? 0).toFixed(2)}</div>
            </div>
          </div>
        </div>

        {/* Trading panel */}
        <div style={{
          flex: '1 1 300px',
          background: 'var(--bg-card)',
          borderRadius: 12,
          padding: 24,
          border: '1px solid var(--border-subtle)',
        }}>
          <h3 style={{ margin: '0 0 16px', fontSize: 16, color: 'var(--text-muted)' }}>
            Trader
          </h3>

          <div style={{ marginBottom: 16 }}>
            <label style={{ fontSize: 12, color: 'var(--text-muted)', display: 'block', marginBottom: 4 }}>
              Quantite (Quintessence)
            </label>
            <input
              type="number"
              value={amount}
              onChange={e => setAmount(e.target.value)}
              placeholder="0.00"
              style={{
                width: '100%',
                padding: '10px 12px',
                background: 'var(--bg-primary)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 8,
                color: 'var(--text-primary)',
                fontSize: 16,
                fontFamily: 'var(--font-mono, monospace)',
              }}
            />
          </div>

          <div style={{ display: 'flex', gap: 12 }}>
            <button
              onClick={() => handleTrade('buy')}
              disabled={loading}
              style={{
                flex: 1,
                padding: '12px 16px',
                background: '#22c55e',
                color: '#fff',
                border: 'none',
                borderRadius: 8,
                fontWeight: 700,
                cursor: 'pointer',
                opacity: loading ? 0.5 : 1,
              }}
            >
              Acheter
            </button>
            <button
              onClick={() => handleTrade('sell')}
              disabled={loading}
              style={{
                flex: 1,
                padding: '12px 16px',
                background: '#ef4444',
                color: '#fff',
                border: 'none',
                borderRadius: 8,
                fontWeight: 700,
                cursor: 'pointer',
                opacity: loading ? 0.5 : 1,
              }}
            >
              Vendre
            </button>
          </div>

          {error && <p style={{ color: '#ef4444', marginTop: 12, fontSize: 13 }}>{error}</p>}
          {success && <p style={{ color: '#22c55e', marginTop: 12, fontSize: 13 }}>{success}</p>}
        </div>
      </div>

      {/* Chart placeholder */}
      <div style={{
        margin: '0 24px 24px',
        background: 'var(--bg-card)',
        borderRadius: 12,
        padding: 24,
        border: '1px solid var(--border-subtle)',
        minHeight: 200,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}>
        <p style={{ color: 'var(--text-muted)', fontSize: 14 }}>
          Graphique historique des cours (720 points)
        </p>
      </div>
    </div>
  );
}
