'use client'

import { useEffect, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Textarea } from '@/components/ui/textarea'
import { Label } from '@/components/ui/label'
import { 
  HelpCircle, 
  Search, 
  Book, 
  Video, 
  FileText, 
  Phone, 
  Mail, 
  MessageCircle,
  ExternalLink,
  Clock,
  User,
  AlertCircle,
  CheckCircle,
  Star,
  Filter
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { AdminSidebar } from '@/components/admin-sidebar'

interface HelpArticle {
  id: string
  title: string
  category: string
  content: string
  type: 'article' | 'video' | 'faq'
  difficulty: 'beginner' | 'intermediate' | 'advanced'
  readTime: number
  views: number
  rating: number
  lastUpdated: string
  tags: string[]
}

interface SupportTicket {
  id: string
  subject: string
  description: string
  category: string
  priority: 'low' | 'medium' | 'high' | 'urgent'
  status: 'open' | 'in_progress' | 'resolved' | 'closed'
  createdAt: string
  updatedAt: string
  responses: number
}

export default function AdminHelp() {
  const router = useRouter()
  const [user, setUser] = useState<any>(null)
  const [loading, setLoading] = useState(true)
  const [activeTab, setActiveTab] = useState('articles')
  const [searchTerm, setSearchTerm] = useState('')
  const [categoryFilter, setCategoryFilter] = useState('all')
  const [typeFilter, setTypeFilter] = useState('all')
  const [isTicketModalOpen, setIsTicketModalOpen] = useState(false)
  
  const [articles] = useState<HelpArticle[]>([
    {
      id: '1',
      title: 'Panduan Dasar Admin Dashboard',
      category: 'dashboard',
      content: 'Panduan lengkap untuk menggunakan dashboard admin...',
      type: 'article',
      difficulty: 'beginner',
      readTime: 5,
      views: 245,
      rating: 4.8,
      lastUpdated: '2024-01-15',
      tags: ['dashboard', 'basic', 'navigation']
    },
    {
      id: '2',
      title: 'Cara Mengelola Layanan',
      category: 'services',
      content: 'Tutorial lengkap untuk menambah, mengedit, dan menghapus layanan...',
      type: 'video',
      difficulty: 'intermediate',
      readTime: 12,
      views: 189,
      rating: 4.6,
      lastUpdated: '2024-01-10',
      tags: ['services', 'management', 'crud']
    },
    {
      id: '3',
      title: 'Memproses Pengajuan Pengguna',
      category: 'requests',
      content: 'Langkah demi langkah dalam memproses pengajuan yang masuk...',
      type: 'article',
      difficulty: 'intermediate',
      readTime: 8,
      views: 312,
      rating: 4.9,
      lastUpdated: '2024-01-12',
      tags: ['requests', 'processing', 'workflow']
    }
  ])

  const [tickets] = useState<SupportTicket[]>([
    {
      id: '1',
      subject: 'Tidak bisa mengubah status pengajuan',
      description: 'Saya mengalami kesulitan saat mencoba mengubah status pengajuan dari pending ke in progress...',
      category: 'technical',
      priority: 'high',
      status: 'in_progress',
      createdAt: '2024-01-20',
      updatedAt: '2024-01-21',
      responses: 2
    },
    {
      id: '2',
      subject: 'Laporan bulanan tidak muncul',
      description: 'Laporan bulanan untuk Desember 2023 tidak dapat diakses...',
      category: 'reports',
      priority: 'medium',
      status: 'resolved',
      createdAt: '2024-01-18',
      updatedAt: '2024-01-19',
      responses: 3
    }
  ])

  const [ticketForm, setTicketForm] = useState({
    subject: '',
    description: '',
    category: '',
    priority: 'medium' as 'low' | 'medium' | 'high' | 'urgent'
  })

  useEffect(() => {
    // Check authentication
    const token = localStorage.getItem('adminToken')
    const userData = localStorage.getItem('adminUser')
    
    if (!token || !userData) {
      router.push('/admin/login')
      return
    }

    try {
      setUser(JSON.parse(userData))
    } catch (error) {
      router.push('/admin/login')
      return
    }

    setLoading(false)
  }, [router])

  const handleCreateTicket = async (e: React.FormEvent) => {
    e.preventDefault()
    // Handle ticket creation logic here
    console.log('Creating ticket:', ticketForm)
    setIsTicketModalOpen(false)
    setTicketForm({
      subject: '',
      description: '',
      category: '',
      priority: 'medium'
    })
  }

  const getDifficultyColor = (difficulty: string) => {
    switch (difficulty) {
      case 'beginner':
        return 'bg-green-100 text-green-800'
      case 'intermediate':
        return 'bg-yellow-100 text-yellow-800'
      case 'advanced':
        return 'bg-red-100 text-red-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'open':
        return 'bg-amber-100 text-amber-800'
      case 'in_progress':
        return 'bg-yellow-100 text-yellow-800'
      case 'resolved':
        return 'bg-green-100 text-green-800'
      case 'closed':
        return 'bg-gray-100 text-gray-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const getPriorityColor = (priority: string) => {
    switch (priority) {
      case 'low':
        return 'bg-gray-100 text-gray-800'
      case 'medium':
        return 'bg-amber-100 text-amber-800'
      case 'high':
        return 'bg-orange-100 text-orange-800'
      case 'urgent':
        return 'bg-red-100 text-red-800'
      default:
        return 'bg-gray-100 text-gray-800'
    }
  }

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleString('id-ID', {
      day: 'numeric',
      month: 'short',
      year: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  if (loading) {
    return (
      <AdminSidebar user={user}>
        <div className="flex items-center justify-center h-64">
          <div className="text-center">
            <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600 mx-auto"></div>
            <p className="mt-2 text-gray-600">Memuat bantuan...</p>
          </div>
        </div>
      </AdminSidebar>
    )
  }

  return (
    <AdminSidebar user={user}>
      <div className="max-w-7xl mx-auto">
        {/* Header */}
        <div className="mb-6">
          <h2 className="text-2xl font-bold text-gray-900">Pusat Bantuan</h2>
          <p className="text-gray-600">Dokumentasi, tutorial, dan dukungan untuk admin</p>
        </div>

        {/* Quick Actions */}
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardContent className="p-4 text-center">
              <Book className="h-8 w-8 mx-auto mb-2 text-amber-600" />
              <h3 className="font-medium">Dokumentasi</h3>
              <p className="text-sm text-gray-600">Panduan lengkap</p>
            </CardContent>
          </Card>
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardContent className="p-4 text-center">
              <Video className="h-8 w-8 mx-auto mb-2 text-green-600" />
              <h3 className="font-medium">Video Tutorial</h3>
              <p className="text-sm text-gray-600">Belajar visual</p>
            </CardContent>
          </Card>
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardContent className="p-4 text-center">
              <MessageCircle className="h-8 w-8 mx-auto mb-2 text-purple-600" />
              <h3 className="font-medium">FAQ</h3>
              <p className="text-sm text-gray-600">Pertanyaan umum</p>
            </CardContent>
          </Card>
          <Card className="hover:shadow-lg transition-shadow cursor-pointer">
            <CardContent className="p-4 text-center">
              <Phone className="h-8 w-8 mx-auto mb-2 text-red-600" />
              <h3 className="font-medium">Kontak Support</h3>
              <p className="text-sm text-gray-600">Bantuan langsung</p>
            </CardContent>
          </Card>
        </div>

        {/* Tabs */}
        <div className="flex space-x-1 mb-6 bg-gray-100 p-1 rounded-lg">
          <Button
            variant={activeTab === 'articles' ? 'default' : 'ghost'}
            onClick={() => setActiveTab('articles')}
            className="flex items-center gap-2"
          >
            <Book className="h-4 w-4" />
            Artikel & Tutorial
          </Button>
          <Button
            variant={activeTab === 'tickets' ? 'default' : 'ghost'}
            onClick={() => setActiveTab('tickets')}
            className="flex items-center gap-2"
          >
            <MessageCircle className="h-4 w-4" />
            Tiket Support
          </Button>
          <Button
            variant={activeTab === 'contact' ? 'default' : 'ghost'}
            onClick={() => setActiveTab('contact')}
            className="flex items-center gap-2"
          >
            <Phone className="h-4 w-4" />
            Kontak Darurat
          </Button>
        </div>

        {/* Search and Filters */}
        {activeTab !== 'contact' && (
          <Card className="mb-6">
            <CardContent className="p-4">
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div className="md:col-span-2">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                    <Input
                      placeholder="Cari artikel atau tiket..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                </div>
                <div>
                  <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                    <SelectTrigger>
                      <SelectValue placeholder="Kategori" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">Semua Kategori</SelectItem>
                      <SelectItem value="dashboard">Dashboard</SelectItem>
                      <SelectItem value="services">Layanan</SelectItem>
                      <SelectItem value="requests">Pengajuan</SelectItem>
                      <SelectItem value="users">Pengguna</SelectItem>
                      <SelectItem value="technical">Teknis</SelectItem>
                      <SelectItem value="reports">Laporan</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Select value={typeFilter} onValueChange={setTypeFilter}>
                    <SelectTrigger>
                      <SelectValue placeholder="Tipe" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="all">Semua Tipe</SelectItem>
                      <SelectItem value="article">Artikel</SelectItem>
                      <SelectItem value="video">Video</SelectItem>
                      <SelectItem value="faq">FAQ</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Tab Content */}
        {activeTab === 'articles' && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {articles.map((article) => (
              <Card key={article.id} className="hover:shadow-lg transition-shadow">
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-2">
                        {article.type === 'video' && <Video className="h-4 w-4 text-red-600" />}
                        {article.type === 'article' && <FileText className="h-4 w-4 text-amber-600" />}
                        {article.type === 'faq' && <HelpCircle className="h-4 w-4 text-green-600" />}
                        <Badge className={getDifficultyColor(article.difficulty)}>
                          {article.difficulty}
                        </Badge>
                      </div>
                      <CardTitle className="text-lg line-clamp-2">{article.title}</CardTitle>
                      <CardDescription className="mt-1">
                        {article.category}
                      </CardDescription>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <p className="text-sm text-gray-600 mb-4 line-clamp-3">
                    {article.content}
                  </p>
                  
                  <div className="flex items-center justify-between text-sm text-gray-500 mb-3">
                    <div className="flex items-center gap-1">
                      <Clock className="h-3 w-3" />
                      <span>{article.readTime} menit</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Star className="h-3 w-3 text-yellow-500" />
                      <span>{article.rating}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <User className="h-3 w-3" />
                      <span>{article.views}</span>
                    </div>
                  </div>

                  <div className="flex flex-wrap gap-1 mb-3">
                    {article.tags.map((tag) => (
                      <Badge key={tag} variant="outline" className="text-xs">
                        {tag}
                      </Badge>
                    ))}
                  </div>

                  <div className="text-xs text-gray-500 mb-3">
                    Diperbarui: {formatDate(article.lastUpdated)}
                  </div>

                  <Button variant="outline" size="sm" className="w-full">
                    Baca Selengkapnya
                    <ExternalLink className="h-3 w-3 ml-1" />
                  </Button>
                </CardContent>
              </Card>
            ))}
          </div>
        )}

        {activeTab === 'tickets' && (
          <div>
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-semibold">Tiket Support Saya</h3>
              <Button onClick={() => setIsTicketModalOpen(true)}>
                <MessageCircle className="h-4 w-4 mr-2" />
                Buat Tiket Baru
              </Button>
            </div>

            <div className="space-y-4">
              {tickets.map((ticket) => (
                <Card key={ticket.id} className="hover:shadow-lg transition-shadow">
                  <CardContent className="p-6">
                    <div className="flex justify-between items-start mb-3">
                      <div className="flex-1">
                        <h4 className="font-semibold text-lg mb-1">{ticket.subject}</h4>
                        <p className="text-gray-600 text-sm line-clamp-2">{ticket.description}</p>
                      </div>
                      <div className="flex flex-col gap-2 ml-4">
                        <Badge className={getPriorityColor(ticket.priority)}>
                          {ticket.priority}
                        </Badge>
                        <Badge className={getStatusColor(ticket.status)}>
                          {ticket.status.replace('_', ' ')}
                        </Badge>
                      </div>
                    </div>
                    
                    <div className="flex items-center justify-between text-sm text-gray-500">
                      <div className="flex items-center gap-4">
                        <span>Kategori: {ticket.category}</span>
                        <span>{ticket.responses} balasan</span>
                      </div>
                      <div>
                        Dibuat: {formatDate(ticket.createdAt)}
                      </div>
                    </div>

                    <div className="flex gap-2 mt-4">
                      <Button variant="outline" size="sm">
                        Lihat Detail
                      </Button>
                      {ticket.status === 'resolved' && (
                        <Button variant="outline" size="sm">
                          <CheckCircle className="h-4 w-4 mr-1" />
                          Tutup Tiket
                        </Button>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          </div>
        )}

        {activeTab === 'contact' && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Phone className="h-5 w-5" />
                  Kontak Darurat
                </CardTitle>
                <CardDescription>
                  Hubungi kami untuk bantuan mendesak
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex items-center gap-3">
                  <Phone className="h-5 w-5 text-amber-600" />
                  <div>
                    <p className="font-medium">Hotline Admin</p>
                    <p className="text-sm text-gray-600">0800-1234-5678</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <Mail className="h-5 w-5 text-green-600" />
                  <div>
                    <p className="font-medium">Email Support</p>
                    <p className="text-sm text-gray-600">admin-support@polreswonosobo.go.id</p>
                  </div>
                </div>
                <div className="flex items-center gap-3">
                  <MessageCircle className="h-5 w-5 text-purple-600" />
                  <div>
                    <p className="font-medium">Live Chat</p>
                    <p className="text-sm text-gray-600">Senin - Jumat, 08:00 - 16:00</p>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <AlertCircle className="h-5 w-5" />
                  Info Penting
                </CardTitle>
                <CardDescription>
                  Informasi yang perlu Anda ketahui
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-3">
                <div className="p-3 bg-amber-50 rounded-lg">
                  <p className="text-sm text-amber-800">
                    <strong>Backup Data:</strong> Sistem melakukan backup otomatis setiap hari pukul 02:00 WIB
                  </p>
                </div>
                <div className="p-3 bg-yellow-50 rounded-lg">
                  <p className="text-sm text-yellow-800">
                    <strong>Maintenance:</strong> Jadwal maintenance rutin setiap hari Minggu pukul 23:00 - 01:00 WIB
                  </p>
                </div>
                <div className="p-3 bg-green-50 rounded-lg">
                  <p className="text-sm text-green-800">
                    <strong>Update Sistem:</strong> Versi terbaru v2.1.0 telah tersedia
                  </p>
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* Create Ticket Modal */}
        {isTicketModalOpen && (
          <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
            <Card className="w-full max-w-2xl">
              <CardHeader>
                <CardTitle>Buat Tiket Support Baru</CardTitle>
                <CardDescription>
                  Jelaskan masalah yang Anda alami dengan detail
                </CardDescription>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleCreateTicket} className="space-y-4">
                  <div>
                    <Label htmlFor="subject">Subjek</Label>
                    <Input
                      id="subject"
                      value={ticketForm.subject}
                      onChange={(e) => setTicketForm({...ticketForm, subject: e.target.value})}
                      required
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="category">Kategori</Label>
                    <Select 
                      value={ticketForm.category} 
                      onValueChange={(value) => setTicketForm({...ticketForm, category: value})}
                      required
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih kategori" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="technical">Masalah Teknis</SelectItem>
                        <SelectItem value="account">Akun & Login</SelectItem>
                        <SelectItem value="features">Fitur & Fungsionalitas</SelectItem>
                        <SelectItem value="reports">Laporan & Data</SelectItem>
                        <SelectItem value="other">Lainnya</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="priority">Prioritas</Label>
                    <Select 
                      value={ticketForm.priority} 
                      onValueChange={(value: 'low' | 'medium' | 'high' | 'urgent') => setTicketForm({...ticketForm, priority: value})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="low">Rendah</SelectItem>
                        <SelectItem value="medium">Sedang</SelectItem>
                        <SelectItem value="high">Tinggi</SelectItem>
                        <SelectItem value="urgent">Darurat</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="description">Deskripsi Masalah</Label>
                    <Textarea
                      id="description"
                      value={ticketForm.description}
                      onChange={(e) => setTicketForm({...ticketForm, description: e.target.value})}
                      rows={5}
                      placeholder="Jelaskan masalah yang Anda alami dengan detail..."
                      required
                    />
                  </div>

                  <div className="flex gap-2 pt-4">
                    <Button type="submit" className="flex-1">
                      Kirim Tiket
                    </Button>
                    <Button 
                      type="button" 
                      variant="outline" 
                      onClick={() => setIsTicketModalOpen(false)}
                    >
                      Batal
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          </div>
        )}
      </div>
    </AdminSidebar>
  )
}