"use client"

import { useState } from "react"
import Link from "next/link"
import { Sidebar } from "@/components/dashboard/sidebar"
import { Header } from "@/components/dashboard/header"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import {
  HelpCircle,
  BookOpen,
  MessageSquare,
  Mail,
  ChevronRight,
  Plus,
  Clock,
  CheckCircle2,
  AlertCircle,
  Loader2,
  Send,
  ArrowLeft,
  Search,
  FileText,
  Users,
  Shield,
  Lightbulb,
  X,
  Paperclip,
  Image,
  File,
  Trash2,
} from "lucide-react"

// Sample tickets data
const sampleTickets = [
  {
    id: "TKT-001",
    subject: "Unable to upload images to my idea post",
    status: "open",
    priority: "medium",
    createdAt: "Mar 18, 2026",
    updatedAt: "Mar 19, 2026",
    messages: [
      {
        id: 1,
        sender: "user",
        name: "Khushoo Gupta",
        message: "I'm trying to upload images to my idea post but the upload keeps failing. I've tried multiple file formats (JPG, PNG) but nothing works. The file size is under 5MB.",
        timestamp: "Mar 18, 2026 at 10:30 AM",
      },
      {
        id: 2,
        sender: "support",
        name: "Support Team",
        message: "Thank you for reaching out. We're looking into this issue. Could you please let us know which browser you're using and if you see any error messages when the upload fails?",
        timestamp: "Mar 18, 2026 at 2:15 PM",
      },
      {
        id: 3,
        sender: "user",
        name: "Khushoo Gupta",
        message: "I'm using Chrome version 122. The error message says 'Upload failed. Please try again.'",
        timestamp: "Mar 19, 2026 at 9:00 AM",
      },
    ],
  },
  {
    id: "TKT-002",
    subject: "How to change my username?",
    status: "resolved",
    priority: "low",
    createdAt: "Mar 15, 2026",
    updatedAt: "Mar 16, 2026",
    messages: [
      {
        id: 1,
        sender: "user",
        name: "Khushoo Gupta",
        message: "How can I change my username? I can't find the option in settings.",
        timestamp: "Mar 15, 2026 at 3:45 PM",
      },
      {
        id: 2,
        sender: "support",
        name: "Support Team",
        message: "You can change your username by going to Settings > Profile > Basic Info section. Click the Edit button and you'll be able to update your username there. Note that usernames must be unique.",
        timestamp: "Mar 16, 2026 at 10:00 AM",
      },
    ],
  },
  {
    id: "TKT-003",
    subject: "Request for business account upgrade",
    status: "in-progress",
    priority: "high",
    createdAt: "Mar 17, 2026",
    updatedAt: "Mar 18, 2026",
    messages: [
      {
        id: 1,
        sender: "user",
        name: "Khushoo Gupta",
        message: "I would like to upgrade my individual account to a business account. What are the steps and requirements?",
        timestamp: "Mar 17, 2026 at 11:20 AM",
      },
      {
        id: 2,
        sender: "support",
        name: "Support Team",
        message: "Thank you for your interest in upgrading to a business account! To proceed, we'll need your business registration documents and a brief description of your company. Our team is reviewing your request and will get back to you within 24-48 hours.",
        timestamp: "Mar 18, 2026 at 9:30 AM",
      },
    ],
  },
]

const helpCategories = [
  {
    icon: Lightbulb,
    title: "Posting Ideas",
    description: "Learn how to create, edit, and manage your ideas",
    articles: 12,
  },
  {
    icon: Users,
    title: "Collaboration",
    description: "Connect with investors and other entrepreneurs",
    articles: 8,
  },
  {
    icon: Shield,
    title: "Privacy & Security",
    description: "Manage your account security and privacy settings",
    articles: 6,
  },
  {
    icon: FileText,
    title: "Account & Profile",
    description: "Update your profile and account settings",
    articles: 10,
  },
]

const faqItems = [
  {
    question: "How do I post a new idea?",
    answer: "Click on the 'Write something...' box on your home feed, enter your idea details, add any attachments, and click Post.",
  },
  {
    question: "Can I edit my idea after posting?",
    answer: "Yes, click the three dots menu on your idea post and select 'Edit'. You can modify the content within 24 hours of posting.",
  },
  {
    question: "How do collaboration requests work?",
    answer: "When AI matches your idea with potential collaborators, they can send you a collaboration request. Premium users can initiate requests directly.",
  },
  {
    question: "Is my idea protected?",
    answer: "Your ideas are timestamped and stored securely. We recommend not sharing sensitive proprietary information until you've established trust with potential collaborators.",
  },
]

