import { useEffect, useMemo, useState } from 'react'
import { PlugZap, Radio, Loader2, ShieldAlert, ExternalLink } from 'lucide-react'
import { BrokerProvider, BrokerPosition } from '../services/broker'

interface BrokerBridgePanelProps {
  providers: BrokerProvider[]
  loadingProviders?: boolean
  activeProvider: BrokerProvider | null
  connectionState: 'disconnected' | 'connecting' | 'connected'
  lastHeartbeat?: string | null
  balance?: number | null
  positions?: BrokerPosition[]
  onConnect: (providerId: string, apiKey: string, accountId: string, demo: boolean) => Promise<void>
  onDisconnect: () => Promise<void>
  onSync: () => Promise<void>
}

export default function BrokerBridgePanel({
  providers,
  loadingProviders = false,
  activeProvider,
  connectionState,
  lastHeartbeat,
  balance,
  positions = [],
  onConnect,
  onDisconnect,
  onSync,
}: BrokerBridgePanelProps) {
  const [selectedProvider, setSelectedProvider] = useState<string>('')
  const [apiKey, setApiKey] = useState('')
  const [accountId, setAccountId] = useState('')
  const [demoMode, setDemoMode] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const isBusy = connectionState === 'connecting'
  const isConnected = connectionState === 'connected'

  const selectedDetails = useMemo(() => providers.find(p => p.id === selectedProvider), [providers, selectedProvider])

  useEffect(() => {
    if (providers.length && !selectedProvider) {
      setSelectedProvider(providers[0].id)
    }
  }, [providers, selectedProvider])

  useEffect(() => {
    if (selectedDetails && selectedDetails.supportsDemo === false) {
      setDemoMode(false)
    }
  }, [selectedDetails])

  const handleConnect = async () => {
    setError(null)
    try {
      await onConnect(selectedProvider, apiKey.trim(), accountId.trim(), demoMode)
      setApiKey('')
      setAccountId('')
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to connect')
    }
  }

  const handleDisconnect = async () => {
    setError(null)
    try {
      await onDisconnect()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to disconnect')
    }
  }

  const handleSync = async () => {
    setError(null)
    try {
      await onSync()
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Unable to sync positions')
    }
  }

  return (
    <div className="card space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <PlugZap className="w-5 h-5 text-amber-400" />
          <h3 className="text-lg font-semibold">Broker bridge</h3>
        </div>
        {isConnected && activeProvider && (
          <span className="text-xs px-2 py-1 rounded-full bg-green-500/20 text-green-300">
            {activeProvider.name}
          </span>
        )}
      </div>

      <div className="grid grid-cols-1 gap-3">
        <label className="text-sm font-medium text-gray-300">
          Provider
          <select
            className="input mt-1"
            value={selectedProvider}
            onChange={e => setSelectedProvider(e.target.value)}
            disabled={isBusy || isConnected || loadingProviders}
          >
            {providers.length === 0 ? (
              <option value="">{loadingProviders ? 'Loading…' : 'No providers'}</option>
            ) : (
              providers.map(provider => (
                <option key={provider.id} value={provider.id}>
                  {provider.name}
                </option>
              ))
            )}
          </select>
        </label>

        {selectedDetails && (
          <div className="text-xs text-gray-400 space-y-2 bg-dark-bg border border-dark-border rounded-lg p-3">
            <p className="text-gray-200 font-semibold flex items-center gap-2">
              <Radio className="w-3 h-3" /> {selectedDetails.description}
            </p>
            <div className="flex flex-wrap gap-2">
              {Object.entries(selectedDetails.features).map(([feature, enabled]) => (
                <span
                  key={feature}
                  className={`px-2 py-0.5 rounded-full border text-[10px] uppercase tracking-wide ${
                    enabled ? 'border-green-500/40 text-green-300' : 'border-gray-600 text-gray-500'
                  }`}
                >
                  {feature.replace(/([A-Z])/g, ' $1').trim()}
                </span>
              ))}
            </div>
            <a
              className="inline-flex items-center gap-1 text-blue-300 hover:text-blue-200"
              href={selectedDetails.docsUrl}
              target="_blank"
              rel="noreferrer"
            >
              Docs <ExternalLink className="w-3 h-3" />
            </a>
          </div>
        )}

        <div className="flex items-center justify-between bg-dark-bg border border-dark-border rounded-lg p-3 text-sm">
          <div>
            <p className="text-gray-300 font-semibold">Demo / paper mode</p>
            <p className="text-xs text-gray-500">Disable to push live orders (when supported)</p>
          </div>
          <button
            className={`px-3 py-1 rounded-full text-xs font-semibold ${demoMode ? 'bg-blue-500/20 text-blue-300' : 'bg-red-500/10 text-red-300'}`}
            onClick={() => setDemoMode(prev => !prev)}
            disabled={isBusy || isConnected || selectedDetails?.supportsDemo === false}
          >
            {selectedDetails?.supportsDemo === false ? 'Live only' : demoMode ? 'Demo' : 'Live'}
          </button>
        </div>

        <label className="text-sm font-medium text-gray-300">
          API key
          <input
            type="password"
            className="input mt-1"
            placeholder="demo-***"
            value={apiKey}
            onChange={e => setApiKey(e.target.value)}
            disabled={isBusy || isConnected}
          />
        </label>

        <label className="text-sm font-medium text-gray-300">
          Account id
          <input
            type="text"
            className="input mt-1"
            placeholder="123-456"
            value={accountId}
            onChange={e => setAccountId(e.target.value)}
            disabled={isBusy || isConnected}
          />
        </label>
      </div>

      {error && (
        <div className="flex items-center gap-2 text-xs text-red-400">
          <ShieldAlert className="w-4 h-4" />
          {error}
        </div>
      )}

      <div className="flex flex-wrap gap-3">
        {!isConnected ? (
          <button
            className="btn-primary flex-1"
            onClick={handleConnect}
            disabled={isBusy || !apiKey || !accountId || !selectedProvider}
          >
            {isBusy ? (
              <span className="flex items-center justify-center gap-2">
                <Loader2 className="w-4 h-4 animate-spin" /> Connecting…
              </span>
            ) : (
              'Connect'
            )}
          </button>
        ) : (
          <button className="btn-secondary flex-1" onClick={handleDisconnect} disabled={isBusy}>
            Disconnect
          </button>
        )}

        <button className="btn-muted" onClick={handleSync} disabled={!isConnected || isBusy}>
          Sync positions
        </button>
      </div>

      {isConnected && (
        <div className="bg-dark-bg border border-dark-border rounded-lg p-3 text-xs text-gray-400 space-y-1">
          {balance !== null && balance !== undefined && (
            <p>
              Balance <span className="text-gray-200 font-semibold">${balance.toLocaleString()}</span>
            </p>
          )}
          {lastHeartbeat && <p>Heartbeat {new Date(lastHeartbeat).toLocaleTimeString()}</p>}
          {positions.length > 0 && (
            <div className="space-y-1 pt-2 border-t border-dark-border">
              <p className="uppercase text-[10px] tracking-wide text-gray-500">Latest synced positions</p>
              {positions.slice(0, 3).map(position => (
                <div key={`${position.symbol}-${position.ticket ?? position.avgPrice}`} className="flex justify-between">
                  <span>{position.symbol}</span>
                  <span className="text-gray-300">{position.quantity} @ {position.avgPrice.toFixed(2)}</span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  )
}
