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 { useLlmPrompts, } from "@/api/llmPrompts/hooks";
import { LlmPrompt } from "@/api/llmPrompts/types";
import './LlmPromptList.scss';
import LlmPromptModal from './LlmPromptModal';
import { fetchDefaultLlmPrompt } from '@/api/llmPrompts/llmPromptApi';


Modal.setAppElement('#root');



const LlmPromptList: React.FC = () => {
  const { prompts, isLoading, error, createPrompt, updatePrompt, setAsDefaultPrompt, deletePrompt } = useLlmPrompts();
  const [sortField, setSortField] = useState<keyof LlmPrompt | 'created_at'>('id');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [selectedPrompt, setSelectedPrompt] = useState<LlmPrompt | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);


  const handleSort = (field: keyof LlmPrompt | 'created_at') => {
    const newDirection = sortField === field && sortDirection === 'asc' ? 'desc' : 'asc';
    setSortField(field);
    setSortDirection(newDirection);
    const sortedPrompts = [...prompts].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);
    });
    prompts.splice(0, prompts.length, ...sortedPrompts);
  };

  const openEditModal = (prompt: LlmPrompt) => {
    setSelectedPrompt(prompt);
    setIsEditMode(true);
    setIsModalOpen(true);
  };

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

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

  const handleSave = async (prompt: LlmPrompt | Omit<LlmPrompt, 'id' | 'created_at'>) => {
    if (isEditMode && 'id' in prompt) {
      await updatePrompt(prompt as LlmPrompt);
    } else {
      await createPrompt(prompt as Omit<LlmPrompt, 'id' | 'created_at'>);
    }
  };

  const handleDelete = async (id: number) => {
    if (window.confirm('Удаляем версию промпта?')) {
      await deletePrompt(id);
    }
  };

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

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

  return (
    <div className="llm-prompt-list">
      <h1>Системные промпты</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>
        {prompts.map(prompt => (
          <div key={prompt.id} className="table-row">
            <div className="table-cell">
              <button
                className="set-default-button"
                onClick={() => handleSetDefault(prompt.id)}
              >
                {prompt.is_default ? <GoStarFill size={20} /> : <GoStar size={20} />}
              </button>
            </div>
            <div className="table-cell" onClick={() => openEditModal(prompt)}>
              {prompt.name}
            </div>
            {/* <div className="table-cell" onClick={() => openEditModal(prompt)}>
              {prompt.created_at || 'N/A'}
            </div> */}
            <div className="table-cell">
              <button className="delete-button" onClick={() => handleDelete(prompt.id)}>
                <GoTrash size={20} />
              </button>
            </div>
          </div>
        ))}
      </div>

      <LlmPromptModal
        isOpen={isModalOpen}
        onRequestClose={closeModal}
        prompt={selectedPrompt}
        onSave={handleSave}
        isEditMode={isEditMode}
      />
    </div>
  );
};

export default LlmPromptList;