import { AnimatePresence, motion } from 'framer-motion'; import type { SupabaseAlert } from '~/types/actions'; import { classNames } from '~/utils/classNames'; import { supabaseConnection } from '~/lib/stores/supabase'; import { useStore } from '@nanostores/react'; import { useState } from 'react'; interface Props { alert: SupabaseAlert; clearAlert: () => void; postMessage: (message: string) => void; } export function SupabaseChatAlert({ alert, clearAlert, postMessage }: Props) { const { content } = alert; const connection = useStore(supabaseConnection); const [isExecuting, setIsExecuting] = useState(false); const [isCollapsed, setIsCollapsed] = useState(true); // Determine connection state const isConnected = !!(connection.token && connection.selectedProjectId); // Set title and description based on connection state const title = isConnected ? 'Supabase Query' : 'Supabase Connection Required'; const description = isConnected ? 'Execute database query' : 'Supabase connection required'; const message = isConnected ? 'Please review the proposed changes and apply them to your database.' : 'Please connect to Supabase to continue with this operation.'; const handleConnectClick = () => { // Dispatch an event to open the Supabase connection dialog document.dispatchEvent(new CustomEvent('open-supabase-connection')); }; // Determine if we should show the Connect button or Apply Changes button const showConnectButton = !isConnected; const executeSupabaseAction = async (sql: string) => { if (!connection.token || !connection.selectedProjectId) { console.error('No Supabase token or project selected'); return; } setIsExecuting(true); try { const response = await fetch('/api/supabase/query', { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${connection.token}`, }, body: JSON.stringify({ projectId: connection.selectedProjectId, query: sql, }), }); if (!response.ok) { const errorData = (await response.json()) as any; throw new Error(`Supabase query failed: ${errorData.error?.message || response.statusText}`); } const result = await response.json(); console.log('Supabase query executed successfully:', result); clearAlert(); } catch (error) { console.error('Failed to execute Supabase action:', error); postMessage( `*Error executing Supabase query please fix and return the query again*\n\`\`\`\n${error instanceof Error ? error.message : String(error)}\n\`\`\`\n`, ); } finally { setIsExecuting(false); } }; const cleanSqlContent = (content: string) => { if (!content) { return ''; } let cleaned = content.replace(/\/\*[\s\S]*?\*\//g, ''); cleaned = cleaned.replace(/(--).*$/gm, '').replace(/(#).*$/gm, ''); const statements = cleaned .split(';') .map((stmt) => stmt.trim()) .filter((stmt) => stmt.length > 0) .join(';\n\n'); return statements; }; return ( {/* Header */}

{title}

{/* SQL Content */}
{!isConnected ? (
You must first connect to Supabase and select a project.
) : ( <>
setIsCollapsed(!isCollapsed)} >
{description || 'Create table and setup auth'}
{!isCollapsed && content && (
{cleanSqlContent(content)}
)} )}
{/* Message and Actions */}

{message}

{showConnectButton ? ( ) : ( )}
); }