import { useEffect, useMemo, useState } from 'react';
import { RefreshCw, Target } from 'lucide-react';
import { useAppContext } from '../context/AppContext';
import { fetchChartBars } from '../lib/marketApi';
import { getPlatformAccessToken } from '../lib/authSession';
import { tradingRuntime } from '../lib/runtime';
import { createRequestId } from '../../../shared/request-id.js';
import { fetchTradeProfiles, type TradeProfilePayload } from '../lib/profileApi';

type SimpleSide = 'buy' | 'sell';
type SimpleOrderType = 'market' | 'limit';

type SimpleTradeDraft = {
  symbol: string;
  side: SimpleSide;
  orderType: SimpleOrderType;
  quantity: string;
  limitPrice: string;
  currentMarketPrice: string;
  stopLossPercent: string;
  takeProfitPercent: string;
  isCrypto: boolean;
};

type SimpleTradePayload = {
  profile_id?: string;
  symbol: string;
  side: SimpleSide;
  qty: number;
  type: SimpleOrderType;
  price?: number;
  sl?: number;
  tp?: number;
};

const DEFAULT_DRAFT: SimpleTradeDraft = {
  symbol: '',
  side: 'buy',
  orderType: 'market',
  quantity: '',
  limitPrice: '',
  currentMarketPrice: '',
  stopLossPercent: '',
  takeProfitPercent: '',
  isCrypto: false,
};

function parsePositiveNumber(value: string): number | null {
  const trimmed = value.trim();
  if (!trimmed) return null;
  const parsed = Number(trimmed);
  return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
}

function roundPrice(value: number): number {
  return Number(value.toFixed(4));
}

export function computeProtectionPrices(input: {
  side: SimpleSide;
  referencePrice: number;
  stopLossPercent?: number | null;
  takeProfitPercent?: number | null;
}) {
  const { side, referencePrice, stopLossPercent, takeProfitPercent } = input;
  let sl: number | undefined;
  let tp: number | undefined;

  if (stopLossPercent && stopLossPercent > 0) {
    sl = side === 'buy'
      ? roundPrice(referencePrice * (1 - stopLossPercent / 100))
      : roundPrice(referencePrice * (1 + stopLossPercent / 100));
  }

  if (takeProfitPercent && takeProfitPercent > 0) {
    tp = side === 'buy'
      ? roundPrice(referencePrice * (1 + takeProfitPercent / 100))
      : roundPrice(referencePrice * (1 - takeProfitPercent / 100));
  }

  return { sl, tp };
}

export function buildSimpleTradePayload(draft: SimpleTradeDraft): SimpleTradePayload {
  const symbol = draft.symbol.trim().toUpperCase();
  if (!symbol) {
    throw new Error('Symbol is required');
  }

  const qty = parsePositiveNumber(draft.quantity);
  if (qty === null) {
    throw new Error('Quantity is required');
  }

  const price = draft.orderType === 'limit' ? parsePositiveNumber(draft.limitPrice) : null;
  if (draft.orderType === 'limit' && price === null) {
    throw new Error('Limit price is required');
  }

  const referencePrice = price ?? parsePositiveNumber(draft.currentMarketPrice);
  if (referencePrice === null) {
    throw new Error('Current market price is unavailable. Refresh market data and try again.');
  }

  const stopLossPercent = parsePositiveNumber(draft.stopLossPercent);
  const takeProfitPercent = parsePositiveNumber(draft.takeProfitPercent);
  const { sl, tp } = computeProtectionPrices({
    side: draft.side,
    referencePrice,
    stopLossPercent,
    takeProfitPercent,
  });

  const payload: SimpleTradePayload = {
    symbol,
    side: draft.side,
    qty,
    type: draft.orderType,
    sl,
    tp,
  };

  if (price !== null) {
    payload.price = price;
  }

  return payload;
}

