'use client'

import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
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 { Label } from '@/components/ui/label'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { 
  FileText, 
  Plus, 
  Edit, 
  Trash2, 
  Search,
  Settings,
  Eye,
  Download,
  Code,
  Layout,
  Save
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { AdminSidebar } from '@/components/admin-sidebar'

// Dynamically import the markdown editor to avoid SSR issues
const MDEditor = dynamic(
  () => import('@uiw/react-md-editor').then((mod) => mod.default),
  { ssr: false }
)

interface Service {
  id: string
  title: string
  slug: string
  category: string
}

interface Template {
  id: string
  serviceId: string
  service: Service
  templateContent: string
  createdAt: string
  updatedAt: string
}

export default function AdminTemplates() {
  const router = useRouter()
  const [templates, setTemplates] = useState<Template[]>([])
  const [services, setServices] = useState<Service[]>([])
  const [loading, setLoading] = useState(true)
  const [user, setUser] = useState<any>(null)
  const [searchTerm, setSearchTerm] = useState('')
  const [serviceFilter, setServiceFilter] = useState('all')
  const [message, setMessage] = useState('')

  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()
    fetchTemplates()
  }, [router])

  const fetchServices = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/services', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const data = await response.json()
        setServices(data.services || [])
      }
    } catch (error) {
      console.error('Error fetching services:', error)
    }
  }

  const fetchTemplates = async () => {
    try {
      const token = localStorage.getItem('adminToken')
      const params = new URLSearchParams({
        ...(serviceFilter !== 'all' && { serviceId: serviceFilter }),
        ...(searchTerm && { search: searchTerm })
      })

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

      if (response.ok) {
        const data = await response.json()
        setTemplates(data.templates || [])
      } else if (response.status === 401) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        router.push('/admin/login')
      }
    } catch (error) {
      console.error('Error fetching templates:', error)
    } finally {
      setLoading(false)
    }
  }

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

      if (response.ok) {
        setMessage('Template berhasil dihapus')
        fetchTemplates()
        setTimeout(() => setMessage(''), 3000)
      } else {
        const data = await response.json()
        setMessage(data.error || 'Gagal menghapus template')
      }
    } catch (error) {
      console.error('Error deleting template:', error)
      setMessage('Terjadi kesalahan jaringan')
    }
  }

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

  const renderPreview = (content: string) => {
    // Simple preview - replace variables with sample data and limit length
    const processedContent = content
      .replace(/\{\{[^}]+\}\}/g, '[VARIABLE]')
      .substring(0, 200)
    
    return processedContent + (content.length > 200 ? '...' : '')
  }

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

  return (
    <AdminSidebar user={user}>
      {/* Alert Messages */}
      {message && (
        <Alert>
          <AlertDescription>{message}</AlertDescription>
        </Alert>
      )}

      {/* Header */}
      <div className="flex justify-between items-center mb-6">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Kelola Template</h2>
          <p className="text-gray-600">Kelola template PDF untuk setiap jenis layanan</p>
        </div>
        <Button 
          onClick={() => router.push('/admin/templates/create')}
          className="bg-amber-600 hover:bg-amber-700"
        >
          <Plus className="h-4 w-4 mr-2" />
          Tambah Template
        </Button>
      </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-2 gap-4">
            <div>
              <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 template..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <div>
              <Select value={serviceFilter} onValueChange={setServiceFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="Filter Layanan" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">Semua Layanan</SelectItem>
                  {services.map((service) => (
                    <SelectItem key={service.id} value={service.id}>
                      {service.title}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Templates Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {templates.map((template) => (
          <Card key={template.id} className="hover:shadow-lg transition-shadow">
            <CardHeader>
              <div className="flex justify-between items-start">
                <div className="flex-1">
                  <CardTitle className="text-lg flex items-center gap-2">
                    <Layout className="h-5 w-5" />
                    {template.service.title}
                  </CardTitle>
                  <CardDescription className="mt-1">
                    {template.service.category}
                  </CardDescription>
                </div>
                <Badge variant="outline">
                  <Code className="h-3 w-3 mr-1" />
                  Template
                </Badge>
              </div>
            </CardHeader>
            <CardContent>
              <div className="mb-4">
                <div className="text-sm text-gray-600 mb-2">Preview:</div>
                <div className="p-3 bg-gray-50 rounded border text-sm max-h-32 overflow-y-auto">
                  <pre className="whitespace-pre-wrap font-sans text-xs">
                    {renderPreview(template.templateContent)}
                  </pre>
                </div>
              </div>
              
              <div className="text-xs text-gray-500 mb-4">
                Diperbarui: {formatDate(template.updatedAt)}
              </div>

              <div className="flex gap-2">
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => router.push(`/admin/templates/${template.id}`)}
                  className="flex-1"
                >
                  <Edit className="h-4 w-4 mr-1" />
                  Edit
                </Button>
                <Button 
                  variant="outline" 
                  size="sm" 
                  onClick={() => handleDelete(template.id)}
                  className="text-red-600 hover:text-red-700 hover:bg-red-50"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {templates.length === 0 && (
        <Card>
          <CardContent className="text-center py-12">
            <FileText className="h-12 w-12 mx-auto mb-4 text-gray-400" />
            <p className="text-gray-500">Belum ada template tersedia</p>
            <Button 
              onClick={() => router.push('/admin/templates/create')}
              className="mt-4"
            >
              <Plus className="h-4 w-4 mr-2" />
              Tambah Template Pertama
            </Button>
          </CardContent>
        </Card>
      )}
    </AdminSidebar>
  )
}