/**
 * Trades Table Component
 * Displays detailed list of backtested trades
 */

import React, { useState, useMemo } from 'react';
import {
  ArrowUpIcon,
  ArrowDownIcon,
  FunnelIcon,
  MagnifyingGlassIcon,
} from '@heroicons/react/24/solid';
import type { BacktestTrade } from '../../../services/backtestService';

interface TradesTableProps {
  trades: BacktestTrade[];
  className?: string;
}

type SortField = 'entry_time' | 'pnl' | 'pnl_percent' | 'holding_time_minutes' | 'confidence';
type SortDirection = 'asc' | 'desc';

export const TradesTable: React.FC<TradesTableProps> = ({
  trades,
  className = '',
}) => {
  const [sortField, setSortField] = useState<SortField>('entry_time');
  const [sortDirection, setSortDirection] = useState<SortDirection>('desc');
  const [filter, setFilter] = useState<'all' | 'wins' | 'losses'>('all');
  const [searchTerm, setSearchTerm] = useState('');
  const [page, setPage] = useState(1);
  const pageSize = 20;

  // Filter and sort trades
  const filteredTrades = useMemo(() => {
    let result = [...trades];

    // Apply filter
    if (filter === 'wins') {
      result = result.filter((t) => t.pnl && t.pnl > 0);
    } else if (filter === 'losses') {
      result = result.filter((t) => t.pnl && t.pnl < 0);
    }

    // Apply search
    if (searchTerm) {
      const search = searchTerm.toLowerCase();
      result = result.filter(
        (t) =>
          t.symbol.toLowerCase().includes(search) ||
          t.strategy.toLowerCase().includes(search)
      );
    }

    // Apply sort
    result.sort((a, b) => {
      let aVal: number | string = 0;
      let bVal: number | string = 0;

      switch (sortField) {
        case 'entry_time':
          aVal = new Date(a.entry_time).getTime();
          bVal = new Date(b.entry_time).getTime();
          break;
        case 'pnl':
          aVal = a.pnl || 0;
          bVal = b.pnl || 0;
          break;
        case 'pnl_percent':
          aVal = a.pnl_percent || 0;
          bVal = b.pnl_percent || 0;
          break;
        case 'holding_time_minutes':
          aVal = a.holding_time_minutes || 0;
          bVal = b.holding_time_minutes || 0;
          break;
        case 'confidence':
          aVal = a.confidence;
          bVal = b.confidence;
          break;
      }

      if (sortDirection === 'asc') {
        return aVal > bVal ? 1 : -1;
      }
      return aVal < bVal ? 1 : -1;
    });

    return result;
  }, [trades, filter, searchTerm, sortField, sortDirection]);

  // Pagination
  const totalPages = Math.ceil(filteredTrades.length / pageSize);
  const paginatedTrades = filteredTrades.slice(
    (page - 1) * pageSize,
    page * pageSize
  );

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

  const SortIcon = ({ field }: { field: SortField }) => {
    if (sortField !== field) return null;
    return sortDirection === 'asc' ? (
      <ArrowUpIcon className="w-3 h-3" />
    ) : (
      <ArrowDownIcon className="w-3 h-3" />
    );
  };

  const formatDuration = (minutes: number): string => {
    if (minutes < 60) return `${minutes}m`;
    if (minutes < 1440) return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
    return `${Math.floor(minutes / 1440)}d ${Math.floor((minutes % 1440) / 60)}h`;
  };

  return (
    <div className={`bg-gray-900 border border-gray-800 rounded-xl p-4 ${className}`}>
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-lg font-bold text-white">Trade History</h3>
        <span className="text-sm text-gray-400">
          {filteredTrades.length} trades
        </span>
      </div>

      {/* Filters */}
      <div className="flex items-center gap-4 mb-4">
        {/* Search */}
        <div className="relative flex-1 max-w-xs">
          <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            type="text"
            placeholder="Search symbol or strategy..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="w-full pl-9 pr-3 py-2 bg-gray-800 border border-gray-700 rounded-lg text-sm text-white focus:outline-none focus:border-purple-500"
          />
        </div>

        {/* Filter buttons */}
        <div className="flex items-center gap-1">
          <FunnelIcon className="w-4 h-4 text-gray-400 mr-1" />
          {(['all', 'wins', 'losses'] as const).map((f) => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-3 py-1.5 text-xs rounded-lg transition-colors ${
                filter === f
                  ? f === 'wins'
                    ? 'bg-green-600 text-white'
                    : f === 'losses'
                    ? 'bg-red-600 text-white'
                    : 'bg-purple-600 text-white'
                  : 'bg-gray-800 text-gray-300 hover:bg-gray-700'
              }`}
            >
              {f.charAt(0).toUpperCase() + f.slice(1)}
            </button>
          ))}
        </div>
      </div>

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="text-left text-gray-400 border-b border-gray-700">
              <th
                className="pb-3 cursor-pointer hover:text-white"
                onClick={() => handleSort('entry_time')}
              >
                <div className="flex items-center gap-1">
                  Date <SortIcon field="entry_time" />
                </div>
              </th>
              <th className="pb-3">Symbol</th>
              <th className="pb-3">Direction</th>
              <th className="pb-3">Entry</th>
              <th className="pb-3">Exit</th>
              <th className="pb-3">SL / TP</th>
              <th
                className="pb-3 cursor-pointer hover:text-white"
                onClick={() => handleSort('pnl')}
              >
                <div className="flex items-center gap-1">
                  P/L $ <SortIcon field="pnl" />
                </div>
              </th>
              <th
                className="pb-3 cursor-pointer hover:text-white"
                onClick={() => handleSort('pnl_percent')}
              >
                <div className="flex items-center gap-1">
                  P/L % <SortIcon field="pnl_percent" />
                </div>
              </th>
              <th
                className="pb-3 cursor-pointer hover:text-white"
                onClick={() => handleSort('holding_time_minutes')}
              >
                <div className="flex items-center gap-1">
                  Duration <SortIcon field="holding_time_minutes" />
                </div>
              </th>
              <th className="pb-3">Strategy</th>
              <th
                className="pb-3 cursor-pointer hover:text-white"
                onClick={() => handleSort('confidence')}
              >
                <div className="flex items-center gap-1">
                  Conf <SortIcon field="confidence" />
                </div>
              </th>
              <th className="pb-3">Status</th>
            </tr>
          </thead>
          <tbody>
            {paginatedTrades.map((trade) => (
              <tr
                key={trade.id}
                className="border-b border-gray-800 hover:bg-gray-800/50"
              >
                <td className="py-3 text-gray-300">
                  {new Date(trade.entry_time).toLocaleDateString()}
                </td>
                <td className="py-3 font-semibold text-white">{trade.symbol}</td>
                <td className="py-3">
                  <span
                    className={`px-2 py-0.5 rounded text-xs font-bold ${
                      trade.direction === 'long'
                        ? 'bg-green-900/50 text-green-400'
                        : 'bg-red-900/50 text-red-400'
                    }`}
                  >
                    {trade.direction.toUpperCase()}
                  </span>
                </td>
                <td className="py-3 font-mono text-gray-300">
                  {trade.entry_price.toFixed(5)}
                </td>
                <td className="py-3 font-mono text-gray-300">
                  {trade.exit_price?.toFixed(5) || '-'}
                </td>
                <td className="py-3 text-xs">
                  <span className="text-red-400">{trade.stop_loss.toFixed(5)}</span>
                  {' / '}
                  <span className="text-green-400">{trade.take_profit.toFixed(5)}</span>
                </td>
                <td
                  className={`py-3 font-bold ${
                    trade.pnl && trade.pnl > 0
                      ? 'text-green-400'
                      : trade.pnl && trade.pnl < 0
                      ? 'text-red-400'
                      : 'text-gray-400'
                  }`}
                >
                  {trade.pnl
                    ? `${trade.pnl > 0 ? '+' : ''}$${trade.pnl.toFixed(2)}`
                    : '-'}
                </td>
                <td
                  className={`py-3 font-bold ${
                    trade.pnl_percent && trade.pnl_percent > 0
                      ? 'text-green-400'
                      : trade.pnl_percent && trade.pnl_percent < 0
                      ? 'text-red-400'
                      : 'text-gray-400'
                  }`}
                >
                  {trade.pnl_percent
                    ? `${trade.pnl_percent > 0 ? '+' : ''}${trade.pnl_percent.toFixed(2)}%`
                    : '-'}
                </td>
                <td className="py-3 text-gray-300">
                  {trade.holding_time_minutes
                    ? formatDuration(trade.holding_time_minutes)
                    : '-'}
                </td>
                <td className="py-3">
                  <span className="px-2 py-0.5 bg-gray-700 rounded text-xs text-gray-300">
                    {trade.strategy}
                  </span>
                </td>
                <td className="py-3">
                  <div className="flex items-center gap-1">
                    <div
                      className="w-8 h-1.5 bg-gray-700 rounded-full overflow-hidden"
                      title={`${(trade.confidence * 100).toFixed(0)}%`}
                    >
                      <div
                        className="h-full bg-purple-500 rounded-full"
                        style={{ width: `${trade.confidence * 100}%` }}
                      />
                    </div>
                    <span className="text-xs text-gray-400">
                      {(trade.confidence * 100).toFixed(0)}%
                    </span>
                  </div>
                </td>
                <td className="py-3">
                  <span
                    className={`px-2 py-0.5 rounded text-xs ${
                      trade.status === 'closed_tp'
                        ? 'bg-green-900/50 text-green-400'
                        : trade.status === 'closed_sl'
                        ? 'bg-red-900/50 text-red-400'
                        : trade.status === 'open'
                        ? 'bg-blue-900/50 text-blue-400'
                        : 'bg-gray-700 text-gray-400'
                    }`}
                  >
                    {trade.status.replace('_', ' ').toUpperCase()}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex items-center justify-between mt-4 pt-4 border-t border-gray-800">
          <span className="text-sm text-gray-400">
            Showing {(page - 1) * pageSize + 1} -{' '}
            {Math.min(page * pageSize, filteredTrades.length)} of{' '}
            {filteredTrades.length}
          </span>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
              className="px-3 py-1 bg-gray-800 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-700"
            >
              Previous
            </button>
            <span className="text-sm text-gray-400">
              Page {page} of {totalPages}
            </span>
            <button
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="px-3 py-1 bg-gray-800 rounded text-sm disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-700"
            >
              Next
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default TradesTable;
