import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { RefreshCw, Target, Trash2 } from 'lucide-react';
import { useAuth } from '../components/AuthContext';
import { useAppContext } from '../context/AppContext';
import { fetchChartBars } from '../lib/marketApi';
import {
  createManualEntry,
  deleteManualEntry,
  fetchManualEntries,
  type ManualEntryPayload,
} from '../lib/manualEntriesApi';

type SimpleSide = 'buy' | 'sell';
type SimpleTriggerMode = 'target_price' | 'profit_percent' | 'drop_percent';

type SimpleRuleDraft = {
  symbol: string;
  side: SimpleSide;
  triggerMode: SimpleTriggerMode;
  quantity: string;
  targetPrice: string;
  purchasePrice: string;
  currentMarketPrice: string;
  percentValue: string;
  isCrypto: boolean;
  notes: string;
};

type SimpleRuleEntry = ManualEntryPayload & {
  stock_instance_id?: string;
  label?: string | null;
  notes?: string | null;
};

const SIMPLE_LABEL_PREFIX = 'SIMPLE ';

const DEFAULT_DRAFT: SimpleRuleDraft = {
  symbol: '',
  side: 'buy',
  triggerMode: 'target_price',
  quantity: '',
  targetPrice: '',
  purchasePrice: '',
  currentMarketPrice: '',
  percentValue: '',
  isCrypto: false,
  notes: '',
};

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 computeSimpleTriggerPrice(draft: Pick<SimpleRuleDraft, 'triggerMode' | 'targetPrice' | 'purchasePrice' | 'currentMarketPrice' | 'percentValue'>): number | null {
  if (draft.triggerMode === 'target_price') {
    return parsePositiveNumber(draft.targetPrice);
  }

  const percentValue = parsePositiveNumber(draft.percentValue);
  if (percentValue === null) return null;

  if (draft.triggerMode === 'profit_percent') {
    const purchasePrice = parsePositiveNumber(draft.purchasePrice);
    if (purchasePrice === null) return null;
    return roundPrice(purchasePrice * (1 + percentValue / 100));
  }

  const currentMarketPrice = parsePositiveNumber(draft.currentMarketPrice);
  if (currentMarketPrice === null) return null;
  return roundPrice(currentMarketPrice * (1 - percentValue / 100));
}

function buildSimpleRuleNote(symbol: string, side: SimpleSide, triggerMode: SimpleTriggerMode, triggerPrice: number, percentValue: number | null): string {
  if (triggerMode === 'target_price') {
    return `${side.toUpperCase()} ${symbol} when price hits ${triggerPrice.toFixed(4)}`;
  }
  if (triggerMode === 'profit_percent') {
    return `SELL ${symbol} at ${percentValue?.toFixed(2)}% profit (${triggerPrice.toFixed(4)}) from purchase price`;
  }
  return `BUY ${symbol} after ${percentValue?.toFixed(2)}% drop from current market (${triggerPrice.toFixed(4)})`;
}

export function buildSimpleEntryPayload(userId: string, draft: SimpleRuleDraft): ManualEntryPayload {
  const symbol = draft.symbol.trim().toUpperCase();
  if (!symbol) {
    throw new Error('Symbol is required');
  }

  const triggerPrice = computeSimpleTriggerPrice(draft);
  if (triggerPrice === null) {
    throw new Error('A valid trigger price could not be calculated');
  }

  const quantity = parsePositiveNumber(draft.quantity);
  const purchasePrice = parsePositiveNumber(draft.purchasePrice);
  const percentValue = parsePositiveNumber(draft.percentValue);
  const notePrefix = buildSimpleRuleNote(symbol, draft.side, draft.triggerMode, triggerPrice, percentValue);
  const notes = draft.notes.trim() ? `${notePrefix}. ${draft.notes.trim()}` : notePrefix;

  return {
    symbol,
    active: true,
    status: 'active',
    user_id: userId,
    quantity,
    is_crypto: draft.isCrypto,
    is_real_trade: false,
    label: `${SIMPLE_LABEL_PREFIX}${draft.side.toUpperCase()}`,
    notes,
    entry_price: purchasePrice,
    buy_price: draft.side === 'buy' ? triggerPrice : purchasePrice,
    sell_price: draft.side === 'sell' ? triggerPrice : null,
    gain_threshold_for_sell: draft.triggerMode === 'profit_percent' ? percentValue : null,
    drop_threshold_for_buy: draft.triggerMode === 'drop_percent' ? percentValue : null,
  };
}

function isSimpleRule(entry: SimpleRuleEntry): boolean {
  return String(entry.label || '').toUpperCase().startsWith(SIMPLE_LABEL_PREFIX);
}

