/**
 * ML Models Page
 * Detailed view of all ML models with filtering and management controls
 */

import { useState, useEffect } from 'react';
import {
  CpuChipIcon,
  FunnelIcon,
  ArrowPathIcon,
  MagnifyingGlassIcon,
} from '@heroicons/react/24/solid';
import { MLModelCard } from '../components';
import {
  getMLModels,
  updateMLModelStatus,
  type MLModel,
} from '../../../services/adminService';

type ModelType = 'all' | 'AMD' | 'ICT' | 'Range' | 'TPSL' | 'Ensemble';
type ModelStatus = 'all' | 'active' | 'training' | 'inactive' | 'error';

export default function MLModelsPage() {
  const [models, setModels] = useState<MLModel[]>([]);
  const [loading, setLoading] = useState(true);
  const [filterType, setFilterType] = useState<ModelType>('all');
  const [filterStatus, setFilterStatus] = useState<ModelStatus>('all');
  const [searchQuery, setSearchQuery] = useState('');

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

  const loadModels = async () => {
    setLoading(true);
    try {
      const data = await getMLModels();
      setModels(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Error loading models:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleToggleStatus = async (modelId: string, newStatus: 'active' | 'inactive') => {
    const success = await updateMLModelStatus(modelId, newStatus);
    if (success) {
      setModels(prev =>
        prev.map(m =>
          m.model_id === modelId ? { ...m, status: newStatus } : m
        )
      );
    }
  };

  const filteredModels = models.filter(model => {
    if (filterType !== 'all' && model.type !== filterType) return false;
    if (filterStatus !== 'all' && model.status !== filterStatus) return false;
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      return (
        model.name?.toLowerCase().includes(query) ||
        model.type?.toLowerCase().includes(query) ||
        model.model_id?.toLowerCase().includes(query)
      );
    }
    return true;
  });

  const stats = {
    total: models.length,
    active: models.filter(m => m.status === 'active').length,
    training: models.filter(m => m.status === 'training').length,
    inactive: models.filter(m => m.status === 'inactive').length,
    avgAccuracy: models.length > 0
      ? models.reduce((acc, m) => acc + (m.accuracy || 0), 0) / models.length
      : 0,
  };

  if (loading) {
    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-blue-600 rounded-lg">
            <CpuChipIcon className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-2xl font-bold text-white">ML Models</h1>
            <p className="text-gray-400">Manage and monitor machine learning models</p>
          </div>
        </div>
        <button
          onClick={loadModels}
          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 Cards */}
      <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Total Models</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">Active</span>
          <p className="text-2xl font-bold text-green-400">{stats.active}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Training</span>
          <p className="text-2xl font-bold text-yellow-400">{stats.training}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Inactive</span>
          <p className="text-2xl font-bold text-gray-400">{stats.inactive}</p>
        </div>
        <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
          <span className="text-gray-400 text-sm">Avg Accuracy</span>
          <p className="text-2xl font-bold text-blue-400">
            {(stats.avgAccuracy * 100).toFixed(1)}%
          </p>
        </div>
      </div>

      {/* Filters */}
      <div className="bg-gray-800 rounded-lg p-4 border border-gray-700">
        <div className="flex flex-wrap items-center gap-4">
          {/* Search */}
          <div className="relative flex-1 min-w-[200px]">
            <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
            <input
              type="text"
              placeholder="Search models..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2 bg-gray-900 border border-gray-700 rounded-lg text-white placeholder-gray-500 focus:outline-none focus:border-primary-500"
            />
          </div>

          {/* Type Filter */}
          <div className="flex items-center gap-2">
            <FunnelIcon className="w-4 h-4 text-gray-400" />
            <select
              value={filterType}
              onChange={(e) => setFilterType(e.target.value as ModelType)}
              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 Types</option>
              <option value="AMD">AMD Detector</option>
              <option value="ICT">ICT/SMC</option>
              <option value="Range">Range Predictor</option>
              <option value="TPSL">TP/SL Classifier</option>
              <option value="Ensemble">Ensemble</option>
            </select>
          </div>

          {/* Status Filter */}
          <select
            value={filterStatus}
            onChange={(e) => setFilterStatus(e.target.value as ModelStatus)}
            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 Status</option>
            <option value="active">Active</option>
            <option value="training">Training</option>
            <option value="inactive">Inactive</option>
            <option value="error">Error</option>
          </select>
        </div>
      </div>

      {/* Models Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {filteredModels.map((model) => (
          <MLModelCard
            key={model.model_id}
            model={model}
            onToggleStatus={handleToggleStatus}
          />
        ))}
      </div>

      {/* Empty State */}
      {filteredModels.length === 0 && (
        <div className="text-center py-12">
          <CpuChipIcon className="w-12 h-12 text-gray-600 mx-auto mb-4" />
          <h3 className="text-lg font-semibold text-white mb-2">No models found</h3>
          <p className="text-gray-400">
            {searchQuery || filterType !== 'all' || filterStatus !== 'all'
              ? 'Try adjusting your filters'
              : 'No ML models have been configured yet'}
          </p>
        </div>
      )}
    </div>
  );
}
