import React, { useState } from 'react';
import { Message } from '../../types/fusemind/messages';
import { useChatStore } from '../../state/stores/useChatStore';
import ChatBubble from './Chat/ChatBubble';
import MoleculeAvatar from './Avatar/MoleculeAvatar';
import { useModalCommands } from './modals/hooks/useModalCommands';
import ModalContainer from './modals/ModalContainer';
import { useModalGrid } from './modals/hooks/useModalGrid';
import { ModalConfig } from './modals/core/types';

interface VisibleMessage extends Message {
    isVisible: boolean;
}

// Helper function to convert grid coordinates to percentages
const gridToPercent = (x: number, y: number, width: number, height: number) => {
    // Grid is 20x8, so each cell is 5% of width and 12.5% of height
    // Since we're using transform: translate(-50%, -50%), we need to center the coordinates
    return {
        x: (x * 5) + (width * 5 / 2),
        y: (y * 12.5) + (height * 12.5 / 2),
        width: `${width * 5}%`,
        height: `${height * 12.5}%`
    };
};

const FuseMindHome: React.FC = () => {
    const [messages, setMessages] = useState<VisibleMessage[]>([]);
    const [inputMessage, setInputMessage] = useState('');
    const { sendChatRequest } = useChatStore();
    const { modals, createModal, removeModal } = useModalCommands();
    const { addModal, removeModal: removeGridModal } = useModalGrid();

    const handleSendMessage = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!inputMessage.trim()) return;

        const userMessage: VisibleMessage = {
            id: Date.now().toString(),
            type: 'user',
            content: inputMessage,
            timestamp: new Date(),
            isVisible: true
        };

        setMessages(prev => [...prev, userMessage]);
        setInputMessage('');

        try {
            const response = await sendChatRequest('/chat/completions', {
                data: `Create a comprehensive table about ${inputMessage}. Return ONLY a JSON object in this format:
{
    "columns": [
        {"field": "column1", "header": "Column 1"},
        {"field": "column2", "header": "Column 2"}
    ],
    "data": [
        {"column1": "value1", "column2": "value2"}
    ]
}

Rules:
1. Return ONLY the JSON object, no explanations
2. Make sure column names are descriptive and relevant to the topic
3. Return ONLY the JSON object, no explanations or additional text
4. Ensure data is accurate, comprehensive, and relevant to the topic
5. Include as many relevant entries as possible to provide a thorough overview
6. Make sure all field names in data match column fields exactly
7. Each entry should be unique and provide distinct information`,
                responseFormat: 'json'
            });

            const tableData = JSON.parse(response.responseText);
            if (tableData.columns && tableData.data) {
                const modalId = Date.now().toString();
                // Try to find a position in the grid (14 columns wide, 5 rows tall)
                const gridPosition = addModal(modalId, 14, 5);

                if (gridPosition) {
                    // Make modal wider by using 16 columns instead of 14
                    const pos = gridToPercent(gridPosition.x, gridPosition.y, 16, 7);
                    await createModal({
                        type: 'table',
                        position: pos,
                        content: tableData
                    });
                }

                const columnCount = tableData.columns.length;
                const rowCount = tableData.data.length;
                const botMessage: VisibleMessage = {
                    id: Date.now().toString(),
                    type: 'system',
                    content: `I've created a table showing ${rowCount} entries with ${columnCount} columns of information about ${inputMessage}. You can view it in the window above.`,
                    timestamp: new Date(),
                    isVisible: true
                };
                setMessages(prev => [...prev, botMessage]);
            }
        } catch (error) {
            console.error('Error processing response:', error);
            const errorMessage: VisibleMessage = {
                id: Date.now().toString(),
                type: 'system',
                content: "Sorry, I ran into an error displaying the table. Please try again.",
                timestamp: new Date(),
                isVisible: true
            };
            setMessages(prev => [...prev, errorMessage]);
        }
    };

    const handleModalClose = (id: string) => {
        removeModal(id);
        removeGridModal(id);
    };

    return (
        <div className="w-full h-full flex flex-col">
            <div className="flex-1 relative w-full">
                {/* Grid Container */}
                <div className="absolute inset-0 p-4">
                    <div className="relative w-full h-full border border-gray-200 bg-white">
                        {/* Grid Lines and Labels */}
                        <div className="absolute inset-0 grid grid-cols-20 grid-rows-8">
                            {/* Grid Cells with Coordinates */}
                            {Array.from({ length: 160 }).map((_, i) => {
                                const col = i % 20;
                                const row = Math.floor(i / 20);
                                const colLabel = String.fromCharCode(65 + col);
                                const rowLabel = row + 1;
                                return (
                                    <div
                                        key={i}
                                        className="border border-gray-100 relative hover:bg-gray-50"
                                        style={{ gridColumn: `${col + 1}`, gridRow: `${row + 1}` }}
                                    >
                                        <span className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 text-gray-300 text-xs select-none">
                                            {`${colLabel}${rowLabel}`}
                                        </span>
                                    </div>
                                );
                            })}
                        </div>
                        {/* Modal Container */}
                        <ModalContainer modals={modals} onClose={handleModalClose} />
                    </div>
                </div>

                <div className="fixed bottom-0 right-8 w-[400px] z-40">
                    <div className="w-full mb-1">
                        {messages.map((message) => (
                            <div key={message.id} className="mb-0.5">
                                <ChatBubble
                                    message={message}
                                    position={message.type === 'user' ? 'right' : 'left'}
                                    bgColor={message.type === 'user' ? '#3b958a' : '#3d8b96'}
                                    isVisible={message.isVisible}
                                />
                            </div>
                        ))}
                    </div>
                    <div className="scale-75 origin-bottom-right flex justify-end translate-y-2">
                        <MoleculeAvatar />
                    </div>
                </div>
            </div>

            <div className="w-full flex justify-center absolute bottom-5">
                <div className="w-2/3 flex items-center gap-2">
                    <form onSubmit={handleSendMessage} className="flex-1 flex gap-2">
                        <div className="flex-grow relative">
                            <input
                                type="text"
                                value={inputMessage}
                                onChange={(e) => setInputMessage(e.target.value)}
                                placeholder="Example: Show me a table about beer"
                                className="w-full px-4 py-3 rounded-lg border border-gray-200 focus:outline-none focus:border-teal-500 shadow-md bg-white"
                            />
                        </div>
                        <button
                            type="submit"
                            className="p-3 bg-teal-500 text-white rounded-lg hover:bg-teal-600 transition-colors shadow-md flex items-center justify-center"
                        >
                            <svg
                                xmlns="http://www.w3.org/2000/svg"
                                viewBox="0 0 24 24"
                                fill="currentColor"
                                className="w-5 h-5"
                            >
                                <path
                                    d="M3.478 2.404a.75.75 0 0 0-.926.941l2.432 7.905H13.5a.75.75 0 0 1 0 1.5H4.984l-2.432 7.905a.75.75 0 0 0 .926.94 60.519 60.519 0 0 0 18.445-8.986.75.75 0 0 0 0-1.218A60.517 60.517 0 0 0 3.478 2.404Z"
                                />
                            </svg>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    );
};

export default FuseMindHome; 