import { useEffect, useState } from 'react'
import { Shield, Zap, Activity, AlertTriangle, RefreshCcw } from 'lucide-react'
import { type PositionMetrics } from '@/services/api'

export type AutomationEventType = 'STOP_LOSS' | 'TAKE_PROFIT' | 'TRAILING' | 'INFO'

export interface AutomationEvent {
  id: string
  timestamp: number
  type: AutomationEventType
  description: string
}

interface RiskAutomationPanelProps {
  currentPrice: number
  stopLoss: number | null
  takeProfit: number | null
  trailingPercent: number | null
  autoCloseEnabled: boolean
  events: AutomationEvent[]
  onToggleAutoClose: (enabled: boolean) => void
  onClearGuards: () => void
  onUpdateTrailing: (percent: number | null) => void
  metrics?: PositionMetrics | null
  metricsLoading?: boolean
  metricsError?: string | null
  onRefreshMetrics?: () => Promise<PositionMetrics | null> | void
  onApplyGuardSuggestions?: (suggestions: { stopLoss?: number | null; takeProfit?: number | null; trailingPercent?: number | null }) => void
  variant?: 'default' | 'embedded'
}

export default function RiskAutomationPanel({
  currentPrice,
  stopLoss,
  takeProfit,
  trailingPercent,
  autoCloseEnabled,
  events,
  onToggleAutoClose,
  onClearGuards,
  onUpdateTrailing,
  metrics,
  metricsLoading = false,
  metricsError,
  onRefreshMetrics,
  onApplyGuardSuggestions,
  variant = 'default',
}: RiskAutomationPanelProps) {
  const [localTrailing, setLocalTrailing] = useState<number>(trailingPercent ?? 1.5)

  useEffect(() => {
    if (typeof trailingPercent === 'number') {
      setLocalTrailing(trailingPercent)
    }
  }, [trailingPercent])

  const trailingActive = typeof trailingPercent === 'number'

  const formatNumber = (value?: number | null, maximumFractionDigits = 2) => {
    if (value === undefined || value === null || Number.isNaN(value)) return '—'
    return new Intl.NumberFormat('en-US', { maximumFractionDigits }).format(value)
  }

  const formatCurrency = (value?: number | null) => {
    if (value === undefined || value === null || Number.isNaN(value)) return '—'
    return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 2 }).format(value)
  }

  const formatPercent = (value?: number | null) => {
    if (value === undefined || value === null || Number.isNaN(value)) return '—'
    const signed = value > 0 ? '+' : ''
    return `${signed}${formatNumber(value)}%`
  }

  const snapshot = metrics ?? null
  const suggestedStopLoss = snapshot?.support_levels?.[0] ?? null
  const suggestedTakeProfit = snapshot?.resistance_levels?.[0] ?? null
  const suggestedTrailingPercent = snapshot?.atr14 && snapshot.current_price
    ? Number(((snapshot.atr14 / snapshot.current_price) * 100).toFixed(1))
    : null

  const canApplySuggestions = Boolean(
    onApplyGuardSuggestions && (
      typeof suggestedStopLoss === 'number' ||
      typeof suggestedTakeProfit === 'number' ||
      typeof suggestedTrailingPercent === 'number'
    ),
  )

  const handleRefreshClick = () => {
    void onRefreshMetrics?.()
  }

  const handleApplySuggestions = () => {
    onApplyGuardSuggestions?.({
      stopLoss: typeof suggestedStopLoss === 'number' ? suggestedStopLoss : undefined,
      takeProfit: typeof suggestedTakeProfit === 'number' ? suggestedTakeProfit : undefined,
      trailingPercent: typeof suggestedTrailingPercent === 'number' ? Math.max(0.5, suggestedTrailingPercent) : undefined,
    })
  }

  const isEmbedded = variant === 'embedded'

  return (
    <div className={isEmbedded ? 'space-y-4' : 'card space-y-4'}>
      <div className="bg-dark-bg/70 border border-dark-border rounded-lg p-4 space-y-3">
        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
          <div>
            <p className="text-xs uppercase tracking-wide text-gray-500">Position metrics snapshot</p>
            {snapshot ? (
              <p className="text-sm text-gray-300">
                {snapshot.symbol} · {snapshot.timeframe} ·{' '}
                {new Date(snapshot.timestamp * 1000).toLocaleTimeString()}
              </p>
            ) : (
              <p className="text-sm text-gray-500">Metrics unavailable</p>
            )}
          </div>
          <div className="flex items-center gap-2">
            {metricsLoading && <span className="text-xs text-gray-500">Refreshing…</span>}
            <button
              onClick={handleRefreshClick}
              className="btn text-xs flex items-center gap-1 disabled:opacity-60"
              type="button"
              disabled={!onRefreshMetrics}
            >
              <RefreshCcw className="w-3 h-3" /> Refresh
            </button>
          </div>
        </div>
        {metricsError && <div className="text-xs text-red-400">{metricsError}</div>}
        {snapshot ? (
          <div className="space-y-4">
            <div className="grid gap-3 sm:grid-cols-3 text-sm text-gray-200">
              <div>
                <div className="text-xs uppercase text-gray-500">Current price</div>
                <div className="font-semibold">{formatCurrency(snapshot.current_price)}</div>
              </div>
              <div>
                <div className="text-xs uppercase text-gray-500">Change</div>
                <div
                  className={`font-semibold ${snapshot.change && snapshot.change < 0 ? 'text-red-400' : snapshot.change && snapshot.change > 0 ? 'text-green-400' : 'text-gray-200'}`}
                >
                  {formatNumber(snapshot.change)} ({formatPercent(snapshot.change_percent)})
                </div>
              </div>
              <div>
                <div className="text-xs uppercase text-gray-500">ATR(14)</div>
                <div className="font-semibold">{formatNumber(snapshot.atr14)}</div>
              </div>
            </div>
            <div className="grid gap-3 sm:grid-cols-3 text-sm text-gray-200">
              <div>
                <div className="text-xs uppercase text-gray-500">RSI(14)</div>
                <div className="font-semibold">{formatNumber(snapshot.rsi14)}</div>
              </div>
              <div>
                <div className="text-xs uppercase text-gray-500">Volatility 30</div>
                <div className="font-semibold">{formatPercent(snapshot.volatility30)}</div>
              </div>
              <div>
                <div className="text-xs uppercase text-gray-500">Momentum 12</div>
                <div className="font-semibold">{formatNumber(snapshot.momentum12)}</div>
              </div>
            </div>
            <div className="grid gap-3 sm:grid-cols-2 text-xs text-gray-400">
              <div>
                <div className="uppercase tracking-wide text-gray-500 mb-1">Support levels</div>
                <ul className="space-y-1">
                  {snapshot.support_levels.length ? (
                    snapshot.support_levels.map(level => (
                      <li key={`support-${level}`}>{formatCurrency(level)}</li>
                    ))
                  ) : (
                    <li>None detected</li>
                  )}
                </ul>
              </div>
              <div>
                <div className="uppercase tracking-wide text-gray-500 mb-1">Resistance levels</div>
                <ul className="space-y-1">
                  {snapshot.resistance_levels.length ? (
                    snapshot.resistance_levels.map(level => (
                      <li key={`resistance-${level}`}>{formatCurrency(level)}</li>
                    ))
                  ) : (
                    <li>None detected</li>
                  )}
                </ul>
              </div>
            </div>
            <div className="text-xs text-gray-500">Bars analysed: {snapshot.bars_analyzed}</div>
            {canApplySuggestions && (
              <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between border-t border-dark-border pt-3 text-xs text-gray-400">
                <div>
                  Suggested guard rails · SL {formatCurrency(suggestedStopLoss)} · TP {formatCurrency(suggestedTakeProfit)} ·
                  Trailing {formatPercent(suggestedTrailingPercent)}
                </div>
                <button className="btn-primary text-xs" onClick={handleApplySuggestions} type="button">
                  Apply guard suggestions
                </button>
              </div>
            )}
          </div>
        ) : (
          <div className="text-xs text-gray-500">Snapshot unavailable. Refresh to load the latest metrics.</div>
        )}
      </div>

      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Shield className="w-5 h-5 text-blue-400" />
          <h3 className="text-lg font-semibold">Automation Guards</h3>
        </div>
        <button
          onClick={onClearGuards}
          className="text-xs text-gray-400 hover:text-white"
        >
          Clear targets
        </button>
      </div>

      <div className="grid grid-cols-2 gap-3 text-sm">
        <div className="bg-dark-bg rounded-lg p-3 border border-dark-border">
          <p className="text-xs uppercase tracking-wide text-gray-400">Stop Loss</p>
          {stopLoss ? (
            <p className="text-lg font-semibold text-red-400">${stopLoss.toFixed(2)}</p>
          ) : (
            <p className="text-gray-500">Not armed</p>
          )}
        </div>
        <div className="bg-dark-bg rounded-lg p-3 border border-dark-border">
          <p className="text-xs uppercase tracking-wide text-gray-400">Take Profit</p>
          {takeProfit ? (
            <p className="text-lg font-semibold text-green-400">${takeProfit.toFixed(2)}</p>
          ) : (
            <p className="text-gray-500">Not armed</p>
          )}
        </div>
      </div>

      <div className="flex items-center justify-between bg-dark-bg rounded-lg p-3 border border-dark-border">
        <div>
          <p className="text-xs text-gray-400">Auto close</p>
          <p className="text-sm font-medium text-gray-200">
            {autoCloseEnabled ? 'Triggers will flatten positions' : 'Manual acknowledgement required'}
          </p>
        </div>
        <button
          onClick={() => onToggleAutoClose(!autoCloseEnabled)}
          className={`px-3 py-1 rounded-full text-xs font-semibold ${
            autoCloseEnabled ? 'bg-green-500/20 text-green-400' : 'bg-gray-700 text-gray-300'
          }`}
        >
          {autoCloseEnabled ? 'Enabled' : 'Disabled'}
        </button>
      </div>

      <div className="space-y-2">
        <div className="flex items-center justify-between text-sm">
          <div className="flex items-center gap-2">
            <Zap className="w-4 h-4 text-yellow-400" />
            <span>Trailing stop (%)</span>
          </div>
          {trailingActive && (
            <button
              onClick={() => onUpdateTrailing(null)}
              className="text-xs text-gray-400 hover:text-white"
            >
              Disable
            </button>
          )}
        </div>
        <div className="flex items-center gap-2">
          <input
            type="range"
            min="0.5"
            max="5"
            step="0.1"
            value={localTrailing}
            onChange={(e) => setLocalTrailing(Number(e.target.value))}
            className="flex-1"
          />
          <span className="w-12 text-sm text-right">{localTrailing.toFixed(1)}%</span>
        </div>
        <button
          onClick={() => onUpdateTrailing(localTrailing)}
          className="btn-primary text-xs"
        >
          {trailingActive ? 'Update trailing stop' : 'Enable trailing stop'}
        </button>
      </div>

      <div className="bg-dark-bg rounded-lg p-3 border border-dark-border">
        <div className="flex items-center gap-2 mb-2">
          <Activity className="w-4 h-4 text-gray-400" />
          <p className="text-sm font-semibold">Latest event</p>
        </div>
        {events.length === 0 ? (
          <p className="text-xs text-gray-500">Awaiting first automation event...</p>
        ) : (
          <div className="text-xs text-gray-300 space-y-1">
            {events.slice(-3).reverse().map(event => (
              <div key={event.id} className="flex items-start gap-2">
                <AlertTriangle className="w-3 h-3 mt-0.5 text-amber-400" />
                <div>
                  <p className="font-medium">{event.description}</p>
                  <p className="text-[10px] text-gray-500">
                    {new Date(event.timestamp).toLocaleTimeString()}
                  </p>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      <p className="text-xs text-gray-500 text-center">
        Current price {currentPrice.toFixed(2)} — automation guards will arm broker actions as soon as the backend is wired.
      </p>
    </div>
  )
}
