import React, { useState, useEffect } from 'react';
import Modal from 'react-modal';
import { GoTrash, GoStar, GoStarFill } from 'react-icons/go';
import { useQuery } from '@tanstack/react-query';
import { useLLMConfigs, } from "@/api/llmConfigs/hooks";
import { LLMConfig } from "@/api/llmConfigs/types";
import './LlmConfigList.scss';
import LLMConfigModal from './LlmConfigModal';
import { fetchDefaultLLMConfig } from '@/api/llmConfigs/llmConfigApi';


Modal.setAppElement('#root');



const LLMConfigList: React.FC = () => {
  const { configs, isLoading, error, createConfig, updateConfig, setAsDefaultConfig, deleteConfig } = useLLMConfigs();
  const [sortField, setSortField] = useState<keyof LLMConfig | 'created_at'>('id');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [selectedConfig, setSelectedConfig] = useState<LLMConfig | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);

  // Функция для форматирования параметров в короткую строку
  const formatParameters = (config: LLMConfig) => {
    return `T:${config.temperature}, TP:${config.top_p}, MP:${config.min_p}, FP:${config.frequency_penalty}, PP:${config.presence_penalty}, S:${config.seed}, M:${config.model}`;
  };

  const handleSort = (field: keyof LLMConfig | 'created_at') => {
    const newDirection = sortField === field && sortDirection === 'asc' ? 'desc' : 'asc';
    setSortField(field);
    setSortDirection(newDirection);
    const sortedConfigs = [...configs].sort((a, b) => {
      const aValue = field === 'created_at' ? a.created_at || '' : a[field];
      const bValue = field === 'created_at' ? b.created_at || '' : b[field];
      return newDirection === 'asc' ? (aValue > bValue ? 1 : -1) : (aValue < bValue ? 1 : -1);
    });
    configs.splice(0, configs.length, ...sortedConfigs);
  };

  const openEditModal = (config: LLMConfig) => {
    setSelectedConfig(config);
    setIsEditMode(true);
    setIsModalOpen(true);
  };

  const openCreateModal = () => {
    setSelectedConfig(null); // Ничего не передаем, запрос будет в модалке
    setIsEditMode(false);
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setSelectedConfig(null);
    setIsModalOpen(false);
  };

  const handleSave = async (config: LLMConfig | Omit<LLMConfig, 'id' | 'created_at'>) => {
    if (isEditMode && 'id' in config) {
      await updateConfig(config as LLMConfig);
    } else {
      await createConfig(config as Omit<LLMConfig, 'id' | 'created_at'>);
    }
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('Are you sure you want to delete this config?')) {
      await deleteConfig(id);
    }
  };

  const handleSetDefault = async (id: number) => {
    await setAsDefaultConfig(id);
  };

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;

  return (
    <div className="llm-config-list">
      <h1>Настройки LLM</h1>
      <button className="create-button" onClick={openCreateModal}>
        Добавить настройки
      </button>
      <div className="table-container">
        <div className="table-header">
          <div className="table-cell"></div>
          <div className="table-cell" onClick={() => handleSort('created_at')}>
            Настройки
          </div>
          <div className="table-cell"></div>
        </div>
        {configs.map(config => (
          <div key={config.id} className="table-row">
            <div className="table-cell">
              <button
                className="set-default-button"
                onClick={() => handleSetDefault(config.id)}
              >
                {config.is_default ? <GoStarFill size={20} /> : <GoStar size={20} />}
              </button>
            </div>
            <div className="table-cell" onClick={() => openEditModal(config)}>
              {formatParameters(config)} {/* Отображение параметров */}
            </div>
            {/* <div className="table-cell" onClick={() => openEditModal(config)}>
              {config.created_at || 'N/A'}
            </div> */}
            <div className="table-cell">
              <button className="delete-button" onClick={() => handleDelete(config.id)}>
                <GoTrash size={20} />
              </button>
            </div>
          </div>
        ))}
      </div>

      <LLMConfigModal
        isOpen={isModalOpen}
        onRequestClose={closeModal}
        config={selectedConfig}
        onSave={handleSave}
        isEditMode={isEditMode}
      />
    </div>
  );
};

export default LLMConfigList;