import React, {useState} from 'react'
import {Modal} from '../index'
import type {Backtest} from '../../../generated/ManagingApi'

interface ConfigDisplayModalProps {
  showModal: boolean
  onClose: () => void
  backtest: Backtest | null
}

const ConfigDisplayModal: React.FC<ConfigDisplayModalProps> = ({
  showModal,
  onClose,
  backtest,
}) => {
  const [copied, setCopied] = useState(false)

  const formatConfigForDisplay = (config: any) => {
    // Create a clean config object without undefined values
    const cleanConfig: Record<string, any> = {
      accountName: config.accountName,
      moneyManagement: config.moneyManagement,
      ticker: config.ticker,
      timeframe: config.timeframe,
      isForWatchingOnly: config.isForWatchingOnly,
      botTradingBalance: config.botTradingBalance,
      isForBacktest: config.isForBacktest,
      cooldownPeriod: config.cooldownPeriod,
      maxLossStreak: config.maxLossStreak,
      flipPosition: config.flipPosition,
      name: config.name,
      riskManagement: config.riskManagement,
      scenario: config.scenario,
      scenarioName: config.scenarioName,
      maxPositionTimeHours: config.maxPositionTimeHours,
      closeEarlyWhenProfitable: config.closeEarlyWhenProfitable,
      flipOnlyWhenInProfit: config.flipOnlyWhenInProfit,
      useSynthApi: config.useSynthApi,
      useForPositionSizing: config.useForPositionSizing,
      useForSignalFiltering: config.useForSignalFiltering,
      useForDynamicStopLoss: config.useForDynamicStopLoss,
    }

    // Remove undefined values
    Object.keys(cleanConfig).forEach(key => {
      if (cleanConfig[key] === undefined || cleanConfig[key] === null) {
        delete cleanConfig[key]
      }
    })

    return JSON.stringify(cleanConfig, null, 2)
  }

  const handleCopyConfig = async () => {
    if (!backtest?.config) return

    try {
      const configJson = formatConfigForDisplay(backtest.config)
      await navigator.clipboard.writeText(configJson)
      setCopied(true)
      setTimeout(() => setCopied(false), 2000)
    } catch (error) {
      console.error('Failed to copy config:', error)
    }
  }

  if (!backtest) return null

  const configJson = formatConfigForDisplay(backtest.config)

  return (
    <Modal
      showModal={showModal}
      onClose={onClose}
      titleHeader="Backtest Configuration"
    >
      <div className="space-y-4">
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-semibold">Configuration JSON</h3>
          <button
            type="button"
            className={`btn btn-sm ${copied ? 'btn-success' : 'btn-primary'}`}
            onClick={handleCopyConfig}
          >
            {copied ? (
              <>
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                </svg>
                Copied!
              </>
            ) : (
              <>
                <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                </svg>
                Copy Config
              </>
            )}
          </button>
        </div>

        <div className="bg-base-200 rounded-lg p-4 max-h-96 overflow-auto">
          <pre className="text-sm text-base-content whitespace-pre-wrap break-words">
            {configJson}
          </pre>
        </div>

        <div className="text-sm text-base-content/70">
          <p>This configuration can be copied and imported into the backtest modal to replicate this exact setup.</p>
        </div>
      </div>
    </Modal>
  )
}

export default ConfigDisplayModal 