/**
 * MT4PositionsManager Component
 * Container for managing all live MT4 positions with real-time updates
 */

import React, { useState, useEffect, useCallback } from 'react';
import {
  RefreshCw,
  X,
  Filter,
  SortAsc,
  SortDesc,
  TrendingUp,
  TrendingDown,
  AlertTriangle,
  Loader2,
  LayoutList,
  LayoutGrid,
} from 'lucide-react';
import LivePositionCard from './LivePositionCard';
import {
  getMT4Positions,
  closeMT4Position,
  modifyMT4Position,
  type MT4Position,
} from '../../../services/trading.service';

type SortField = 'profit' | 'volume' | 'symbol' | 'openTime';
type SortDirection = 'asc' | 'desc';
type FilterType = 'all' | 'buy' | 'sell' | 'profit' | 'loss';

interface MT4PositionsManagerProps {
  autoRefresh?: boolean;
  refreshInterval?: number;
  onPositionClose?: (ticket: number) => void;
  onPositionModify?: (ticket: number) => void;
  compact?: boolean;
}

const MT4PositionsManager: React.FC<MT4PositionsManagerProps> = ({
  autoRefresh = true,
  refreshInterval = 30000,
  onPositionClose,
  onPositionModify,
  compact = false,
}) => {
  const [positions, setPositions] = useState<MT4Position[]>([]);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sortField, setSortField] = useState<SortField>('openTime');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  const [filter, setFilter] = useState<FilterType>('all');
  const [showCloseAllConfirm, setShowCloseAllConfirm] = useState(false);
  const [closingAll, setClosingAll] = useState(false);
  const [viewMode, setViewMode] = useState<'list' | 'grid'>('list');

  const fetchPositions = useCallback(async (isRefresh = false) => {
    if (isRefresh) setRefreshing(true);
    else setLoading(true);

    try {
      const data = await getMT4Positions();
      setPositions(data || []);
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Failed to load positions');
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, []);

  useEffect(() => {
    fetchPositions();

    if (autoRefresh) {
      const interval = setInterval(() => fetchPositions(true), refreshInterval);
      return () => clearInterval(interval);
    }
  }, [fetchPositions, autoRefresh, refreshInterval]);

  const handleClosePosition = async (ticket: number) => {
    try {
      await closeMT4Position(ticket);
      setPositions((prev) => prev.filter((p) => p.ticket !== ticket));
      onPositionClose?.(ticket);
    } catch (err) {
      console.error('Failed to close position:', err);
    }
  };

  const handleModifyPosition = async (
    ticket: number,
    stopLoss?: number,
    takeProfit?: number
  ) => {
    try {
      await modifyMT4Position(ticket, stopLoss, takeProfit);
      setPositions((prev) =>
        prev.map((p) =>
          p.ticket === ticket
            ? { ...p, stop_loss: stopLoss || p.stop_loss, take_profit: takeProfit || p.take_profit }
            : p
        )
      );
      onPositionModify?.(ticket);
    } catch (err) {
      console.error('Failed to modify position:', err);
    }
  };

  const handleCloseAll = async () => {
    setClosingAll(true);
    try {
      await Promise.all(positions.map((p) => closeMT4Position(p.ticket)));
      setPositions([]);
      setShowCloseAllConfirm(false);
    } catch (err) {
      console.error('Failed to close all positions:', err);
    } finally {
      setClosingAll(false);
    }
  };

  // Filter positions
  const filteredPositions = positions.filter((p) => {
    switch (filter) {
      case 'buy':
        return p.type === 'buy';
      case 'sell':
        return p.type === 'sell';
      case 'profit':
        return p.profit >= 0;
      case 'loss':
        return p.profit < 0;
      default:
        return true;
    }
  });

  // Sort positions
  const sortedPositions = [...filteredPositions].sort((a, b) => {
    let comparison = 0;
    switch (sortField) {
      case 'profit':
        comparison = a.profit - b.profit;
        break;
      case 'volume':
        comparison = a.volume - b.volume;
        break;
      case 'symbol':
        comparison = a.symbol.localeCompare(b.symbol);
        break;
      case 'openTime':
        comparison = new Date(a.open_time).getTime() - new Date(b.open_time).getTime();
        break;
    }
    return sortDirection === 'asc' ? comparison : -comparison;
  });

  // Calculate totals
  const totalProfit = positions.reduce((sum, p) => sum + p.profit, 0);
  const totalLots = positions.reduce((sum, p) => sum + p.volume, 0);
  const buyCount = positions.filter((p) => p.type === 'buy').length;
  const sellCount = positions.filter((p) => p.type === 'sell').length;

  const toggleSort = (field: SortField) => {
    if (sortField === field) {
      setSortDirection((prev) => (prev === 'asc' ? 'desc' : 'asc'));
    } else {
      setSortField(field);
      setSortDirection('desc');
    }
  };

  if (loading) {
    return (
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-8 flex items-center justify-center">
        <Loader2 className="w-6 h-6 text-blue-400 animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="bg-gray-800 rounded-xl border border-gray-700 p-6 text-center">
        <AlertTriangle className="w-10 h-10 text-red-400 mx-auto mb-3" />
        <h4 className="font-medium text-white mb-1">Failed to Load Positions</h4>
        <p className="text-sm text-gray-400 mb-4">{error}</p>
        <button
          onClick={() => fetchPositions()}
          className="px-4 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-lg text-sm transition-colors"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className="bg-gray-800 rounded-xl border border-gray-700 overflow-hidden">
      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-700">
        <div className="flex items-center gap-3">
          <h3 className="font-medium text-white">Open Positions</h3>
          <span className="px-2 py-0.5 bg-gray-700 rounded text-sm text-gray-300">
            {positions.length}
          </span>
        </div>
        <div className="flex items-center gap-2">
          {/* View Mode Toggle */}
          {!compact && (
            <div className="flex items-center bg-gray-700 rounded-lg p-0.5">
              <button
                onClick={() => setViewMode('list')}
                className={`p-1.5 rounded ${
                  viewMode === 'list' ? 'bg-gray-600 text-white' : 'text-gray-400'
                }`}
              >
                <LayoutList className="w-4 h-4" />
              </button>
              <button
                onClick={() => setViewMode('grid')}
                className={`p-1.5 rounded ${
                  viewMode === 'grid' ? 'bg-gray-600 text-white' : 'text-gray-400'
                }`}
              >
                <LayoutGrid className="w-4 h-4" />
              </button>
            </div>
          )}
          <button
            onClick={() => fetchPositions(true)}
            disabled={refreshing}
            className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
          >
            <RefreshCw className={`w-4 h-4 ${refreshing ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </div>

      {/* Summary Bar */}
      <div className="flex items-center justify-between px-4 py-3 bg-gray-900/50 border-b border-gray-700">
        <div className="flex items-center gap-6 text-sm">
          <div className="flex items-center gap-2">
            <TrendingUp className="w-4 h-4 text-green-400" />
            <span className="text-gray-400">Buy:</span>
            <span className="text-white font-medium">{buyCount}</span>
          </div>
          <div className="flex items-center gap-2">
            <TrendingDown className="w-4 h-4 text-red-400" />
            <span className="text-gray-400">Sell:</span>
            <span className="text-white font-medium">{sellCount}</span>
          </div>
          <div className="flex items-center gap-2">
            <span className="text-gray-400">Lots:</span>
            <span className="text-white font-medium">{totalLots.toFixed(2)}</span>
          </div>
        </div>
        <div className={`text-lg font-bold ${totalProfit >= 0 ? 'text-green-400' : 'text-red-400'}`}>
          {totalProfit >= 0 ? '+' : ''}{totalProfit.toFixed(2)} USD
        </div>
      </div>

      {/* Filters & Sort */}
      <div className="flex items-center justify-between px-4 py-2 border-b border-gray-700">
        <div className="flex items-center gap-2">
          <Filter className="w-4 h-4 text-gray-500" />
          {(['all', 'buy', 'sell', 'profit', 'loss'] as FilterType[]).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-2 py-1 text-xs rounded transition-colors ${
                filter === f
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-700 text-gray-400 hover:text-white'
              }`}
            >
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
        <div className="flex items-center gap-2">
          <span className="text-xs text-gray-500">Sort:</span>
          {(['profit', 'volume', 'symbol'] as SortField[]).map((field) => (
            <button
              key={field}
              onClick={() => toggleSort(field)}
              className={`flex items-center gap-1 px-2 py-1 text-xs rounded transition-colors ${
                sortField === field
                  ? 'bg-blue-600 text-white'
                  : 'bg-gray-700 text-gray-400 hover:text-white'
              }`}
            >
              {field.charAt(0).toUpperCase() + field.slice(1)}
              {sortField === field &&
                (sortDirection === 'asc' ? (
                  <SortAsc className="w-3 h-3" />
                ) : (
                  <SortDesc className="w-3 h-3" />
                ))}
            </button>
          ))}
        </div>
      </div>

      {/* Positions List */}
      <div className={`p-4 ${viewMode === 'grid' ? 'grid grid-cols-2 gap-4' : 'space-y-3'}`}>
        {sortedPositions.length === 0 ? (
          <div className="text-center py-8 col-span-2">
            <LayoutList className="w-10 h-10 text-gray-600 mx-auto mb-3" />
            <p className="text-gray-400">No open positions</p>
            {filter !== 'all' && (
              <button
                onClick={() => setFilter('all')}
                className="mt-2 text-sm text-blue-400 hover:text-blue-300"
              >
                Clear filter
              </button>
            )}
          </div>
        ) : (
          sortedPositions.map((position) => (
            <LivePositionCard
              key={position.ticket}
              position={position}
              onClose={handleClosePosition}
              onModify={handleModifyPosition}
            />
          ))
        )}
      </div>

      {/* Close All Footer */}
      {positions.length > 0 && (
        <div className="px-4 py-3 border-t border-gray-700 bg-gray-900/50">
          {showCloseAllConfirm ? (
            <div className="flex items-center justify-between">
              <span className="text-sm text-yellow-400">
                Close all {positions.length} positions?
              </span>
              <div className="flex items-center gap-2">
                <button
                  onClick={() => setShowCloseAllConfirm(false)}
                  className="px-3 py-1.5 text-sm text-gray-300 hover:text-white transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleCloseAll}
                  disabled={closingAll}
                  className="flex items-center gap-2 px-3 py-1.5 bg-red-600 hover:bg-red-500 text-white rounded-lg text-sm transition-colors disabled:opacity-50"
                >
                  {closingAll ? (
                    <Loader2 className="w-4 h-4 animate-spin" />
                  ) : (
                    <X className="w-4 h-4" />
                  )}
                  Confirm Close All
                </button>
              </div>
            </div>
          ) : (
            <button
              onClick={() => setShowCloseAllConfirm(true)}
              className="w-full flex items-center justify-center gap-2 py-2 bg-red-600/20 hover:bg-red-600/30 text-red-400 rounded-lg text-sm transition-colors border border-red-600/30"
            >
              <X className="w-4 h-4" />
              Close All Positions
            </button>
          )}
        </div>
      )}
    </div>
  );
};

export default MT4PositionsManager;
