"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
Create a ticket for technical help, build issues, or delivery—or browse the Help Center for quick answers.
Having technical issues? We can help diagnose and fix problems with your build.
Need help with assembly or compatibility issues? Our experts are here to help.
Need delivery services or repair work? We offer comprehensive support.
Use our compatibility checker in the PC builder. It automatically validates component compatibility and suggests alternatives if needed.
Check all connections, ensure RAM is properly seated, verify power supply connections, and check that the CPU is correctly installed.
Yes! We offer professional assembly services and can deliver your completed build. Contact support for more information.
We offer 30-day returns on unopened components and 14-day returns on opened items. Contact support for return requests.
Phone Support
1-800-BUILDMATE (Mon-Fri 9AM-6PM EST)
Email Support
support@buildmate.com