/**
 * PaperTradingPanel Component
 * Main panel for paper trading functionality
 */

import { useState, useEffect } from 'react';
import { useTradingStore } from '../../../stores/tradingStore';
import AccountSummary from './AccountSummary';
import OrderForm from './OrderForm';
import PositionsList from './PositionsList';
import TradesHistory from './TradesHistory';

type TabType = 'order' | 'positions' | 'history' | 'settings';

export default function PaperTradingPanel() {
  const [activeTab, setActiveTab] = useState<TabType>('order');
  const [resetting, setResetting] = useState(false);
  const [showResetConfirm, setShowResetConfirm] = useState(false);

  // Get state and actions from store
  const {
    selectedSymbol,
    currentTicker,
    paperBalance,
    paperPositions,
    paperTrades,
    loadingPaperBalance,
    loadingPaperPositions,
    loadingPaperTrades,
    fetchPaperBalance,
    fetchPaperPositions,
    fetchPaperTrades,
    createOrder,
    closePosition,
    initializePaperAccount,
    resetPaperAccount,
  } = useTradingStore();

  // Handle reset account
  const handleResetAccount = async () => {
    setResetting(true);
    try {
      await resetPaperAccount();
      setShowResetConfirm(false);
      setActiveTab('order');
    } catch (error) {
      console.error('Failed to reset account:', error);
    } finally {
      setResetting(false);
    }
  };

  // Initialize paper trading data
  useEffect(() => {
    const initializePaperTrading = async () => {
      try {
        await fetchPaperBalance();
      } catch (error) {
        // If balance fetch fails, try to initialize account
        console.log('No paper account found, initializing...');
        try {
          await initializePaperAccount();
        } catch (initError) {
          console.error('Failed to initialize paper account:', initError);
        }
      }
    };

    initializePaperTrading();
    fetchPaperPositions();
    fetchPaperTrades();
  }, [fetchPaperBalance, fetchPaperPositions, fetchPaperTrades, initializePaperAccount]);

  // Refresh positions every 30 seconds
  useEffect(() => {
    const interval = setInterval(() => {
      if (activeTab === 'positions') {
        fetchPaperPositions();
      }
    }, 30000);

    return () => clearInterval(interval);
  }, [activeTab, fetchPaperPositions]);

  // Get current price
  const currentPrice = currentTicker?.price || 0;

  // Get balance data
  const balance = paperBalance?.balance || 0;
  const equity = paperBalance?.equity || balance;
  const unrealizedPnl = paperBalance?.unrealizedPnl || 0;

  return (
    <div className="w-80 card p-0 flex flex-col" style={{ height: '600px' }}>
      {/* Account Summary Header */}
      <AccountSummary
        balance={balance}
        equity={equity}
        unrealizedPnl={unrealizedPnl}
      />

      {/* Tabs */}
      <div className="flex border-b border-gray-700">
        <button
          onClick={() => setActiveTab('order')}
          className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
            activeTab === 'order'
              ? 'text-blue-400 border-b-2 border-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
        >
          Order
        </button>
        <button
          onClick={() => setActiveTab('positions')}
          className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
            activeTab === 'positions'
              ? 'text-blue-400 border-b-2 border-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
        >
          Positions
          {paperPositions.length > 0 && (
            <span className="ml-1 text-xs bg-blue-600 text-white px-1.5 py-0.5 rounded-full">
              {paperPositions.length}
            </span>
          )}
        </button>
        <button
          onClick={() => setActiveTab('history')}
          className={`flex-1 px-4 py-3 text-sm font-medium transition-colors ${
            activeTab === 'history'
              ? 'text-blue-400 border-b-2 border-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
        >
          History
        </button>
        <button
          onClick={() => setActiveTab('settings')}
          className={`px-3 py-3 text-sm font-medium transition-colors ${
            activeTab === 'settings'
              ? 'text-blue-400 border-b-2 border-blue-400'
              : 'text-gray-400 hover:text-white'
          }`}
          title="Settings"
        >
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
          </svg>
        </button>
      </div>

      {/* Tab Content */}
      <div className="flex-1 overflow-y-auto">
        {activeTab === 'order' && (
          <OrderForm
            symbol={selectedSymbol}
            currentPrice={currentPrice}
            balance={balance}
            onSubmit={createOrder}
          />
        )}

        {activeTab === 'positions' && (
          <PositionsList
            positions={paperPositions}
            isLoading={loadingPaperPositions}
            onClosePosition={closePosition}
          />
        )}

        {activeTab === 'history' && (
          <TradesHistory
            trades={paperTrades}
            isLoading={loadingPaperTrades}
          />
        )}

        {activeTab === 'settings' && (
          <div className="p-4 space-y-4">
            <h3 className="text-sm font-medium text-white">Paper Trading Settings</h3>

            {/* Account Info */}
            <div className="p-3 bg-gray-800 rounded-lg space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Initial Balance</span>
                <span className="text-white">$100,000.00</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Total Trades</span>
                <span className="text-white">{paperTrades.length}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-gray-400">Open Positions</span>
                <span className="text-white">{paperPositions.length}</span>
              </div>
            </div>

            {/* Reset Account */}
            <div className="p-3 bg-red-900/20 border border-red-800/50 rounded-lg">
              <h4 className="text-sm font-medium text-red-400 mb-2">Reset Account</h4>
              <p className="text-xs text-gray-400 mb-3">
                This will reset your paper trading account to the initial balance and clear all positions and trade history.
              </p>
              {showResetConfirm ? (
                <div className="space-y-2">
                  <p className="text-xs text-yellow-400">Are you sure? This cannot be undone.</p>
                  <div className="flex gap-2">
                    <button
                      onClick={handleResetAccount}
                      disabled={resetting}
                      className="flex-1 px-3 py-2 bg-red-600 hover:bg-red-700 disabled:bg-gray-600 text-white text-sm rounded transition-colors"
                    >
                      {resetting ? 'Resetting...' : 'Confirm Reset'}
                    </button>
                    <button
                      onClick={() => setShowResetConfirm(false)}
                      className="px-3 py-2 bg-gray-700 hover:bg-gray-600 text-white text-sm rounded transition-colors"
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              ) : (
                <button
                  onClick={() => setShowResetConfirm(true)}
                  className="w-full px-3 py-2 bg-red-600/50 hover:bg-red-600 text-red-200 text-sm rounded transition-colors"
                >
                  Reset Account
                </button>
              )}
            </div>
          </div>
        )}
      </div>

      {/* Loading Overlay */}
      {loadingPaperBalance && !paperBalance && (
        <div className="absolute inset-0 bg-gray-900/80 flex items-center justify-center">
          <div className="text-center">
            <div className="inline-block animate-spin rounded-full h-8 w-8 border-2 border-gray-600 border-t-blue-500 mb-2"></div>
            <p className="text-sm text-gray-400">Loading paper trading...</p>
          </div>
        </div>
      )}
    </div>
  );
}
