import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { useState, useEffect } from 'react';
import { useChatStore } from '../../state/stores/useChatStore';
import { Dialog } from 'primereact/dialog';
import { generateTablePrompt } from '../../prompts/table-generation';
import { Toast } from 'primereact/toast';
import { useRef } from 'react';
import { InputText } from 'primereact/inputtext';

interface ChatGPTModalProps {
    content?: {
        prompt: string;
        id?: string;
        keywords?: string[];
        context?: string;
        tableSchema?: {
            name: string;
            fields: Array<{
                name: string;
                type: string;
                description?: string;
            }>;
        };
    };
}

interface TableData {
    columns: Array<{
        field: string;
        header: string;
    }>;
    data: any[];
    metadata?: {
        id?: string;
        keywords?: string[];
        context?: string;
        timestamp: string;
        actions?: Array<{
            action: string;
            target: string;
            description: string;
        }>;
    };
}

export const ChatGPTModal = ({ content }: ChatGPTModalProps) => {
    const [tableData, setTableData] = useState<TableData>({
        columns: [],
        data: [],
        metadata: {
            timestamp: new Date().toISOString()
        }
    });
    const [loading, setLoading] = useState(false);
    const [selectedRow, setSelectedRow] = useState<any>(null);
    const [showRowDialog, setShowRowDialog] = useState(false);
    const [finalPrompt, setFinalPrompt] = useState<string>('');
    const { sendChatRequest } = useChatStore();
    const toast = useRef<Toast>(null);

    const constructPath = (id: string | number, pathname: string): string => {
        // Remove any leading/trailing slashes from pathname
        const cleanPathname = pathname.replace(/^\/+|\/+$/g, '');
        // Construct the path with proper slashes
        return `/${id}/${cleanPathname}`.replace(/\/+/g, '/');
    };

    const findRowById = (id: string | number) => {
        const row = tableData.data.find(row => row.id?.toString() === id.toString());
        if (row) {
            setSelectedRow(row);
            setShowRowDialog(true);
            showToast('info', `Viewing details for ID: ${id}`);
        } else {
            showToast('warn', `No row found with ID: ${id}`);
        }
    };

    const handlePublicPath = (prompt: string) => {
        // Check for path construction pattern
        const pathMatch = prompt.match(/add\s+public\s+path\s+to\s+(\d+)\s+slash\s+([^\s]+)/i);
        if (pathMatch) {
            const [, id, pathname] = pathMatch;
            const constructedPath = constructPath(id, pathname);
            // Find the row with the given ID
            const rowIndex = tableData.data.findIndex(row => row.id?.toString() === id.toString());
            if (rowIndex !== -1) {
                // Update the path of the existing row
                setTableData(prev => {
                    const newData = [...prev.data];
                    newData[rowIndex] = {
                        ...newData[rowIndex],
                        path: constructedPath
                    };
                    // Add an 'add_path' action to metadata
                    return {
                        ...prev,
                        data: newData,
                        metadata: {
                            ...prev.metadata,
                            actions: [
                                ...(prev.metadata?.actions || []),
                                {
                                    action: 'add_path',
                                    target: constructedPath,
                                    description: `added public path ${constructedPath} to endpoint ID ${id}`
                                }
                            ]
                        }
                    };
                });
                showToast('success', `Updated path for ID ${id}: ${constructedPath}`);
                findRowById(id);
            } else {
                showToast('warn', `No endpoint found with ID: ${id}`);
            }
            return { id, constructedPath };
        }
        return null;
    };

    useEffect(() => {
        if (content?.prompt) {
            setFinalPrompt(content.prompt);
            // Handle public path update only, not endpoint creation
            handlePublicPath(content.prompt);
            generateTable();
        }
    }, [content]);

    const showToast = (severity: 'success' | 'info' | 'warn' | 'error', message: string) => {
        toast.current?.show({
            severity,
            summary: severity.charAt(0).toUpperCase() + severity.slice(1),
            detail: message,
            life: 3000
        });
    };

    const generateTable = async () => {
        if (!content?.prompt) return;

        setLoading(true);
        try {
            const promptText = generateTablePrompt({
                prompt: content.prompt,
                context: content.context,
                keywords: content.keywords,
                id: content.id,
                tableSchema: content.tableSchema
            });

            const response = await sendChatRequest('/chat/completions', {
                data: promptText,
                responseFormat: 'json'
            });

            if (response?.responseText) {
                try {
                    const parsedData = JSON.parse(response.responseText);
                    setTableData({
                        ...parsedData,
                        metadata: {
                            ...parsedData.metadata,
                            timestamp: new Date().toISOString()
                        }
                    });

                    // Show success message based on the primary action
                    const primaryAction = parsedData.metadata?.actions?.[0];
                    if (primaryAction) {
                        const actionMessage = {
                            create: 'Successfully created',
                            delete: 'Successfully deleted',
                            update: 'Successfully updated',
                            show: 'Successfully retrieved',
                            search: 'Search completed',
                            view: 'Viewing details'
                        }[primaryAction.action] || 'Operation completed';

                        showToast('success', `${actionMessage} ${primaryAction.target}`);
                    }
                } catch (error) {
                    console.error('Error parsing response:', error);
                    showToast('error', 'Error processing the response');
                }
            } else {
                showToast('error', 'Invalid response format');
            }
        } catch (error) {
            console.error('Error generating table:', error);
            showToast('error', 'Error generating table');
        } finally {
            setLoading(false);
        }
    };

    const handleRowClick = (event: any) => {
        const rowData = event.data;
        setSelectedRow(rowData);
        setShowRowDialog(true);

        // Add view action to metadata if not present
        if (tableData.metadata?.actions) {
            const hasViewAction = tableData.metadata.actions.some(
                action => action.action === 'view' && action.target === rowData.id
            );

            if (!hasViewAction) {
                setTableData(prev => ({
                    ...prev,
                    metadata: {
                        ...prev.metadata,
                        actions: [
                            ...(prev.metadata?.actions || []),
                            {
                                action: 'view',
                                target: rowData.id || 'selected row',
                                description: `view details for ${rowData.id || 'selected row'}`
                            }
                        ]
                    }
                }));
                showToast('info', `Viewing details for ${rowData.id || 'selected row'}`);
            }
        }
    };

    const renderRowDialog = () => {
        if (!selectedRow) return null;

        return (
            <Dialog
                visible={showRowDialog}
                onHide={() => setShowRowDialog(false)}
                header={`View Details - ${selectedRow.id || 'Selected Row'}`}
                style={{ width: '50vw' }}
            >
                <div className="grid">
                    {tableData.columns.map(col => (
                        <div key={col.field} className="col-12 md:col-6 p-2">
                            <div className="font-bold">{col.header}</div>
                            <div>{selectedRow[col.field] || 'N/A'}</div>
                        </div>
                    ))}
                </div>
            </Dialog>
        );
    };

    return (
        <>
            <Toast ref={toast} position="top-right" />
            <div className="flex flex-column gap-3 p-4 relative">
                {finalPrompt && (
                    <div className="mb-3">
                        <label className="block text-sm font-medium text-gray-700 mb-1">
                            Your Request
                        </label>
                        <InputText
                            value={finalPrompt}
                            readOnly
                            className="w-full p-2 border rounded"
                            style={{ backgroundColor: '#f8f9fa' }}
                        />
                    </div>
                )}
                <DataTable
                    value={tableData.data}
                    loading={loading}
                    className="w-full"
                    onRowClick={handleRowClick}
                    selectionMode="single"
                    rowHover
                >
                    {tableData.columns.map(col => (
                        <Column
                            key={col.field}
                            field={col.field}
                            header={col.header}
                            body={(rowData) => (
                                <div className="cursor-pointer hover:bg-gray-100 p-2">
                                    {rowData[col.field] || 'N/A'}
                                </div>
                            )}
                        />
                    ))}
                </DataTable>
                {tableData.metadata && (
                    <div className="text-sm text-gray-500 mt-2">
                        <p>ID: {tableData.metadata.id}</p>
                        <p>Keywords: {tableData.metadata.keywords?.join(', ')}</p>
                        <p>Context: {tableData.metadata.context}</p>
                        <p>Generated: {new Date(tableData.metadata.timestamp).toLocaleString()}</p>
                        {tableData.metadata.actions && tableData.metadata.actions.length > 0 && (
                            <div className="mt-2">
                                <p className="font-bold">Detected Actions:</p>
                                {tableData.metadata.actions.map((action, index) => (
                                    <div key={index} className="ml-2">
                                        <span className="font-semibold">{action.action}:</span> {action.target}
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>
                )}
                {renderRowDialog()}
            </div>
        </>
    );
};

export default ChatGPTModal; 