"use client" import { useState, useEffect } from "react" import Link from "next/link" import { useLoading } from "@/contexts/loading-context" import { Button } from "@/components/ui/button" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" 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 { Badge } from "@/components/ui/badge" import { Alert, AlertDescription } from "@/components/ui/alert" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { useAuth } from "@/contexts/supabase-auth-context" import { Cpu, ArrowLeft, Plus, Wrench, Truck, AlertTriangle, CheckCircle, Clock, Search, Filter, FileText, Phone, Mail, HelpCircle, Settings, User, Calendar, Tag, } from "lucide-react" // Mock support ticket data const mockTickets = [ { id: "TKT-001", title: "PC won't boot after assembly", type: "troubleshooting", priority: "high", status: "open", createdAt: "2024-01-15", updatedAt: "2024-01-16", description: "My PC won't turn on after I assembled all the components. No lights or fans spinning.", assignedTo: "Tech Support", replies: 2, }, { id: "TKT-002", title: "Request for delivery service", type: "delivery", priority: "medium", status: "in_progress", createdAt: "2024-01-14", updatedAt: "2024-01-15", description: "I need help with delivery options for my completed build.", assignedTo: "Delivery Team", replies: 1, }, { id: "TKT-003", title: "Component compatibility issue", type: "build_problem", priority: "low", status: "resolved", createdAt: "2024-01-10", updatedAt: "2024-01-12", description: "RAM not fitting properly in motherboard slots.", assignedTo: "Build Support", replies: 3, }, ] const supportTypes = [ { value: "troubleshooting", label: "Troubleshooting", icon: Wrench, description: "Technical issues and problems" }, { value: "build_problem", label: "Build Problem", icon: Settings, description: "Assembly and compatibility issues" }, { value: "delivery", label: "Delivery/Repair", icon: Truck, description: "Shipping and repair services" }, { value: "general", label: "General Inquiry", icon: HelpCircle, description: "General questions and support" }, ] const priorityLevels = [ { value: "low", label: "Low", color: "bg-green-100 text-green-800" }, { value: "medium", label: "Medium", color: "bg-yellow-100 text-yellow-800" }, { value: "high", label: "High", color: "bg-orange-100 text-orange-800" }, { value: "urgent", label: "Urgent", color: "bg-red-100 text-red-800" }, ] const statusOptions = [ { value: "open", label: "Open", color: "bg-blue-100 text-blue-800" }, { value: "in_progress", label: "In Progress", color: "bg-yellow-100 text-yellow-800" }, { value: "resolved", label: "Resolved", color: "bg-green-100 text-green-800" }, { value: "closed", label: "Closed", color: "bg-gray-100 text-gray-800" }, ] export default function SupportPage() { const { user } = useAuth() const [activeTab, setActiveTab] = useState("create") const [searchTerm, setSearchTerm] = useState("") const [statusFilter, setStatusFilter] = useState("all") const [typeFilter, setTypeFilter] = useState("all") const { startLoading } = useLoading() // Load tickets from localStorage or use mock data const loadTickets = () => { if (typeof window !== 'undefined') { const savedTickets = localStorage.getItem('buildmate-support-tickets') if (savedTickets) { try { const tickets = JSON.parse(savedTickets) // Normalize replies: if it's an array, convert to count; if missing, set to 0 return tickets.map((ticket: any) => ({ ...ticket, replies: Array.isArray(ticket.replies) ? ticket.replies.length : (typeof ticket.replies === 'number' ? ticket.replies : 0) })) } catch (e) { console.error('Error loading tickets from localStorage:', e) } } } return mockTickets } const [tickets, setTickets] = useState(() => loadTickets()) // Save tickets to localStorage whenever they change useEffect(() => { if (typeof window !== 'undefined') { localStorage.setItem('buildmate-support-tickets', JSON.stringify(tickets)) } }, [tickets]) // New ticket form state const [newTicket, setNewTicket] = useState({ title: "", type: "", priority: "medium", description: "", buildId: "", }) const [isSubmitting, setIsSubmitting] = useState(false) const [submitSuccess, setSubmitSuccess] = useState(false) const handleSubmitTicket = async (e: React.FormEvent) => { e.preventDefault() setIsSubmitting(true) // Generate ticket ID const ticketId = `TKT-${String(tickets.length + 1).padStart(3, '0')}` const today = new Date().toISOString().split('T')[0] // Create new ticket const createdTicket = { id: ticketId, title: newTicket.title, type: newTicket.type, priority: newTicket.priority, status: "open", createdAt: today, updatedAt: today, description: newTicket.description, assignedTo: "Tech Support", replies: 0, buildId: newTicket.buildId || null, userId: user?.user_id || null, } // Add ticket to the list setTickets(prevTickets => [createdTicket, ...prevTickets]) console.log("Creating support ticket:", createdTicket) // Send email notification to sales.centraljuan.net@gmail.com try { const emailResponse = await fetch("/api/support/send-ticket-email", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...createdTicket, userName: user?.user_name || null, userEmail: user?.email || null, }), }) const emailData = await emailResponse.json() if (emailResponse.ok) { console.log("✅ Support ticket email sent successfully:", emailData) } else { console.error("⚠️ Failed to send support ticket email:", emailData.error) // Don't fail the ticket creation if email fails } } catch (emailError) { console.error("⚠️ Error sending support ticket email:", emailError) // Don't fail the ticket creation if email fails } setSubmitSuccess(true) setIsSubmitting(false) // Reset form setNewTicket({ title: "", type: "", priority: "medium", description: "", buildId: "", }) // Redirect to profile to view tickets setTimeout(() => { setSubmitSuccess(false) if (typeof window !== 'undefined') { window.location.href = "/profile" } }, 2000) } const filteredTickets = tickets.filter(ticket => { const matchesSearch = ticket.title.toLowerCase().includes(searchTerm.toLowerCase()) || ticket.description.toLowerCase().includes(searchTerm.toLowerCase()) const matchesStatus = statusFilter === "all" || ticket.status === statusFilter const matchesType = typeFilter === "all" || ticket.type === typeFilter return matchesSearch && matchesStatus && matchesType }) const getStatusIcon = (status: string) => { switch (status) { case "open": return case "in_progress": return case "resolved": return case "closed": return default: return } } const getPriorityColor = (priority: string) => { const level = priorityLevels.find(p => p.value === priority) return level?.color || "bg-gray-100 text-gray-800" } const getStatusColor = (status: string) => { const option = statusOptions.find(s => s.value === status) return option?.color || "bg-gray-100 text-gray-800" } return (
{/* Page header */}

Support

Create a ticket for technical help, build issues, or delivery—or browse the Help Center for quick answers.

Create Ticket Help Center {/* Create Ticket Tab */} Create Support Ticket Describe your issue and we'll help you resolve it quickly {submitSuccess && ( Your support ticket has been created successfully! We'll get back to you soon. )}
setNewTicket({ ...newTicket, title: e.target.value })} placeholder="Brief description of your issue" required />
setNewTicket({ ...newTicket, buildId: e.target.value })} placeholder="If related to a specific build" />