"use client" import { useState, useEffect } from 'react' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Badge } from '@/components/ui/badge' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs' import { Input } from '@/components/ui/input' import { Label } from '@/components/ui/label' import { Textarea } from '@/components/ui/textarea' import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select' import { CheckCircle, XCircle, Clock, RefreshCw, AlertCircle, Copy, Filter, Search, Edit, Plus, Save, Files, Settings } from 'lucide-react' import { adminApi, formatDate, getStatusColor, getComplexityColor } from '@/lib/api/admin' import { AdminTemplate, AdminStats } from '@/types/admin.types' import { TemplateEditDialog } from './template-edit-dialog' import { RejectDialog } from './reject-dialog' import { TemplateFeaturesManager } from './template-features-manager' import { AdminTemplatesList } from './admin-templates-list' import { useAdminNotifications } from '@/contexts/AdminNotificationContext' export function AdminTemplatesManager() { const [activeTab, setActiveTab] = useState("admin-templates") const [customTemplates, setCustomTemplates] = useState([]) const [templateStats, setTemplateStats] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [selectedTemplate, setSelectedTemplate] = useState(null) const [showTemplateEditDialog, setShowTemplateEditDialog] = useState(false) const [showRejectDialog, setShowRejectDialog] = useState(false) const [rejectItem, setRejectItem] = useState<{ id: string; name: string; type: 'template' } | null>(null) const [searchQuery, setSearchQuery] = useState('') const [statusFilter, setStatusFilter] = useState('all') const [showFeaturesManager, setShowFeaturesManager] = useState(false) const [selectedTemplateForFeatures, setSelectedTemplateForFeatures] = useState(null) // Create template form state const [newTemplate, setNewTemplate] = useState({ title: '', description: '', category: '', type: '', complexity: 'low', icon: '', gradient: '', border: '', text: '', subtext: '' }) const { removeByReference } = useAdminNotifications() // Load templates data const loadTemplatesData = async () => { try { setLoading(true) setError(null) console.log('Loading templates data...') const [templatesResponse, templateStatsResponse] = await Promise.all([ adminApi.getCustomTemplates(), // Try without status filter first adminApi.getTemplateStats() ]) console.log('Templates response:', templatesResponse) console.log('Template stats response:', templateStatsResponse) setCustomTemplates(templatesResponse || []) setTemplateStats(templateStatsResponse) } catch (err) { setError(err instanceof Error ? err.message : 'Failed to load templates data') console.error('Error loading templates data:', err) } finally { setLoading(false) } } useEffect(() => { loadTemplatesData() }, []) // Handle template review const handleTemplateReview = async (templateId: string, reviewData: { status: 'pending' | 'approved' | 'rejected' | 'duplicate'; admin_notes?: string }) => { try { await adminApi.reviewTemplate(templateId, reviewData) // Update the template in the list setCustomTemplates(prev => prev.map(t => t.id === templateId ? { ...t, status: reviewData.status as AdminTemplate['status'], admin_notes: reviewData.admin_notes } : t )) // Reload stats const newStats = await adminApi.getTemplateStats() setTemplateStats(newStats) } catch (err) { console.error('Error reviewing template:', err) alert('Error reviewing template') } } // Handle template update const handleTemplateUpdate = (templateId: string, updatedTemplate: AdminTemplate) => { setCustomTemplates(prev => prev.filter(t => t.id !== templateId)) } // Handle reject action const handleReject = async (adminNotes: string) => { if (!rejectItem) return try { await adminApi.rejectTemplate(rejectItem.id, adminNotes) setCustomTemplates(prev => prev.map(t => t.id === rejectItem.id ? { ...t, status: 'rejected', admin_notes: adminNotes } : t )) // Reload template stats const newStats = await adminApi.getTemplateStats() setTemplateStats(newStats) } catch (err) { console.error('Error rejecting template:', err) alert('Error rejecting template') } } // Handle approve action const handleApprove = async (templateId: string) => { // Optimistic UI: remove immediately setCustomTemplates(prev => prev.filter(t => t.id !== templateId)) try { // Get the template details first const template = customTemplates.find(t => t.id === templateId) if (template) { // Create new approved template in main templates table await adminApi.createApprovedTemplate(templateId, { title: template.title || '', description: template.description, category: template.category || '', type: template.type || '', icon: template.icon, gradient: template.gradient, border: template.border, text: template.text, subtext: template.subtext }) // Update the custom template status to approved await adminApi.reviewTemplate(templateId, { status: 'approved', admin_notes: 'Approved and created in main templates' }) // Remove related notifications for this template removeByReference('custom_template', templateId) } // Reload template stats const newStats = await adminApi.getTemplateStats() setTemplateStats(newStats) } catch (err) { console.error('Error approving template:', err) // Recover UI by reloading if optimistic removal was wrong await loadTemplatesData() } } // Handle create template const handleCreateTemplate = async (e: React.FormEvent) => { e.preventDefault() try { // Validate required fields if (!newTemplate.title || !newTemplate.description || !newTemplate.category || !newTemplate.type) { alert('Please fill in all required fields (Title, Description, Category, Type)') return } // Call API to create new custom template using the correct endpoint await adminApi.createCustomTemplate({ title: newTemplate.title, description: newTemplate.description, category: newTemplate.category, type: newTemplate.type, complexity: newTemplate.complexity, icon: newTemplate.icon, gradient: newTemplate.gradient, border: newTemplate.border, text: newTemplate.text, subtext: newTemplate.subtext }) // Reset form setNewTemplate({ title: '', description: '', category: '', type: '', complexity: 'low', icon: '', gradient: '', border: '', text: '', subtext: '' }) // Reload templates await loadTemplatesData() // Switch to manage tab setActiveTab("manage") alert('Template created successfully!') } catch (err) { console.error('Error creating template:', err) const errorMessage = err instanceof Error ? err.message : 'Failed to create template' alert(`Error creating template: ${errorMessage}`) } } // Filter templates based on search and status const filteredTemplates = customTemplates.filter(template => { const matchesSearch = template.title?.toLowerCase().includes(searchQuery.toLowerCase()) || template.description?.toLowerCase().includes(searchQuery.toLowerCase()) || template.category?.toLowerCase().includes(searchQuery.toLowerCase()) const matchesStatus = statusFilter === 'all' || template.status === statusFilter return matchesSearch && matchesStatus }) // Get status counts for templates const getTemplateStatusCount = (status: string) => { return (templateStats as AdminStats & { templates?: Array<{ status: string; count: number }> })?.templates?.find((s) => s.status === status)?.count || 0 } if (loading) { return (
Loading templates...
) } if (error) { return (
Error loading templates

{error}

) } return (
{/* Header */}

Templates Management

Manage templates and create new ones

{/* Stats Cards */}
Total Templates
{customTemplates.length}
Pending
{getTemplateStatusCount('pending')}
Approved
{getTemplateStatusCount('approved')}
Rejected
{getTemplateStatusCount('rejected')}
{/* Main Content */} Admin Templates Custom Templates ({customTemplates.length}) {/* Filters */}
setSearchQuery(e.target.value)} className="pl-10" />
{/* Templates List */}
{filteredTemplates.length === 0 ? (

No templates found

All templates have been reviewed or no templates match your filters.

) : ( filteredTemplates.map((template) => (

{template.title}

{template.status} {template.complexity} {template.category && ( {template.category} )}
{template.description && (

{template.description}

)}
Type: {template.type || 'Unknown'} Submitted: {formatDate(template.created_at)} Usage: {template.usage_count || 0}
{template.admin_notes && (

Admin Notes: {template.admin_notes}

)}
)) )}
Create New Template
setNewTemplate(prev => ({ ...prev, title: e.target.value }))} className="bg-white/5 border-white/10 text-white" placeholder="Enter template title" required />