'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 { 
  FileCheck, 
  Plus, 
  Edit, 
  Trash2, 
  Search,
  Settings,
  Clock,
  CheckCircle,
  AlertCircle,
  ImageIcon,
  ExternalLink,
  GripVertical,
  ArrowUp,
  ArrowDown
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { AdminSidebar } from '@/components/admin-sidebar'
import { ImageUpload } from '@/components/ImageUpload'
import { useToast } from '@/components/ui/use-toast'
import Image from 'next/image'

interface Service {
  id: string
  title: string
  description: string
  category: string
  estimatedTime: string
  requirements: string[] | string  // Allow both array and string
  iconUrl?: string
  linkType: 'INTERNAL' | 'EXTERNAL' | 'SUBMENU'
  linkUrl?: string
  isNewTab: boolean
  status: 'ACTIVE' | 'INACTIVE'
  position: number
  parentId?: string
  children?: Service[]
  createdAt: string
  updatedAt: string
}

export default function AdminServices() {
  const router = useRouter()
  const { toast } = useToast()
  const [services, setServices] = useState<Service[]>([])
  const [loading, setLoading] = useState(true)
  const [user, setUser] = useState<any>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [categoryFilter, setCategoryFilter] = useState('all')
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
  const [editingService, setEditingService] = useState<Service | null>(null)
  const [formData, setFormData] = useState({
    title: '',
    description: '',
    category: '',
    estimatedTime: '',
    requirements: '',
    iconUrl: '',
    linkType: 'INTERNAL' as 'INTERNAL' | 'EXTERNAL' | 'SUBMENU',
    linkUrl: '',
    isNewTab: false,
    status: 'ACTIVE' as 'ACTIVE' | 'INACTIVE',
    parentId: 'none' as string,
    position: 0 as number
  })
  const [parentServices, setParentServices] = useState<Service[]>([])
  const [isReordering, setIsReordering] = useState(false)

  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
    }

    fetchServices()
  }, [router])

  const fetchServices = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const params = new URLSearchParams({
        ...(statusFilter !== 'all' && { status: statusFilter }),
        ...(categoryFilter !== 'all' && { category: categoryFilter }),
        ...(searchTerm && { search: searchTerm })
      })

      const response = await fetch(`/api/admin/services?${params}`, {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const data = await response.json()
        const allServices = data.services || []
        
        // Organize services with their children
        const organizedServices = organizeServicesWithChildren(allServices)
        setServices(organizedServices)
        
        // Filter parent services (services without parentId and with SUBMENU type)
        setParentServices(allServices.filter((s: Service) => !s.parentId && s.linkType === 'SUBMENU'))
      } else if (response.status === 401) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        router.push('/admin/login')
      }
    } catch (error) {
      console.error('Error fetching services:', error)
    } finally {
      setLoading(false)
    }
  }

  // Helper function to organize services with their children
  const organizeServicesWithChildren = (allServices: Service[]) => {
    const parentServices = allServices.filter(service => !service.parentId)
    const childServices = allServices.filter(service => service.parentId)
    
    return parentServices
      .sort((a, b) => a.position - b.position)
      .map(parent => ({
        ...parent,
        children: childServices
          .filter(child => child.parentId === parent.id)
          .sort((a, b) => a.position - b.position)
      }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    try {
      const token = localStorage.getItem('adminToken')
      if (!token) {
        toast({
          title: 'Sesi Berakhir',
          description: 'Sesi login telah berakhir. Silakan login kembali.',
          variant: 'destructive'
        })
        router.push('/admin/login')
        return
      }
      
      const url = editingService 
        ? `/api/admin/services/${editingService.id}`
        : '/api/admin/services'
      
      const method = editingService ? 'PUT' : 'POST'
      
      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          ...formData,
          requirements: formData.requirements.split('\n').filter(req => req.trim()),
          parentId: formData.parentId === 'none' ? null : formData.parentId
        })
      })

      const responseData = await response.json()

      if (response.ok) {
        fetchServices()
        setIsCreateModalOpen(false)
        setEditingService(null)
        setFormData({
          title: '',
          description: '',
          category: '',
          estimatedTime: '',
          requirements: '',
          iconUrl: '',
          linkType: 'INTERNAL',
          linkUrl: '',
          isNewTab: false,
          status: 'ACTIVE',
          parentId: 'none',
          position: 0
        })
        toast({
          title: 'Berhasil',
          description: editingService ? 'Layanan berhasil diperbarui!' : 'Layanan berhasil ditambahkan!',
          variant: 'success'
        })
      } else {
        toast({
          title: 'Gagal',
          description: responseData.error || 'Terjadi kesalahan saat menyimpan layanan',
          variant: 'destructive'
        })
      }
    } catch (error) {
      console.error('Error saving service:', error)
      toast({
        title: 'Error',
        description: 'Terjadi kesalahan saat menyimpan layanan. Silakan coba lagi.',
        variant: 'destructive'
      })
    }
  }

  // Helper function to safely parse requirements
  const parseRequirements = (requirements: any): string[] => {
    if (!requirements) return []
    if (Array.isArray(requirements)) return requirements
    if (typeof requirements === 'string') {
      try {
        return JSON.parse(requirements)
      } catch (error) {
        console.error('Error parsing requirements:', error)
        return [requirements]
      }
    }
    return []
  }

  const handleEdit = (service: Service) => {
    // Parse requirements safely - handle both array and string JSON formats
    const parsedRequirements = parseRequirements(service.requirements)

    setEditingService(service)
    setFormData({
      title: service.title,
      description: service.description,
      category: service.category,
      estimatedTime: service.estimatedTime,
      requirements: parsedRequirements.join('\n'),
      iconUrl: service.iconUrl || '',
      linkType: service.linkType,
      linkUrl: service.linkUrl || '',
      isNewTab: service.isNewTab,
      status: service.status,
      parentId: service.parentId || 'none',
      position: service.position
    })
    setIsCreateModalOpen(true)
  }

  const handleDelete = async (serviceId: string) => {
    if (!confirm('Apakah Anda yakin ingin menghapus layanan ini?')) return
    
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch(`/api/admin/services/${serviceId}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        fetchServices()
      }
    } catch (error) {
      console.error('Error deleting service:', error)
    }
  }

  // Reordering functions
  const moveService = async (serviceId: string, direction: 'up' | 'down') => {
    const serviceIndex = services.findIndex(s => s.id === serviceId)
    if (serviceIndex === -1) return

    const newServices = [...services]
    const targetIndex = direction === 'up' ? serviceIndex - 1 : serviceIndex + 1

    // Check bounds
    if (targetIndex < 0 || targetIndex >= newServices.length) return

    // Swap positions
    const temp = newServices[serviceIndex].position
    newServices[serviceIndex].position = newServices[targetIndex].position
    newServices[targetIndex].position = temp

    // Re-sort the array
    newServices.sort((a, b) => a.position - b.position)
    setServices(newServices)

    // Update in database
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/services/reorder', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          services: newServices.map(s => ({ id: s.id, position: s.position }))
        })
      })

      if (!response.ok) {
        // Revert changes if failed
        fetchServices()
        toast({
          title: 'Gagal',
          description: 'Gagal memperbarui urutan layanan',
          variant: 'destructive'
        })
      }
    } catch (error) {
      console.error('Error reordering services:', error)
      fetchServices()
      toast({
        title: 'Error',
        description: 'Terjadi kesalahan saat memperbarui urutan',
        variant: 'destructive'
      })
    }
  }

  const saveReorder = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/services/reorder', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          services: services.map(s => ({ id: s.id, position: s.position }))
        })
      })

      if (response.ok) {
        setIsReordering(false)
        toast({
          title: 'Berhasil',
          description: 'Urutan layanan berhasil disimpan!',
          variant: 'success'
        })
      } else {
        toast({
          title: 'Gagal',
          description: 'Gagal menyimpan urutan layanan',
          variant: 'destructive'
        })
      }
    } catch (error) {
      console.error('Error saving reorder:', error)
      toast({
        title: 'Error',
        description: 'Terjadi kesalahan saat menyimpan urutan',
        variant: 'destructive'
      })
    }
  }

  const getStatusColor = (status: string) => {
    return status === 'ACTIVE' 
      ? 'bg-green-100 text-green-800' 
      : 'bg-red-100 text-red-800'
  }

  const getStatusLabel = (status: string) => {
    return status === 'ACTIVE' ? 'Aktif' : 'Tidak Aktif'
  }

  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 data layanan...</p>
          </div>
        </div>
      </AdminSidebar>
    )
  }

  return (
    <AdminSidebar user={user}>
      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Kelola Layanan</h2>
          <p className="text-gray-600">Kelola semua layanan yang tersedia untuk pengguna</p>
        </div>
        <div className="flex gap-2">
          {isReordering ? (
            <>
              <Button 
                onClick={saveReorder}
                className="bg-green-600 hover:bg-green-700"
              >
                <CheckCircle className="h-4 w-4 mr-2" />
                Simpan Urutan
              </Button>
              <Button 
                onClick={() => {
                  setIsReordering(false)
                  fetchServices()
                }}
                variant="outline"
              >
                Batal
              </Button>
            </>
          ) : (
            <>
              <Button 
                onClick={() => setIsReordering(true)}
                variant="outline"
              >
                <GripVertical className="h-4 w-4 mr-2" />
                Urutkan
              </Button>
              <Button 
                onClick={() => setIsCreateModalOpen(true)}
                className="bg-amber-600 hover:bg-amber-700"
              >
                <Plus className="h-4 w-4 mr-2" />
                Tambah Layanan
              </Button>
            </>
          )}
        </div>
      </div>

        {/* Filters */}
        <Card className="mb-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-2">
              <Search className="h-5 w-5" />
              Filter dan Pencarian
            </CardTitle>
          </CardHeader>
          <CardContent>
            <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 nama layanan..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="pl-10"
                  />
                </div>
              </div>
              <div>
                <Select value={statusFilter} onValueChange={setStatusFilter}>
                  <SelectTrigger>
                    <SelectValue placeholder="Filter Status" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Semua Status</SelectItem>
                    <SelectItem value="ACTIVE">Aktif</SelectItem>
                    <SelectItem value="INACTIVE">Tidak Aktif</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Select value={categoryFilter} onValueChange={setCategoryFilter}>
                  <SelectTrigger>
                    <SelectValue placeholder="Filter Kategori" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">Semua Kategori</SelectItem>
                    <SelectItem value="skck">SKCK</SelectItem>
                    <SelectItem value="spkt">SPKT</SelectItem>
                    <SelectItem value="lalu-lintas">Lalu Lintas</SelectItem>
                    <SelectItem value="lainnya">Lainnya</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Services Grid */}
        <div className="space-y-6">
          {services.map((service) => (
            <Card key={service.id} className={`hover:shadow-lg transition-shadow ${isReordering ? 'border-amber-300 bg-amber-50' : ''}`}>
              <CardHeader>
                <div className="flex justify-between items-start">
                  <div className="flex items-start gap-3 flex-1">
                    {/* Drag Handle or Service Icon */}
                    <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0">
                      {isReordering ? (
                        <GripVertical className="w-6 h-6 text-gray-400" />
                      ) : (
                        <>
                          {service.iconUrl && (service.iconUrl.startsWith('/') || service.iconUrl.startsWith('http')) ? (
                            <Image 
                              src={service.iconUrl} 
                              alt={service.title}
                              width={48}
                              height={48}
                              className="w-12 h-12 object-contain rounded-lg"
                              onError={(e) => {
                                // Fallback to default icon if image fails to load
                                const target = e.target as HTMLImageElement;
                                target.style.display = 'none';
                                const parent = target.parentElement;
                                if (parent) {
                                          parent.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="w-6 h-6 text-gray-400"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>';
                                        }
                                      }}
                                    />
                                  ) : (
                                    <ImageIcon className="w-6 h-6 text-gray-400" />
                                  )}
                                </>
                              )}
                            </div>
                    <div className="flex-1">
                      <div className="flex items-center gap-2 mb-1">
                        <CardTitle className="text-lg">{service.title}</CardTitle>
                        {service.linkType === 'SUBMENU' && (
                          <Badge variant="secondary" className="text-xs">
                            Menu Utama
                          </Badge>
                        )}
                      </div>
                      <CardDescription>
                        {service.category}
                      </CardDescription>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <Badge className={getStatusColor(service.status)}>
                      {getStatusLabel(service.status)}
                    </Badge>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <p className="text-sm text-gray-600 mb-4">
                  {service.description}
                </p>
                
                <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-4">
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <Clock className="h-4 w-4" />
                    <span>Estimasi: {service.estimatedTime}</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    <FileCheck className="h-4 w-4" />
                    <span>{parseRequirements(service.requirements).length} persyaratan</span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-gray-600">
                    {service.linkType === 'EXTERNAL' ? (
                      <>
                        <ExternalLink className="h-4 w-4" />
                        <span>Link Eksternal {service.isNewTab && '(New Tab)'}</span>
                      </>
                    ) : service.linkType === 'SUBMENU' ? (
                      <>
                        <Settings className="h-4 w-4" />
                        <span>
                          {service.parentId 
                            ? `Submenu dengan ${service.children?.length || 0} anak`
                            : `Menu Induk dengan ${service.children?.length || 0} submenu`
                          }
                          {service.linkUrl && ' + Link Action'}
                        </span>
                      </>
                    ) : (
                      <>
                        <Settings className="h-4 w-4" />
                        <span>
                          {service.parentId ? 'Submenu Internal' : 'Halaman Internal'}
                          {service.linkUrl && ` → ${service.linkUrl}`}
                        </span>
                      </>
                    )}
                  </div>
                </div>

                {service.linkUrl && (
                  <div className="text-xs text-gray-500 mb-4">
                    <strong>Link:</strong> {service.linkUrl.length > 50 ? service.linkUrl.substring(0, 50) + '...' : service.linkUrl}
                  </div>
                )}

                {/* Integrated Submenu Display */}
                {service.linkType === 'SUBMENU' && service.children && service.children.length > 0 && (
                  <div className="mt-4 p-4 bg-gray-50 rounded-lg border border-gray-200">
                    <div className="flex items-center justify-between mb-3">
                      <h4 className="text-sm font-semibold text-gray-700 flex items-center gap-2">
                        <Settings className="h-4 w-4" />
                        Submenu Items ({service.children.length})
                      </h4>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => {
                          setFormData({
                            title: '',
                            description: '',
                            category: service.category,
                            estimatedTime: '',
                            requirements: '',
                            iconUrl: '',
                            linkType: 'INTERNAL',
                            linkUrl: '',
                            isNewTab: false,
                            status: 'ACTIVE',
                            parentId: service.id
                          })
                          setEditingService(null)
                          setIsCreateModalOpen(true)
                        }}
                      >
                        <Plus className="h-3 w-3 mr-1" />
                        Tambah Submenu
                      </Button>
                    </div>
                    <div className="space-y-2">
                      {service.children.map((child) => (
                        <div key={child.id} className="flex items-center justify-between p-3 bg-white rounded-lg border border-gray-100 hover:border-gray-300 transition-colors">
                          <div className="flex items-center gap-3 flex-1">
                            <div className="w-8 h-8 bg-gray-100 rounded flex items-center justify-center">
                              {child.linkType === 'EXTERNAL' ? (
                                <ExternalLink className="h-4 w-4 text-blue-500" />
                              ) : child.linkType === 'SUBMENU' ? (
                                <Settings className="h-4 w-4 text-purple-500" />
                              ) : (
                                <FileCheck className="h-4 w-4 text-green-500" />
                              )}
                            </div>
                            <div className="flex-1">
                              <div className="flex items-center gap-2">
                                <span className="font-medium text-sm">{child.title}</span>
                                <Badge variant="outline" className="text-xs">
                                  {child.linkType === 'EXTERNAL' ? 'Eksternal' : 
                                   child.linkType === 'SUBMENU' ? 'Submenu' : 'Internal'}
                                </Badge>
                                {child.linkUrl && child.linkType === 'SUBMENU' && (
                                  <Badge variant="secondary" className="text-xs">
                                    + Action
                                  </Badge>
                                )}
                                <Badge className={`${getStatusColor(child.status)} text-xs`}>
                                  {getStatusLabel(child.status)}
                                </Badge>
                              </div>
                              {child.description && (
                                <p className="text-xs text-gray-500 mt-1">{child.description}</p>
                              )}
                              {child.linkUrl && (
                                <p className="text-xs text-gray-400 mt-1">
                                  {child.linkUrl.length > 40 ? child.linkUrl.substring(0, 40) + '...' : child.linkUrl}
                                </p>
                              )}
                            </div>
                          </div>
                          <div className="flex items-center gap-1">
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleEdit(child)}
                              className="h-8 w-8 p-0"
                            >
                              <Edit className="h-3 w-3" />
                            </Button>
                            <Button
                              variant="ghost"
                              size="sm"
                              onClick={() => handleDelete(child.id)}
                              className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:bg-red-50"
                            >
                              <Trash2 className="h-3 w-3" />
                            </Button>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                <div className="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
                  <div className="text-xs text-gray-500">
                    {isReordering ? `Posisi: ${service.position + 1}` : `Diperbarui: ${formatDate(service.updatedAt)}`}
                  </div>
                  <div className="flex gap-2">
                    {isReordering ? (
                      <>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => moveService(service.id, 'up')}
                          disabled={service.position === 0}
                          className="h-8 w-8 p-0"
                        >
                          <ArrowUp className="h-3 w-3" />
                        </Button>
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => moveService(service.id, 'down')}
                          disabled={service.position === services.length - 1}
                          className="h-8 w-8 p-0"
                        >
                          <ArrowDown className="h-3 w-3" />
                        </Button>
                      </>
                    ) : (
                      <>
                        {service.linkType === 'SUBMENU' && (
                          <Button 
                            variant="outline" 
                            size="sm" 
                            onClick={() => {
                              setFormData({
                                title: '',
                                description: '',
                                category: service.category,
                                estimatedTime: '',
                                requirements: '',
                                iconUrl: '',
                                linkType: 'INTERNAL',
                                linkUrl: '',
                                isNewTab: false,
                                status: 'ACTIVE',
                                parentId: service.id,
                                position: 0
                              })
                              setEditingService(null)
                              setIsCreateModalOpen(true)
                            }}
                          >
                        <Plus className="h-4 w-4 mr-1" />
                        Tambah Submenu
                      </Button>
                    )}
                    <Button 
                      variant="outline" 
                      size="sm" 
                      onClick={() => handleEdit(service)}
                    >
                      <Edit className="h-4 w-4 mr-1" />
                      Edit
                    </Button>
                    <Button 
                      variant="outline" 
                      size="sm" 
                      onClick={() => handleDelete(service.id)}
                      className="text-red-600 hover:text-red-700 hover:bg-red-50"
                    >
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {services.length === 0 && (
          <Card>
            <CardContent className="text-center py-12">
              <FileCheck className="h-12 w-12 mx-auto mb-4 text-gray-400" />
              <p className="text-gray-500">Belum ada layanan tersedia</p>
              <Button 
                onClick={() => setIsCreateModalOpen(true)}
                className="mt-4"
              >
                <Plus className="h-4 w-4 mr-2" />
                Tambah Layanan Pertama
              </Button>
            </CardContent>
          </Card>
        )}

        {/* Create/Edit Modal */}
        {isCreateModalOpen && (
          <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 max-h-[90vh] overflow-y-auto">
              <CardHeader>
                <CardTitle>
                  {editingService ? 'Edit Layanan' : 'Tambah Layanan Baru'}
                </CardTitle>
                <CardDescription>
                  {editingService 
                    ? 'Perbarui informasi layanan yang ada' 
                    : 'Tambahkan layanan baru untuk pengguna'
                  }
                </CardDescription>
              </CardHeader>
              <CardContent>
                <form onSubmit={handleSubmit} className="space-y-4">
                  <div>
                    <Label htmlFor="title">Nama Layanan</Label>
                    <Input
                      id="title"
                      value={formData.title}
                      onChange={(e) => setFormData({...formData, title: e.target.value})}
                      required
                    />
                  </div>
                  
                  <div>
                    <Label htmlFor="category">Kategori</Label>
                    <Select 
                      value={formData.category} 
                      onValueChange={(value) => setFormData({...formData, category: value})}
                      required
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih kategori" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="skck">SKCK</SelectItem>
                        <SelectItem value="spkt">SPKT</SelectItem>
                        <SelectItem value="lalu-lintas">Lalu Lintas</SelectItem>
                        <SelectItem value="lainnya">Lainnya</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div>
                    <Label htmlFor="description">Deskripsi</Label>
                    <Textarea
                      id="description"
                      value={formData.description}
                      onChange={(e) => setFormData({...formData, description: e.target.value})}
                      rows={3}
                      required
                    />
                  </div>

                  <div>
                    <Label htmlFor="estimatedTime">Estimasi Waktu Pengerjaan</Label>
                    <Input
                      id="estimatedTime"
                      value={formData.estimatedTime}
                      onChange={(e) => setFormData({...formData, estimatedTime: e.target.value})}
                      placeholder="contoh: 3-5 hari kerja"
                      required
                    />
                  </div>

                  <div>
                    <Label htmlFor="position">Posisi Urutan</Label>
                    <Input
                      id="position"
                      type="number"
                      min="0"
                      value={formData.position}
                      onChange={(e) => setFormData({...formData, position: parseInt(e.target.value) || 0})}
                      placeholder="0 untuk posisi otomatis"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      Nomor urutan untuk mengatur posisi layanan. Kosongkan untuk posisi otomatis.
                    </p>
                  </div>

                  <div>
                    <Label>Icon Layanan</Label>
                    <ImageUpload
                      value={formData.iconUrl}
                      onChange={(url) => setFormData({...formData, iconUrl: url})}
                      type="icon"
                      maxSize={10}
                      previewSize="small"
                    />
                    <p className="text-xs text-gray-500 mt-1">
                      Upload icon untuk layanan. Format: JPEG, PNG, GIF, WebP (max 10MB, tidak dikompresi)
                    </p>
                  </div>

                  <div>
                    <Label htmlFor="linkType">Tipe Link</Label>
                    <Select 
                      value={formData.linkType} 
                      onValueChange={(value: 'INTERNAL' | 'EXTERNAL' | 'SUBMENU') => setFormData({...formData, linkType: value})}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih tipe link" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="INTERNAL">Halaman Internal</SelectItem>
                        <SelectItem value="EXTERNAL">Link Eksternal</SelectItem>
                        <SelectItem value="SUBMENU">Menu dengan Submenu</SelectItem>
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-gray-500 mt-1">
                      {formData.linkType === 'SUBMENU' 
                        ? 'Menu induk yang akan menampilkan submenu-item di bawahnya'
                        : 'Menu langsung dengan link action'
                      }
                    </p>
                  </div>

                  <div>
                    <Label htmlFor="parentId">Induk Menu (jika submenu)</Label>
                    <Select 
                      value={formData.parentId} 
                      onValueChange={(value) => setFormData({...formData, parentId: value})}
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih induk menu (kosongkan untuk menu utama)" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="none">Tidak ada (Menu Utama)</SelectItem>
                        {parentServices.filter(ps => ps.id !== editingService?.id).map((parent) => (
                          <SelectItem key={parent.id} value={parent.id}>
                            {parent.title}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                    <p className="text-xs text-gray-500 mt-1">
                      {formData.parentId && formData.parentId !== 'none'
                        ? 'Ini akan menjadi submenu dari menu induk yang dipilih'
                        : 'Ini akan menjadi menu utama (level tertinggi)'
                      }
                    </p>
                  </div>

                  {formData.linkType === 'EXTERNAL' ? (
                    <>
                      <div>
                        <Label htmlFor="linkUrl">URL Link</Label>
                        <Input
                          id="linkUrl"
                          value={formData.linkUrl}
                          onChange={(e) => setFormData({...formData, linkUrl: e.target.value})}
                          placeholder="https://contoh.com atau tel:110 atau mailto:info@example.com"
                          type="url"
                        />
                        <p className="text-xs text-gray-500 mt-1">
                          Support: https://, http://, tel:, mailto:, sms:, whatsapp:, dll.
                        </p>
                      </div>

                      <div className="flex items-center space-x-2">
                        <input
                          type="checkbox"
                          id="isNewTab"
                          checked={formData.isNewTab}
                          onChange={(e) => setFormData({...formData, isNewTab: e.target.checked})}
                          className="rounded border-gray-300 text-amber-600 focus:ring-amber-500"
                        />
                        <Label htmlFor="isNewTab" className="text-sm">
                          Buka di tab baru
                        </Label>
                      </div>
                    </>
                  ) : formData.linkType === 'INTERNAL' ? (
                    <div>
                      <Label htmlFor="linkUrl">Path Halaman</Label>
                      <Input
                        id="linkUrl"
                        value={formData.linkUrl}
                        onChange={(e) => setFormData({...formData, linkUrl: e.target.value})}
                        placeholder="/ajuan/nama-layanan"
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        Kosongkan untuk menggunakan path default: /ajuan/[slug]
                      </p>
                    </div>
                  ) : formData.linkType === 'SUBMENU' && (
                    <div>
                      <Label htmlFor="linkUrl">Link Opsional (untuk submenu dengan action)</Label>
                      <Input
                        id="linkUrl"
                        value={formData.linkUrl}
                        onChange={(e) => setFormData({...formData, linkUrl: e.target.value})}
                        placeholder={formData.parentId && formData.parentId !== 'none' 
                          ? "/ajuan/submenu-path, https://link.com, tel:110, atau mailto:info@example.com" 
                          : "Kosongkan jika hanya menu induk tanpa action"
                        }
                      />
                      <p className="text-xs text-gray-500 mt-1">
                        {formData.parentId && formData.parentId !== 'none'
                          ? 'Submenu bisa memiliki link action (internal/eksternal/tel/mailto) atau kosongkan jika hanya grouping'
                          : 'Menu induk biasanya kosong, tapi bisa memiliki link action jika diperlukan'
                        }
                      </p>
                      
                      {formData.linkUrl && /^https?:|^ftp:|^mailto:/.test(formData.linkUrl) && (
                        <div className="flex items-center space-x-2 mt-2">
                          <input
                            type="checkbox"
                            id="isNewTab"
                            checked={formData.isNewTab}
                            onChange={(e) => setFormData({...formData, isNewTab: e.target.checked})}
                            className="rounded border-gray-300 text-amber-600 focus:ring-amber-500"
                          />
                          <Label htmlFor="isNewTab" className="text-sm">
                            Buka di tab baru (untuk link eksternal)
                          </Label>
                        </div>
                      )}
                    </div>
                  )}

                  <div>
                    <Label htmlFor="requirements">Persyaratan (satu per baris)</Label>
                    <Textarea
                      id="requirements"
                      value={formData.requirements}
                      onChange={(e) => setFormData({...formData, requirements: e.target.value})}
                      rows={5}
                      placeholder="Masukkan setiap persyaratan pada baris baru"
                      required
                    />
                  </div>

                  <div>
                    <Label htmlFor="status">Status</Label>
                    <Select 
                      value={formData.status} 
                      onValueChange={(value: 'ACTIVE' | 'INACTIVE') => setFormData({...formData, status: value})}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="ACTIVE">Aktif</SelectItem>
                        <SelectItem value="INACTIVE">Tidak Aktif</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="flex gap-2 pt-4">
                    <Button type="submit" className="flex-1">
                      {editingService ? 'Perbarui' : 'Simpan'}
                    </Button>
                    <Button 
                      type="button" 
                      variant="outline" 
                      onClick={() => {
                        setIsCreateModalOpen(false)
                        setEditingService(null)
                        setFormData({
                          title: '',
                          description: '',
                          category: '',
                          estimatedTime: '',
                          requirements: '',
                          iconUrl: '',
                          linkType: 'INTERNAL',
                          linkUrl: '',
                          isNewTab: false,
                          status: 'ACTIVE',
                          parentId: 'none'
                        })
                      }}
                    >
                      Batal
                    </Button>
                  </div>
                </form>
              </CardContent>
            </Card>
          </div>
        )}
    </AdminSidebar>
  )
}