import React, { useState, useEffect } from 'react'; import { IonPage, IonContent, IonHeader, IonToolbar, IonTitle, IonButtons, IonButton, IonIcon, IonSpinner, IonItem, IonLabel, IonInput, IonTextarea, } from '@ionic/react'; import { useHistory, useParams } from 'react-router-dom'; import { supabase } from '../supabase'; import { useAuth } from '../contexts/AuthContext'; import { chevronBackOutline, saveOutline, trashOutline } from 'ionicons/icons'; const AdminNewsForm: React.FC = () => { const history = useHistory(); const { id } = useParams<{ id: string }>(); const isEdit = !!id && id !== 'new'; const { user, profile } = useAuth(); const [loading, setLoading] = useState(false); const [initialLoading, setInitialLoading] = useState(isEdit); const [error, setError] = useState(null); const [title, setTitle] = useState(''); const [content, setContent] = useState(''); const [imageUrl, setImageUrl] = useState(''); const showError = (msg: string) => { setError(msg); setTimeout(() => setError(null), 4000); }; useEffect(() => { if (profile?.role !== 'admin') { history.replace('/profile'); return; } if (isEdit) { loadNewsItem(); } }, [profile, isEdit]); const loadNewsItem = async () => { try { const { data, error } = await supabase .from('news') .select('*') .eq('id', id) .single(); if (error) throw error; if (data) { setTitle(data.title); setContent(data.content); setImageUrl(data.image_url || ''); } } catch (err: any) { showError(err.message); } finally { setInitialLoading(false); } }; const handleSave = async () => { if (!title.trim() || !content.trim()) { showError('Title and content are required.'); return; } setLoading(true); try { if (isEdit) { const { error } = await supabase .from('news') .update({ title, content, image_url: imageUrl.trim() || null, }) .eq('id', id); if (error) throw error; } else { const { error } = await supabase.from('news').insert({ title, content, image_url: imageUrl.trim() || null, created_by: user!.id, }); if (error) throw error; } history.goBack(); } catch (err: any) { showError(err.message); setLoading(false); } }; const handleDelete = async () => { if (!window.confirm('Delete this news item?')) return; setLoading(true); try { const { error } = await supabase.from('news').delete().eq('id', id); if (error) throw error; history.goBack(); } catch (err: any) { showError(err.message); setLoading(false); } }; if (initialLoading) { return ( history.goBack()}>
); } return ( history.goBack()}> {isEdit ? 'Edit News' : 'Create News'} {isEdit && ( )}
{error && (
{error}
)}
setTitle(e.detail.value!)} placeholder="Enter news title" style={{ fontWeight: '500' }} />
setImageUrl(e.detail.value!)} placeholder="https://example.com/image.jpg" />
setContent(e.detail.value!)} placeholder="Write your news update here..." autoGrow style={{ minHeight: '150px' }} />
); }; export default AdminNewsForm;