export function SimpleView() {
  const { user } = useAuth();
  const { botState } = useAppContext();
  const [draft, setDraft] = useState<SimpleRuleDraft>(DEFAULT_DRAFT);
  const [savedRules, setSavedRules] = useState<SimpleRuleEntry[]>([]);
  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 computedTriggerPrice = computeSimpleTriggerPrice(draft);

  const triggerOptions = draft.side === 'buy'
    ? [
        { value: 'target_price' as const, label: 'Buy when price hits target' },
        { value: 'drop_percent' as const, label: 'Buy after % drop from current market' },
      ]
    : [
        { value: 'target_price' as const, label: 'Sell when price hits target' },
        { value: 'profit_percent' as const, label: 'Sell at % profit from purchase' },
      ];

  async function loadSavedRules() {
    try {
      const rows = await fetchManualEntries();
      setSavedRules(rows.filter(isSimpleRule));
    } catch (err: any) {
      setError(err?.message ?? 'Failed to load simple rules');
    }
  }

  useEffect(() => {
    if (user) {
      loadSavedRules();
    }
  }, [user]);

  useEffect(() => {
    if (draft.side === 'buy' && draft.triggerMode === 'profit_percent') {
      setDraft(prev => ({ ...prev, triggerMode: 'target_price' }));
    }
    if (draft.side === 'sell' && draft.triggerMode === 'drop_percent') {
      setDraft(prev => ({ ...prev, triggerMode: 'target_price' }));
    }
  }, [draft.side, draft.triggerMode]);

  useEffect(() => {
    if (draft.triggerMode !== 'drop_percent' || !livePrice || draft.currentMarketPrice.trim()) {
      return;
    }
    setDraft(prev => ({ ...prev, currentMarketPrice: livePrice.toFixed(4) }));
  }, [draft.triggerMode, draft.currentMarketPrice, livePrice]);

  const rulePreview = useMemo(() => {
    if (!normalizedSymbol || computedTriggerPrice === null) return null;
    return buildSimpleRuleNote(normalizedSymbol, draft.side, draft.triggerMode, computedTriggerPrice, parsePositiveNumber(draft.percentValue));
  }, [normalizedSymbol, computedTriggerPrice, draft.side, draft.triggerMode, draft.percentValue]);

  function updateDraft<K extends keyof SimpleRuleDraft>(key: K, value: SimpleRuleDraft[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 current market price for ${normalizedSymbol}`);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to load current market price');
    } finally {
      setLoadingPrice(false);
    }
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (!user?.id) {
      setError('Not authenticated');
      return;
    }

    setSubmitting(true);
    setError(null);
    setMessage(null);
    try {
      const payload = buildSimpleEntryPayload(user.id, draft);
      await createManualEntry(payload);
      setDraft(DEFAULT_DRAFT);
      setMessage('Simple rule saved to your watchlist');
      await loadSavedRules();
    } catch (err: any) {
      setError(err?.message ?? 'Failed to save simple rule');
    } finally {
      setSubmitting(false);
    }
  }

  async function handleDelete(ruleId: string) {
    if (!confirm('Delete this simple rule?')) return;
    try {
      await deleteManualEntry(ruleId);
      await loadSavedRules();
      setMessage('Simple rule deleted');
      setError(null);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to delete simple rule');
    }
  }

  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 }}>
              Simple Triggers
            </div>
            <div style={{ fontSize: 24, fontWeight: 900, color: '#111827', marginBottom: 6 }}>
              Save a buy or sell rule without the full strategy builder
            </div>
            <div style={{ color: '#4B5563', fontSize: 14, lineHeight: 1.6, maxWidth: 760 }}>
              This creates a tracked rule in your watchlist using the existing manual-entry system. It does not place a broker-native conditional order by itself.
            </div>
          </div>
          <Link
            to="/watchlist"
            style={{
              whiteSpace: 'nowrap',
              padding: '10px 14px',
              borderRadius: 999,
              border: '1px solid #D1D5DB',
              color: '#111827',
              textDecoration: 'none',
              fontSize: 12,
              fontWeight: 800,
            }}
          >
            Open Watchlist
          </Link>
        </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' }}>Trigger</span>
              <select
                value={draft.triggerMode}
                onChange={e => updateDraft('triggerMode', e.target.value as SimpleTriggerMode)}
                style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14, background: '#fff' }}
              >
                {triggerOptions.map(option => (
                  <option key={option.value} value={option.value}>{option.label}</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="Optional"
                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 }}>
            {draft.triggerMode === 'target_price' && (
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Target price</span>
                <input
                  value={draft.targetPrice}
                  onChange={e => updateDraft('targetPrice', e.target.value)}
                  placeholder="e.g. 210.50"
                  inputMode="decimal"
                  style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
                />
              </label>
            )}

            {draft.triggerMode === 'profit_percent' && (
              <>
                <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Purchase price</span>
                  <input
                    value={draft.purchasePrice}
                    onChange={e => updateDraft('purchasePrice', e.target.value)}
                    placeholder="e.g. 182.10"
                    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' }}>Profit percent</span>
                  <input
                    value={draft.percentValue}
                    onChange={e => updateDraft('percentValue', e.target.value)}
                    placeholder="e.g. 8"
                    inputMode="decimal"
                    style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
                  />
                </label>
              </>
            )}

            {draft.triggerMode === 'drop_percent' && (
              <>
                <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}
                      onChange={e => updateDraft('currentMarketPrice', e.target.value)}
                      placeholder="e.g. 212.42"
                      inputMode="decimal"
                      style={{ flex: 1, border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
                    />
                    <button
                      type="button"
                      onClick={handleLoadMarketPrice}
                      disabled={loadingPrice}
                      style={{
                        border: '1px solid #D1D5DB',
                        borderRadius: 10,
                        background: '#fff',
                        padding: '0 12px',
                        fontSize: 12,
                        fontWeight: 800,
                        color: '#374151',
                        cursor: loadingPrice ? 'wait' : 'pointer',
                      }}
                    >
                      <RefreshCw size={14} style={{ animation: loadingPrice ? 'spin 1s linear infinite' : 'none' }} />
                    </button>
                  </div>
                  {livePrice > 0 && (
                    <small style={{ color: '#6B7280' }}>Live feed price in app state: {livePrice.toFixed(4)}</small>
                  )}
                </label>
                <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Drop percent</span>
                  <input
                    value={draft.percentValue}
                    onChange={e => updateDraft('percentValue', e.target.value)}
                    placeholder="e.g. 5"
                    inputMode="decimal"
                    style={{ border: '1px solid #D1D5DB', borderRadius: 10, padding: '10px 12px', fontSize: 14 }}
                  />
                </label>
              </>
            )}

            {draft.side === 'sell' && draft.triggerMode === 'target_price' && (
              <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 700, color: '#374151' }}>Purchase price</span>
                <input
                  value={draft.purchasePrice}
                  onChange={e => updateDraft('purchasePrice', e.target.value)}
                  placeholder="Optional, for context"
                  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' }}>Extra note</span>
              <input
                value={draft.notes}
                onChange={e => updateDraft('notes', e.target.value)}
                placeholder="Optional note"
                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' }}>
                Rule Preview
              </span>
            </div>
            <div style={{ color: '#111827', fontSize: 14, fontWeight: 700 }}>
              {rulePreview ?? 'Complete the fields to preview the simple rule.'}
            </div>
            {computedTriggerPrice !== null && (
              <div style={{ color: '#2563EB', fontSize: 24, fontWeight: 900, marginTop: 8 }}>
                Trigger Price: {computedTriggerPrice.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}
            style={{
              border: 'none',
              borderRadius: 999,
              background: '#111827',
              color: '#fff',
              padding: '12px 18px',
              fontSize: 13,
              fontWeight: 800,
              cursor: submitting ? 'wait' : 'pointer',
            }}
          >
            {submitting ? 'Saving…' : 'Save Simple Rule'}
          </button>
        </form>
      </div>

      <div
        style={{
          borderRadius: 20,
          border: '1px solid #E5E7EB',
          background: '#fff',
          padding: 24,
        }}
      >
        <div style={{ fontSize: 16, fontWeight: 800, color: '#111827', marginBottom: 16 }}>
          Saved Simple Rules
        </div>

        {savedRules.length === 0 ? (
          <div style={{ color: '#6B7280', fontSize: 14 }}>
            No saved simple rules yet.
          </div>
        ) : (
          <div style={{ display: 'grid', gap: 12 }}>
            {savedRules.map(rule => (
              <div
                key={rule.stock_instance_id}
                style={{
                  border: '1px solid #E5E7EB',
                  borderRadius: 16,
                  padding: 16,
                  display: 'flex',
                  justifyContent: 'space-between',
                  gap: 16,
                  alignItems: 'flex-start',
                }}
              >
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                    <span style={{ fontSize: 15, fontWeight: 900, color: '#111827' }}>{rule.symbol}</span>
                    <span style={{ fontSize: 11, fontWeight: 900, color: '#2563EB', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                      {rule.label}
                    </span>
                  </div>
                  <div style={{ color: '#374151', fontSize: 13, marginBottom: 6 }}>
                    {rule.notes || 'Simple trigger rule'}
                  </div>
                  <div style={{ color: '#6B7280', fontSize: 12, display: 'flex', gap: 14, flexWrap: 'wrap' }}>
                    {rule.buy_price != null && <span>Buy trigger: {Number(rule.buy_price).toFixed(4)}</span>}
                    {rule.sell_price != null && <span>Sell trigger: {Number(rule.sell_price).toFixed(4)}</span>}
                    {rule.quantity != null && <span>Qty: {rule.quantity}</span>}
                  </div>
                </div>

                {rule.stock_instance_id && (
                  <button
                    type="button"
                    onClick={() => handleDelete(rule.stock_instance_id!)}
                    style={{
                      border: '1px solid #FECACA',
                      background: '#FEF2F2',
                      color: '#B91C1C',
                      borderRadius: 10,
                      padding: '8px 10px',
                      cursor: 'pointer',
                    }}
                    aria-label={`Delete simple rule for ${rule.symbol}`}
                  >
                    <Trash2 size={14} />
                  </button>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