const statusConfig = {
  open: { label: "Open", color: "text-blue-400 bg-blue-400/10", icon: AlertCircle },
  "in-progress": { label: "In Progress", color: "text-amber-400 bg-amber-400/10", icon: Loader2 },
  resolved: { label: "Resolved", color: "text-emerald-400 bg-emerald-400/10", icon: CheckCircle2 },
}

export default function HelpPage() {
  const [activeTab, setActiveTab] = useState<"help" | "tickets">("help")
  const [selectedTicket, setSelectedTicket] = useState<typeof sampleTickets[0] | null>(null)
  const [showNewTicket, setShowNewTicket] = useState(false)
  const [newTicketSubject, setNewTicketSubject] = useState("")
  const [newTicketMessage, setNewTicketMessage] = useState("")
  const [newReply, setNewReply] = useState("")
  const [searchQuery, setSearchQuery] = useState("")
  const [attachments, setAttachments] = useState<{ name: string; size: string; type: string }[]>([])

  const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files
    if (!files) return
    
    const newAttachments = Array.from(files).map(file => ({
      name: file.name,
      size: `${(file.size / 1024).toFixed(1)} KB`,
      type: file.type.startsWith('image/') ? 'image' : 'file'
    }))
    
    setAttachments(prev => [...prev, ...newAttachments])
    e.target.value = '' // Reset input
  }

  const removeAttachment = (index: number) => {
    setAttachments(prev => prev.filter((_, i) => i !== index))
  }

  const handleCreateTicket = () => {
    if (!newTicketSubject.trim() || !newTicketMessage.trim()) return
    // In real app, this would create a ticket via API with attachments
    setShowNewTicket(false)
    setNewTicketSubject("")
    setNewTicketMessage("")
    setAttachments([])
    setActiveTab("tickets")
  }

  const handleSendReply = () => {
    if (!newReply.trim() || !selectedTicket) return
    // In real app, this would send the reply via API
    setNewReply("")
  }

  return (
    <div className="min-h-screen bg-background">
      <Sidebar />
      <div className="lg:pl-72">
        <Header />
        <main className="p-4 lg:p-6">
          <div className="max-w-4xl mx-auto">
            {/* Page Header */}
            <div className="mb-8">
              <h1 className="text-2xl font-bold text-foreground mb-2">Help & Support</h1>
              <p className="text-muted-foreground">Find answers, browse help articles, or contact our support team</p>
            </div>

            {/* Tabs */}
            <div className="flex gap-2 mb-6">
              <button
                onClick={() => { setActiveTab("help"); setSelectedTicket(null); setShowNewTicket(false); }}
                className={cn(
                  "flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium transition-all",
                  activeTab === "help"
                    ? "bg-primary text-primary-foreground"
                    : "bg-secondary/50 text-muted-foreground hover:bg-secondary hover:text-foreground"
                )}
              >
                <HelpCircle className="h-4 w-4" />
                Help Center
              </button>
              <button
                onClick={() => { setActiveTab("tickets"); setShowNewTicket(false); }}
                className={cn(
                  "flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium transition-all",
                  activeTab === "tickets"
                    ? "bg-primary text-primary-foreground"
                    : "bg-secondary/50 text-muted-foreground hover:bg-secondary hover:text-foreground"
                )}
              >
                <MessageSquare className="h-4 w-4" />
                Support Tickets
                <span className="flex h-5 min-w-5 items-center justify-center rounded-full bg-accent/20 px-1.5 text-xs">
                  {sampleTickets.filter(t => t.status !== "resolved").length}
                </span>
              </button>
            </div>

            {/* Help Center Tab */}
            {activeTab === "help" && !showNewTicket && (
              <div className="space-y-6">
                {/* Search */}
                <div className="relative">
                  <Search className="absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground" />
                  <input
                    type="text"
                    placeholder="Search for help articles..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="w-full rounded-2xl bg-secondary/50 pl-12 pr-4 py-3.5 text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                  />
                </div>

                {/* Help Categories */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  {helpCategories.map((category) => (
                    <div
                      key={category.title}
                      className="rounded-2xl glass glass-border p-5 hover:bg-secondary/30 cursor-pointer transition-all group"
                    >
                      <div className="flex items-start gap-4">
                        <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-primary/10">
                          <category.icon className="h-6 w-6 text-primary" />
                        </div>
                        <div className="flex-1">
                          <h3 className="font-semibold text-foreground group-hover:text-primary transition-colors">
                            {category.title}
                          </h3>
                          <p className="text-sm text-muted-foreground mt-1">{category.description}</p>
                          <p className="text-xs text-primary mt-2">{category.articles} articles</p>
                        </div>
                        <ChevronRight className="h-5 w-5 text-muted-foreground group-hover:text-primary transition-colors" />
                      </div>
                    </div>
                  ))}
                </div>

                {/* FAQ Section */}
                <div className="rounded-2xl glass glass-border p-6">
                  <h2 className="text-lg font-semibold text-foreground mb-4">Frequently Asked Questions</h2>
                  <div className="space-y-4">
                    {faqItems.map((faq, idx) => (
                      <div key={idx} className="border-b border-border/50 pb-4 last:border-0 last:pb-0">
                        <h4 className="font-medium text-foreground mb-2">{faq.question}</h4>
                        <p className="text-sm text-muted-foreground">{faq.answer}</p>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Contact Support CTA */}
                <div className="rounded-2xl bg-primary/10 border border-primary/20 p-6">
                  <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
                    <div>
                      <h3 className="font-semibold text-foreground mb-1">Can't find what you're looking for?</h3>
                      <p className="text-sm text-muted-foreground">Create a support ticket and our team will help you</p>
                    </div>
                    <Button onClick={() => setShowNewTicket(true)} className="gap-2">
                      <Plus className="h-4 w-4" />
                      Create Ticket
                    </Button>
                  </div>
                </div>

                {/* Contact Info */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div className="rounded-2xl glass glass-border p-5">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary">
                        <Mail className="h-5 w-5 text-muted-foreground" />
                      </div>
                      <div>
                        <h4 className="font-medium text-foreground">Email Support</h4>
                        <p className="text-sm text-primary">support@checkuridea.com</p>
                      </div>
                    </div>
                    <p className="text-xs text-muted-foreground">Response time: 24-48 hours</p>
                  </div>
                  <div className="rounded-2xl glass glass-border p-5">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-secondary">
                        <BookOpen className="h-5 w-5 text-muted-foreground" />
                      </div>
                      <div>
                        <h4 className="font-medium text-foreground">Documentation</h4>
                        <p className="text-sm text-primary">docs.checkuridea.com</p>
                      </div>
                    </div>
                    <p className="text-xs text-muted-foreground">Detailed guides and tutorials</p>
                  </div>
                </div>
              </div>
            )}

            {/* New Ticket Form */}
            {showNewTicket && (
              <div className="rounded-2xl glass glass-border p-6">
                <div className="flex items-center justify-between mb-6">
                  <div className="flex items-center gap-3">
                    <button
                      onClick={() => setShowNewTicket(false)}
                      className="flex h-9 w-9 items-center justify-center rounded-lg bg-secondary/50 hover:bg-secondary transition-colors"
                    >
                      <ArrowLeft className="h-4 w-4 text-muted-foreground" />
                    </button>
                    <h2 className="text-lg font-semibold text-foreground">Create Support Ticket</h2>
                  </div>
                </div>

                <div className="space-y-4">
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-2">Subject</label>
                    <input
                      type="text"
                      value={newTicketSubject}
                      onChange={(e) => setNewTicketSubject(e.target.value)}
                      placeholder="Brief description of your issue"
                      className="w-full rounded-xl bg-secondary/50 px-4 py-3 text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/50"
                    />
                  </div>
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-2">Message</label>
                    <textarea
                      value={newTicketMessage}
                      onChange={(e) => setNewTicketMessage(e.target.value)}
                      placeholder="Describe your issue in detail. Include any relevant information that might help us assist you better."
                      rows={6}
                      className="w-full rounded-xl bg-secondary/50 px-4 py-3 text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none"
                    />
                  </div>

                  {/* Attachments Section */}
                  <div>
                    <label className="block text-sm font-medium text-foreground mb-2">
                      Attachments <span className="text-muted-foreground font-normal">(optional)</span>
                    </label>
                    <p className="text-xs text-muted-foreground mb-3">
                      Attach screenshots or files to help explain your issue. Max 5 files, 10MB each.
                    </p>
                    
                    {/* Upload Area */}
                    <label className="flex flex-col items-center justify-center w-full h-32 rounded-xl border-2 border-dashed border-border hover:border-primary/50 bg-secondary/30 hover:bg-secondary/50 cursor-pointer transition-all">
                      <div className="flex flex-col items-center justify-center pt-5 pb-6">
                        <Paperclip className="h-8 w-8 text-muted-foreground mb-2" />
                        <p className="text-sm text-muted-foreground">
                          <span className="text-primary font-medium">Click to upload</span> or drag and drop
                        </p>
                        <p className="text-xs text-muted-foreground mt-1">PNG, JPG, PDF up to 10MB</p>
                      </div>
                      <input
                        type="file"
                        className="hidden"
                        multiple
                        accept="image/*,.pdf,.doc,.docx"
                        onChange={handleFileUpload}
                      />
                    </label>

                    {/* Attached Files List */}
                    {attachments.length > 0 && (
                      <div className="mt-3 space-y-2">
                        {attachments.map((file, index) => (
                          <div
                            key={index}
                            className="flex items-center justify-between gap-3 rounded-lg bg-secondary/50 px-3 py-2"
                          >
                            <div className="flex items-center gap-3 min-w-0">
                              <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary/10">
                                {file.type === 'image' ? (
                                  <Image className="h-4 w-4 text-primary" />
                                ) : (
                                  <File className="h-4 w-4 text-primary" />
                                )}
                              </div>
                              <div className="min-w-0">
                                <p className="text-sm text-foreground truncate">{file.name}</p>
                                <p className="text-xs text-muted-foreground">{file.size}</p>
                              </div>
                            </div>
                            <button
                              type="button"
                              onClick={() => removeAttachment(index)}
                              className="flex h-7 w-7 items-center justify-center rounded-lg hover:bg-destructive/10 text-muted-foreground hover:text-destructive transition-colors"
                            >
                              <Trash2 className="h-4 w-4" />
                            </button>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>

                  <div className="flex justify-end gap-3 pt-2">
                    <Button variant="outline" onClick={() => { setShowNewTicket(false); setAttachments([]); }}>
                      Cancel
                    </Button>
                    <Button onClick={handleCreateTicket} className="gap-2">
                      <Send className="h-4 w-4" />
                      Submit Ticket
                    </Button>
                  </div>
                </div>
              </div>
            )}

            {/* Tickets Tab */}
            {activeTab === "tickets" && !selectedTicket && !showNewTicket && (
              <div className="space-y-4">
                {/* Ticket Header */}
                <div className="flex items-center justify-between">
                  <p className="text-sm text-muted-foreground">{sampleTickets.length} tickets</p>
                  <Button onClick={() => setShowNewTicket(true)} size="sm" className="gap-2">
                    <Plus className="h-4 w-4" />
                    New Ticket
                  </Button>
                </div>

                {/* Ticket List */}
                <div className="space-y-3">
                  {sampleTickets.map((ticket) => {
                    const status = statusConfig[ticket.status as keyof typeof statusConfig]
                    const StatusIcon = status.icon

                    return (
                      <div
                        key={ticket.id}
                        onClick={() => setSelectedTicket(ticket)}
                        className="rounded-2xl glass glass-border p-5 hover:bg-secondary/30 cursor-pointer transition-all"
                      >
                        <div className="flex items-start justify-between gap-4">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <span className="px-2 py-0.5 rounded bg-primary/10 text-primary text-xs font-bold font-mono">{ticket.id}</span>
                              <span className={cn("flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium", status.color)}>
                                <StatusIcon className={cn("h-3 w-3", ticket.status === "in-progress" && "animate-spin")} />
                                {status.label}
                              </span>
                            </div>
                            <h3 className="font-medium text-foreground truncate">{ticket.subject}</h3>
                            <div className="flex items-center gap-3 mt-2 text-xs text-muted-foreground">
                              <span className="flex items-center gap-1">
                                <Clock className="h-3 w-3" />
                                Created {ticket.createdAt}
                              </span>
                              <span>Updated {ticket.updatedAt}</span>
                            </div>
                          </div>
                          <ChevronRight className="h-5 w-5 text-muted-foreground shrink-0" />
                        </div>
                      </div>
                    )
                  })}
                </div>

                {sampleTickets.length === 0 && (
                  <div className="rounded-2xl glass glass-border p-12 text-center">
                    <MessageSquare className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                    <h3 className="font-semibold text-foreground mb-2">No tickets yet</h3>
                    <p className="text-sm text-muted-foreground mb-4">Create a ticket to get help from our support team</p>
                    <Button onClick={() => setShowNewTicket(true)} className="gap-2">
                      <Plus className="h-4 w-4" />
                      Create Your First Ticket
                    </Button>
                  </div>
                )}
              </div>
            )}

            {/* Ticket Detail View */}
            {selectedTicket && (
              <div className="space-y-4">
                {/* Ticket Header */}
                <div className="rounded-2xl glass glass-border p-5">
                  <div className="flex items-start justify-between gap-4">
                    <div className="flex items-center gap-3">
                      <button
                        onClick={() => setSelectedTicket(null)}
                        className="flex h-9 w-9 items-center justify-center rounded-lg bg-secondary/50 hover:bg-secondary transition-colors"
                      >
                        <ArrowLeft className="h-4 w-4 text-muted-foreground" />
                      </button>
                      <div>
                        <div className="flex items-center gap-2 mb-1">
                          <span className="px-2 py-0.5 rounded bg-primary/10 text-primary text-xs font-bold font-mono">{selectedTicket.id}</span>
                          {(() => {
                            const status = statusConfig[selectedTicket.status as keyof typeof statusConfig]
                            const StatusIcon = status.icon
                            return (
                              <span className={cn("flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium", status.color)}>
                                <StatusIcon className={cn("h-3 w-3", selectedTicket.status === "in-progress" && "animate-spin")} />
                                {status.label}
                              </span>
                            )
                          })()}
                        </div>
                        <h2 className="font-semibold text-foreground">{selectedTicket.subject}</h2>
                      </div>
                    </div>
                    {selectedTicket.status !== "resolved" && (
                      <Button variant="outline" size="sm" className="text-muted-foreground">
                        <X className="h-4 w-4 mr-1.5" />
                        Close Ticket
                      </Button>
                    )}
                  </div>
                </div>

                {/* Messages */}
                <div className="rounded-2xl glass glass-border p-5 space-y-4">
                  {selectedTicket.messages.map((msg) => (
                    <div
                      key={msg.id}
                      className={cn(
                        "flex gap-3",
                        msg.sender === "user" ? "flex-row" : "flex-row"
                      )}
                    >
                      <div className={cn(
                        "flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-bold",
                        msg.sender === "user" 
                          ? "bg-primary text-primary-foreground" 
                          : "bg-emerald-500/20 text-emerald-400"
                      )}>
                        {msg.sender === "user" ? "KG" : "CS"}
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <span className="font-medium text-foreground text-sm">{msg.name}</span>
                          {msg.sender === "support" && (
                            <span className="text-[10px] px-1.5 py-0.5 rounded bg-emerald-500/10 text-emerald-400 font-medium">
                              Support
                            </span>
                          )}
                        </div>
                        <div className={cn(
                          "rounded-2xl px-4 py-3 text-sm",
                          msg.sender === "user" 
                            ? "bg-secondary/50 text-foreground" 
                            : "bg-emerald-500/5 border border-emerald-500/20 text-foreground"
                        )}>
                          {msg.message}
                        </div>
                        <p className="text-xs text-muted-foreground mt-1.5">{msg.timestamp}</p>
                      </div>
                    </div>
                  ))}
                </div>

                {/* Reply Box */}
                {selectedTicket.status !== "resolved" && (
                  <div className="rounded-2xl glass glass-border p-5">
                    <textarea
                      value={newReply}
                      onChange={(e) => setNewReply(e.target.value)}
                      placeholder="Type your reply..."
                      rows={3}
                      className="w-full rounded-xl bg-secondary/50 px-4 py-3 text-sm text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary/50 resize-none mb-3"
                    />
                    <div className="flex justify-end">
                      <Button onClick={handleSendReply} className="gap-2">
                        <Send className="h-4 w-4" />
                        Send Reply
                      </Button>
                    </div>
                  </div>
                )}

                {selectedTicket.status === "resolved" && (
                  <div className="rounded-2xl bg-emerald-500/10 border border-emerald-500/20 p-4 text-center">
                    <CheckCircle2 className="h-6 w-6 text-emerald-400 mx-auto mb-2" />
                    <p className="text-sm text-foreground font-medium">This ticket has been resolved</p>
                    <p className="text-xs text-muted-foreground mt-1">If you need further assistance, please create a new ticket</p>
                  </div>
                )}
              </div>
            )}
          </div>
        </main>
      </div>
    </div>
  )
}