function buildExecutionPreview(payload: SimpleTradePayload | null) {
  if (!payload) return null;

  const verb = payload.side === 'buy' ? 'BUY' : 'SELL';
  const orderText = payload.type === 'market'
    ? `${verb} ${payload.symbol} now at market`
    : `${verb} ${payload.symbol} with a limit at ${Number(payload.price).toFixed(4)}`;

  const extras = [
    `Qty ${payload.qty}`,
    payload.sl ? `SL ${payload.sl.toFixed(4)}` : null,
    payload.tp ? `TP ${payload.tp.toFixed(4)}` : null,
  ].filter(Boolean);

  return `${orderText} · ${extras.join(' · ')}`;
}

export function SimpleView() {
  const { botState } = useAppContext();
  const [profiles, setProfiles] = useState<TradeProfilePayload[]>([]);
  const [selectedProfileId, setSelectedProfileId] = useState('');
  const [draft, setDraft] = useState<SimpleTradeDraft>(DEFAULT_DRAFT);
  const [submitting, setSubmitting] = useState(false);
  const [loadingPrice, setLoadingPrice] = useState(false);
  const [message, setMessage] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const normalizedSymbol = draft.symbol.trim().toUpperCase();
  const livePrice = normalizedSymbol ? Number(botState.symbols?.[normalizedSymbol]?.price || 0) : 0;
  const resolvedMarketPrice = parsePositiveNumber(draft.currentMarketPrice);
  const marketPriceSource = livePrice > 0 ? 'live' : (resolvedMarketPrice !== null ? 'recent_close' : null);
  const activeProfiles = useMemo(
    () => profiles.filter((profile) => Boolean(profile.is_active)),
    [profiles],
  );

  useEffect(() => {
    let cancelled = false;

    async function loadProfiles() {
      try {
        const rows = await fetchTradeProfiles();
        if (cancelled) return;
        setProfiles(rows);
      } catch (err: any) {
        if (cancelled) return;
        setError(err?.message ?? 'Failed to load trade profiles');
      }
    }

    void loadProfiles();
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (!activeProfiles.length) {
      setSelectedProfileId('');
      return;
    }

    if (selectedProfileId && activeProfiles.some((profile) => profile.id === selectedProfileId)) {
      return;
    }

    setSelectedProfileId(String(activeProfiles[0]?.id || ''));
  }, [activeProfiles, selectedProfileId]);

  useEffect(() => {
    if (!livePrice) return;
    setDraft(prev => (
      prev.currentMarketPrice === livePrice.toFixed(4)
        ? prev
        : { ...prev, currentMarketPrice: livePrice.toFixed(4) }
    ));
  }, [livePrice]);

  useEffect(() => {
    if (!normalizedSymbol || livePrice > 0 || draft.currentMarketPrice.trim() || loadingPrice) {
      return;
    }

    void handleLoadMarketPrice();
  }, [normalizedSymbol, livePrice]);

  const payloadPreview = useMemo(() => {
    try {
      return buildSimpleTradePayload(draft);
    } catch {
      return null;
    }
  }, [draft]);

  const executionPreview = useMemo(
    () => buildExecutionPreview(payloadPreview),
    [payloadPreview],
  );

  function updateDraft<K extends keyof SimpleTradeDraft>(key: K, value: SimpleTradeDraft[K]) {
    setDraft(prev => ({ ...prev, [key]: value }));
  }

  async function handleLoadMarketPrice() {
    if (!normalizedSymbol) {
      setError('Enter a symbol first');
      return;
    }

    setLoadingPrice(true);
    setError(null);
    setMessage(null);
    try {
      const bars = await fetchChartBars(normalizedSymbol, '1D');
      const latestClose = Number(bars[bars.length - 1]?.close || 0);
      if (!Number.isFinite(latestClose) || latestClose <= 0) {
        throw new Error(`No recent market price found for ${normalizedSymbol}`);
      }
      updateDraft('currentMarketPrice', latestClose.toFixed(4));
      setMessage(`Loaded market price for ${normalizedSymbol}`);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to load market price');
    } finally {
      setLoadingPrice(false);
    }
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();

    setSubmitting(true);
    setError(null);
    setMessage(null);

    try {
      if (!activeProfiles.length) {
        throw new Error('No active trade profile available. Activate a profile first.');
      }

      const payload = buildSimpleTradePayload(draft);
      if (selectedProfileId) {
        payload.profile_id = selectedProfileId;
      }
      const accessToken = await getPlatformAccessToken();
      const response = await fetch(`${tradingRuntime.tradingApiUrl}/api/trade`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${accessToken}`,
          'x-request-id': createRequestId('web-simple-trade'),
        },
        body: JSON.stringify(payload),
      });

      const result = await response.json().catch(() => ({}));
      if (!response.ok || !result?.success) {
        throw new Error(result?.error || `Trade request failed (${response.status})`);
      }

      setMessage(`Order submitted${result.orderId ? ` · ${result.orderId}` : ''}`);
      setDraft(prev => ({
        ...DEFAULT_DRAFT,
        symbol: prev.symbol,
        isCrypto: prev.isCrypto,
        currentMarketPrice: prev.currentMarketPrice,
      }));
    } catch (err: any) {
      setError(err?.message ?? 'Failed to submit trade');
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div>
      <h2 style={{ fontSize: 22, fontWeight: 800, color: '#111827', margin: '0 0 20px' }}>Simple</h2>

      <div
        style={{
          borderRadius: 20,
          border: '1px solid #E5E7EB',
          background: 'linear-gradient(135deg, #FFFFFF 0%, #F8FAFC 100%)',
          padding: 24,
          marginBottom: 20,
        }}
      >
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 16, marginBottom: 18 }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 900, letterSpacing: '0.12em', textTransform: 'uppercase', color: '#2563EB', marginBottom: 8 }}>
              Direct Execution
            </div>
            <div style={{ fontSize: 24, fontWeight: 900, color: '#111827', marginBottom: 6 }}>
              Submit a simple buy or sell without the full strategy builder
            </div>
            <div style={{ color: '#4B5563', fontSize: 14, lineHeight: 1.6, maxWidth: 760 }}>
              This page sends a direct trade request to your configured trading profile. Market price is sourced automatically from live data or the most recent close.
            </div>
          </div>
        </div>

        <form onSubmit={handleSubmit}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14, marginBottom: 16 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Symbol</span>
              <input
                value={draft.symbol}
                onChange={e => updateDraft('symbol', e.target.value.toUpperCase())}
                placeholder="AAPL or BTC/USD"
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
              />
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Action</span>
              <select
                value={draft.side}
                onChange={e => updateDraft('side', e.target.value as SimpleSide)}
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14, background: '#fff' }}
              >
                <option value="buy">Buy</option>
                <option value="sell">Sell</option>
              </select>
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Order type</span>
              <select
                value={draft.orderType}
                onChange={e => updateDraft('orderType', e.target.value as SimpleOrderType)}
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14, background: '#fff' }}
              >
                <option value="market">Market</option>
                <option value="limit">Limit</option>
              </select>
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Profile</span>
              <select
                value={selectedProfileId}
                onChange={e => setSelectedProfileId(e.target.value)}
                disabled={!activeProfiles.length}
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14, background: '#fff' }}
              >
                {!activeProfiles.length && <option value="">No active profile</option>}
                {activeProfiles.map((profile) => (
                  <option key={profile.id} value={profile.id}>
                    {profile.name}
                  </option>
                ))}
              </select>
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Quantity</span>
              <input
                value={draft.quantity}
                onChange={e => updateDraft('quantity', e.target.value)}
                placeholder="e.g. 5"
                inputMode="decimal"
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
              />
            </label>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 14, marginBottom: 16 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Current market price</span>
              <div style={{ display: 'flex', gap: 8 }}>
                <input
                  value={draft.currentMarketPrice}
                  readOnly
                  placeholder={normalizedSymbol ? 'Loading market price…' : 'Enter symbol first'}
                  style={{
                    flex: 1,
                    border: '1px solid #D1D5DB',
                    borderRadius: 10,
                    padding: '10px 12px',
                    fontSize: 14,
                    background: '#F9FAFB',
                    color: draft.currentMarketPrice ? '#111827' : '#6B7280',
                  }}
                />
                <button
                  type="button"
                  onClick={handleLoadMarketPrice}
                  disabled={loadingPrice || !normalizedSymbol}
                  style={{
                    border: '1px solid #D1D5DB',
                    borderRadius: 10,
                    background: '#fff',
                    padding: '0 12px',
                    fontSize: 12,
                    fontWeight: 800,
                    color: loadingPrice || !normalizedSymbol ? '#9CA3AF' : '#374151',
                    cursor: loadingPrice ? 'wait' : (!normalizedSymbol ? 'not-allowed' : 'pointer'),
                  }}
                >
                  <RefreshCw size={14} style={{ animation: loadingPrice ? 'spin 1s linear infinite' : 'none' }} />
                </button>
              </div>
              {marketPriceSource && (
                <small style={{ color: '#6B7280' }}>
                  Source: {marketPriceSource === 'live' ? 'live market feed' : 'recent market close'}
                </small>
              )}
            </label>

            {draft.orderType === 'limit' && (
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Limit price</span>
                <input
                  value={draft.limitPrice}
                  onChange={e => updateDraft('limitPrice', e.target.value)}
                  placeholder="e.g. 210.50"
                  inputMode="decimal"
                  style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
                />
              </label>
            )}

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Stop loss %</span>
              <input
                value={draft.stopLossPercent}
                onChange={e => updateDraft('stopLossPercent', e.target.value)}
                placeholder="Optional"
                inputMode="decimal"
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
              />
            </label>

            <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Take profit %</span>
              <input
                value={draft.takeProfitPercent}
                onChange={e => updateDraft('takeProfitPercent', e.target.value)}
                placeholder="Optional"
                inputMode="decimal"
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
              />
            </label>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12, fontWeight: 700, color: '#374151' }}>
              <input
                type="checkbox"
                checked={draft.isCrypto}
                onChange={e => updateDraft('isCrypto', e.target.checked)}
              />
              Crypto pair
            </label>
          </div>

          <div
            style={{
              borderRadius: 16,
              background: '#F8FAFC',
              border: '1px solid #E5E7EB',
              padding: 16,
              marginBottom: 18,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
              <Target size={16} color="#2563EB" />
              <span style={{ fontSize: 12, fontWeight: 900, color: '#1F2937', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                Execution Preview
              </span>
            </div>
            <div style={{ color: '#111827', fontSize: 14, fontWeight: 700 }}>
              {executionPreview ?? 'Complete the fields to preview the direct trade request.'}
            </div>
            {!activeProfiles.length && (
              <div style={{ color: '#B91C1C', fontSize: 13, fontWeight: 800, marginTop: 8 }}>
                No active trade profile is available. Activate one in Strategies before submitting.
              </div>
            )}
            {payloadPreview?.sl && (
              <div style={{ color: '#B91C1C', fontSize: 13, fontWeight: 800, marginTop: 8 }}>
                Stop loss: {payloadPreview.sl.toFixed(4)}
              </div>
            )}
            {payloadPreview?.tp && (
              <div style={{ color: '#065F46', fontSize: 13, fontWeight: 800, marginTop: 4 }}>
                Take profit: {payloadPreview.tp.toFixed(4)}
              </div>
            )}
          </div>

          {(error || message) && (
            <div
              style={{
                marginBottom: 16,
                borderRadius: 12,
                padding: '12px 14px',
                fontSize: 13,
                fontWeight: 700,
                color: error ? '#B91C1C' : '#065F46',
                background: error ? '#FEF2F2' : '#ECFDF5',
                border: `1px solid ${error ? '#FCA5A5' : '#A7F3D0'}`,
              }}
            >
              {error || message}
            </div>
          )}

          <button
            type="submit"
            disabled={submitting || !activeProfiles.length}
            style={{
              border: 'none',
              borderRadius: 999,
              background: '#111827',
              color: '#fff',
              padding: '12px 18px',
              fontSize: 13,
              fontWeight: 800,
              cursor: submitting ? 'wait' : (!activeProfiles.length ? 'not-allowed' : 'pointer'),
              opacity: !activeProfiles.length ? 0.6 : 1,
            }}
          >
            {submitting ? 'Submitting…' : `Submit ${draft.side === 'buy' ? 'Buy' : 'Sell'}`}
          </button>
        </form>
      </div>
    </div>
  );
}
