import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { useState, useEffect, useCallback } from 'react';
import { useChatStore } from '../state/stores/useChatStore';

interface ChatGPTModalProps {
    content?: {
        prompt: string;
    };
}

interface TableData {
    columns: Array<{
        field: string;
        header: string;
    }>;
    data: any[];
}

export const ChatGPTModal = ({ content }: ChatGPTModalProps) => {
    const [tableData, setTableData] = useState<TableData>({ columns: [], data: [] });
    const [loading, setLoading] = useState(false);
    const { sendChatRequest } = useChatStore();

    useEffect(() => {
        console.log('useEffect triggered with content:', content);
        if (content?.prompt) {
            generateTable();
        }
    }, [content]);

    const generateTable = async () => {
        if (!content?.prompt) return;
        console.log('Generating table for prompt:', content.prompt);

        setLoading(true);
        try {
            const response = await sendChatRequest('/chat/completions', {
                data: `Create a table with data about: ${content.prompt}
Return ONLY a JSON object in this format:
{
    "columns": [
        {"field": "column1", "header": "Column 1"},
        {"field": "column2", "header": "Column 2"}
    ],
    "data": [
        {"column1": "value1", "column2": "value2"},
        {"column1": "value3", "column2": "value4"}
    ]
}

Rules:
1. Return ONLY the JSON object, no explanations
2. Make sure field names in data match column fields exactly
3. Choose appropriate column names based on the topic
4. Include at least 5 rows of data`,
                responseFormat: 'json'
            });
            console.log('Got raw response:', response);

            if (response?.responseText) {
                console.log('Got responseText:', response.responseText);
                setTableData(JSON.parse(response.responseText));
            } else {
                console.error('Invalid response format:', response);
            }
        } catch (error) {
            console.error('Error generating table:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="flex flex-column gap-3 p-4">
            <DataTable value={tableData.data} loading={loading} className="w-full">
                {tableData.columns.map(col => (
                    <Column key={col.field} field={col.field} header={col.header} />
                ))}
            </DataTable>
        </div>
    );
};

export default ChatGPTModal; 