/**
 * Predictions Page
 * View and analyze ML model predictions history
 */

import { useState, useEffect } from 'react';
import {
  ChartBarSquareIcon,
  ArrowPathIcon,
  FunnelIcon,
  CalendarIcon,
  CheckCircleIcon,
  XCircleIcon,
  ClockIcon,
} from '@heroicons/react/24/solid';
import {
  getPredictions,
  getMLModels,
  type Prediction,
  type MLModel,
} from '../../../services/adminService';

type ResultFilter = 'all' | 'success' | 'failed' | 'pending';

export default function PredictionsPage() {
  const [predictions, setPredictions] = useState<Prediction[]>([]);
  const [models, setModels] = useState<MLModel[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterModel, setFilterModel] = useState<string>('all');
  const [filterSymbol, setFilterSymbol] = useState<string>('all');
  const [filterResult, setFilterResult] = useState<ResultFilter>('all');
  const [dateRange, setDateRange] = useState({
    start: '',
    end: '',
  });

  const symbols = ['XAUUSD', 'EURUSD', 'BTCUSDT'];

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    setLoading(true);
    try {
      const [predictionsData, modelsData] = await Promise.all([
        getPredictions({ limit: 100 }),
        getMLModels(),
      ]);
      setPredictions(Array.isArray(predictionsData) ? predictionsData : []);
      setModels(Array.isArray(modelsData) ? modelsData : []);
    } catch (error) {
      console.error('Error loading data:', error);
    } finally {
      setLoading(false);
    }
  };

  const applyFilters = async () => {
    setLoading(true);
    try {
      const params: {
        model_id?: string;
        symbol?: string;
        result?: 'success' | 'failed' | 'pending';
        start_date?: string;
        end_date?: string;
        limit: number;
      } = { limit: 100 };

      if (filterModel !== 'all') params.model_id = filterModel;
      if (filterSymbol !== 'all') params.symbol = filterSymbol;
      if (filterResult !== 'all') params.result = filterResult;
      if (dateRange.start) params.start_date = dateRange.start;
      if (dateRange.end) params.end_date = dateRange.end;

      const data = await getPredictions(params);
      setPredictions(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error applying filters:', error);
    } finally {
      setLoading(false);
    }
  };

  const formatCurrency = (value: number) => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 2,
    }).format(value);
  };

  const formatDate = (dateString: string) => {
    if (!dateString) return 'N/A';
    return new Date(dateString).toLocaleString('en-US', {
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  };

  const getResultIcon = (result?: string) => {
    switch (result) {
      case 'success':
        return <CheckCircleIcon className="w-5 h-5 text-green-400" />;
      case 'failed':
        return <XCircleIcon className="w-5 h-5 text-red-400" />;
      default:
        return <ClockIcon className="w-5 h-5 text-yellow-400" />;
    }
  };

  const stats = {
    total: predictions.length,
    success: predictions.filter(p => p.result === 'success').length,
    failed: predictions.filter(p => p.result === 'failed').length,
    pending: predictions.filter(p => p.result === 'pending' || !p.result).length,
    totalPnL: predictions.reduce((acc, p) => acc + (p.profit_loss || 0), 0),
    avgConfidence: predictions.length > 0
      ? predictions.reduce((acc, p) => acc + (p.confidence || 0), 0) / predictions.length
      : 0,
  };

  const successRate = stats.total > 0 && (stats.success + stats.failed) > 0
    ? (stats.success / (stats.success + stats.failed)) * 100
    : 0;

  if (loading && predictions.length === 0) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary-500"></div>
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="p-2 bg-orange-600 rounded-lg">
            <ChartBarSquareIcon className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">Predictions</h1>
            <p className="text-gray-400">ML model prediction history and performance</p>
          </div>
        </div>
        <button
          onClick={loadData}
          className="flex items-center gap-2 px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg transition-colors"
        >
          <ArrowPathIcon className="w-4 h-4" />
          Refresh
        </button>
      </div>

      {/* Stats */}
      <div className="grid grid-cols-2 md:grid-cols-6 gap-4">
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Total</span>
          <p className="text-2xl font-bold text-white">{stats.total}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Success</span>
          <p className="text-2xl font-bold text-green-400">{stats.success}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Failed</span>
          <p className="text-2xl font-bold text-red-400">{stats.failed}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Pending</span>
          <p className="text-2xl font-bold text-yellow-400">{stats.pending}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Success Rate</span>
          <p className="text-2xl font-bold text-blue-400">{successRate.toFixed(1)}%</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Total P&L</span>
          <p className={`text-2xl font-bold ${stats.totalPnL >= 0 ? 'text-green-400' : 'text-red-400'}`}>
            {formatCurrency(stats.totalPnL)}
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
        <div className="flex flex-wrap items-end gap-4">
          {/* Model Filter */}
          <div>
            <label className="block text-gray-400 text-sm mb-1">Model</label>
            <select
              value={filterModel}
              onChange={(e) => setFilterModel(e.target.value)}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-primary-500"
            >
              <option value="all">All Models</option>
              {models.map(m => (
                <option key={m.model_id} value={m.model_id}>
                  {m.name || m.type}
                </option>
              ))}
            </select>
          </div>

          {/* Symbol Filter */}
          <div>
            <label className="block text-gray-400 text-sm mb-1">Symbol</label>
            <select
              value={filterSymbol}
              onChange={(e) => setFilterSymbol(e.target.value)}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-primary-500"
            >
              <option value="all">All Symbols</option>
              {symbols.map(s => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>

          {/* Result Filter */}
          <div>
            <label className="block text-gray-400 text-sm mb-1">Result</label>
            <select
              value={filterResult}
              onChange={(e) => setFilterResult(e.target.value as ResultFilter)}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-primary-500"
            >
              <option value="all">All Results</option>
              <option value="success">Success</option>
              <option value="failed">Failed</option>
              <option value="pending">Pending</option>
            </select>
          </div>

          {/* Date Range */}
          <div>
            <label className="block text-gray-400 text-sm mb-1">From</label>
            <input
              type="date"
              value={dateRange.start}
              onChange={(e) => setDateRange(prev => ({ ...prev, start: e.target.value }))}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-primary-500"
            />
          </div>
          <div>
            <label className="block text-gray-400 text-sm mb-1">To</label>
            <input
              type="date"
              value={dateRange.end}
              onChange={(e) => setDateRange(prev => ({ ...prev, end: e.target.value }))}
              className="px-3 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white focus:outline-none focus:border-primary-500"
            />
          </div>

          {/* Apply Button */}
          <button
            onClick={applyFilters}
            className="flex items-center gap-2 px-4 py-2 bg-primary-600 hover:bg-primary-700 text-white rounded-lg transition-colors"
          >
            <FunnelIcon className="w-4 h-4" />
            Apply Filters
          </button>
        </div>
      </div>

      {/* Predictions Table */}
      <div className="bg-gray-800 rounded-lg border border-gray-700 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="text-left text-gray-400 text-sm bg-gray-900">
                <th className="px-4 py-3 font-medium">Model</th>
                <th className="px-4 py-3 font-medium">Symbol</th>
                <th className="px-4 py-3 font-medium">Direction</th>
                <th className="px-4 py-3 font-medium">Entry</th>
                <th className="px-4 py-3 font-medium">TP / SL</th>
                <th className="px-4 py-3 font-medium">Confidence</th>
                <th className="px-4 py-3 font-medium">Result</th>
                <th className="px-4 py-3 font-medium">P&L</th>
                <th className="px-4 py-3 font-medium">Time</th>
              </tr>
            </thead>
            <tbody>
              {predictions.map((prediction) => (
                <tr key={prediction.prediction_id} className="border-t border-gray-700 hover:bg-gray-700/30">
                  <td className="px-4 py-3">
                    <span className="text-white font-medium">{prediction.model_name}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className="text-white font-semibold">{prediction.symbol}</span>
                  </td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-1 rounded text-xs font-semibold ${
                      prediction.direction === 'long'
                        ? 'bg-green-900/50 text-green-400'
                        : 'bg-red-900/50 text-red-400'
                    }`}>
                      {prediction.direction.toUpperCase()}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-white">{prediction.entry_price?.toFixed(2)}</td>
                  <td className="px-4 py-3">
                    <span className="text-green-400">{prediction.take_profit?.toFixed(2)}</span>
                    {' / '}
                    <span className="text-red-400">{prediction.stop_loss?.toFixed(2)}</span>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      <div className="w-16 h-2 bg-gray-700 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-blue-500 rounded-full"
                          style={{ width: `${(prediction.confidence || 0) * 100}%` }}
                        />
                      </div>
                      <span className="text-blue-400 text-sm">
                        {((prediction.confidence || 0) * 100).toFixed(0)}%
                      </span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    <div className="flex items-center gap-2">
                      {getResultIcon(prediction.result)}
                      <span className={`text-sm capitalize ${
                        prediction.result === 'success' ? 'text-green-400' :
                        prediction.result === 'failed' ? 'text-red-400' :
                        'text-yellow-400'
                      }`}>
                        {prediction.result || 'pending'}
                      </span>
                    </div>
                  </td>
                  <td className="px-4 py-3">
                    {prediction.profit_loss !== undefined && (
                      <span className={`font-semibold ${
                        prediction.profit_loss >= 0 ? 'text-green-400' : 'text-red-400'
                      }`}>
                        {prediction.profit_loss >= 0 ? '+' : ''}
                        {formatCurrency(prediction.profit_loss)}
                      </span>
                    )}
                  </td>
                  <td className="px-4 py-3 text-gray-400 text-sm">
                    {formatDate(prediction.created_at)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {predictions.length === 0 && (
          <div className="text-center py-12">
            <ChartBarSquareIcon className="w-12 h-12 text-gray-600 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-white mb-2">No predictions found</h3>
            <p className="text-gray-400">Try adjusting your filters or check back later</p>
          </div>
        )}
      </div>
    </div>
  );
}
