'use client'

import { useEffect, useState } from 'react'
import dynamic from 'next/dynamic'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { 
  ArrowLeft, 
  Save, 
  FileText,
  Code,
  Eye,
  EyeOff,
  Loader2
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { AdminSidebar } from '@/components/admin-sidebar'
import { EnhancedMDXEditor } from '@/components/EnhancedMDXEditor'

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

export default function CreateTemplatePage() {
  const router = useRouter()
  
  const [services, setServices] = useState<Service[]>([])
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [user, setUser] = useState<any>(null)
  const [message, setMessage] = useState('')
  const [previewMode, setPreviewMode] = useState(false)
  const [formData, setFormData] = useState({
    serviceId: '',
    templateContent: ''
  })

  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 response = await fetch('/api/admin/services', {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      })

      if (response.ok) {
        const data = await response.json()
        setServices(data.services || [])
      } else if (response.status === 401) {
        localStorage.removeItem('adminToken')
        localStorage.removeItem('adminUser')
        router.push('/admin/login')
      }
    } catch (error) {
      console.error('Error fetching services:', error)
      setMessage('Terjadi kesalahan saat memuat layanan')
    } finally {
      setLoading(false)
    }
  }

  const handleSave = async () => {
    if (!formData.serviceId || !formData.templateContent.trim()) {
      setMessage('Semua field harus diisi')
      return
    }

    setSaving(true)
    setMessage('')

    try {
      const token = localStorage.getItem('adminToken')
      const response = await fetch('/api/admin/templates', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify(formData)
      })

      if (response.ok) {
        setMessage('Template berhasil ditambahkan')
        setTimeout(() => {
          router.push('/admin/templates')
        }, 1500)
      } else {
        const data = await response.json()
        setMessage(data.error || 'Terjadi kesalahan')
      }
    } catch (error) {
      console.error('Error saving template:', error)
      setMessage('Terjadi kesalahan jaringan')
    } finally {
      setSaving(false)
    }
  }

  const renderPreview = () => {
    if (!formData.templateContent) return null
    
    const selectedService = services.find(s => s.id === formData.serviceId)
    
    // Simple preview - replace variables with sample data
    const processedContent = formData.templateContent
      .replace(/\{\{trackingNumber\}\}/g, 'SRV-2024-001234')
      .replace(/\{\{serviceName\}\}/g, selectedService?.title || 'Nama Layanan')
      .replace(/\{\{userName\}\}/g, 'John Doe')
      .replace(/\{\{userEmail\}\}/g, 'john.doe@example.com')
      .replace(/\{\{fullName\}\}/g, 'John Doe')
      .replace(/\{\{placeOfBirth\}\}/g, 'Jakarta')
      .replace(/\{\{dateOfBirth\}\}/g, '01 Januari 1990')
      .replace(/\{\{gender\}\}/g, 'Laki-laki')
      .replace(/\{\{religion\}\}/g, 'Islam')
      .replace(/\{\{occupation\}\}/g, 'Pegawai Swasta')
      .replace(/\{\{address\}\}/g, 'Jl. Contoh No. 123, Jakarta')
      .replace(/\{\{phone\}\}/g, '08123456789')
      .replace(/\{\{identityNumber\}\}/g, '3275010112900001')
      .replace(/\{\{purpose\}\}/g, 'Untuk keperluan melamar pekerjaan')
      .replace(/\{\{status\}\}/g, 'Selesai')
      .replace(/\{\{createdAt\}\}/g, new Date().toLocaleString('id-ID'))
    
    return processedContent
  }

  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...</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 className="flex items-center gap-4">
          <Button 
            variant="outline" 
            onClick={() => router.push('/admin/templates')}
          >
            <ArrowLeft className="h-4 w-4 mr-2" />
            Kembali
          </Button>
          <div>
            <h2 className="text-2xl font-bold text-gray-900">Template Baru</h2>
            <p className="text-gray-600">Buat template PDF untuk layanan</p>
          </div>
        </div>
        <div className="flex gap-2">
          <Button 
            variant="outline"
            onClick={() => setPreviewMode(!previewMode)}
            disabled={!formData.serviceId}
          >
            {previewMode ? (
              <>
                <EyeOff className="h-4 w-4 mr-2" />
                Edit Mode
              </>
            ) : (
              <>
                <Eye className="h-4 w-4 mr-2" />
                Preview
              </>
            )}
          </Button>
          <Button 
            onClick={handleSave}
            disabled={saving}
            className="bg-amber-600 hover:bg-amber-700"
          >
            {saving ? (
              <>
                <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                Menyimpan...
              </>
            ) : (
              <>
                <Save className="h-4 w-4 mr-2" />
                Simpan
              </>
            )}
          </Button>
        </div>
      </div>

      {/* Form */}
      <Card className="mb-6">
        <CardHeader>
          <CardTitle>Informasi Template</CardTitle>
          <CardDescription>Pilih layanan untuk template ini</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="serviceId">Layanan</Label>
              <Select 
                value={formData.serviceId} 
                onValueChange={(value) => setFormData({...formData, serviceId: value})}
                required
              >
                <SelectTrigger>
                  <SelectValue placeholder="Pilih layanan" />
                </SelectTrigger>
                <SelectContent>
                  {services.map((service) => (
                    <SelectItem key={service.id} value={service.id}>
                      {service.title}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Editor */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Code className="h-5 w-5" />
            {previewMode ? 'Preview Template' : 'Editor Template'}
          </CardTitle>
          <CardDescription>
            {previewMode 
              ? 'Preview template dengan data sample' 
              : 'Edit konten template menggunakan Markdown. Gunakan variabel seperti {{nama}}, {{trackingNumber}}, dll.'
            }
          </CardDescription>
        </CardHeader>
        <CardContent>
          {previewMode ? (
            <div className="min-h-[400px] p-6 bg-gray-50 rounded border">
              <div className="prose max-w-none">
                <pre className="whitespace-pre-wrap font-sans text-sm">
                  {renderPreview()}
                </pre>
              </div>
            </div>
          ) : (
            <div>
              <div className="mb-4">
                <Label htmlFor="templateContent">Konten Template</Label>
                <p className="text-xs text-gray-500 mt-1">
                  Variabel yang tersedia: {"{{trackingNumber}}"}, {"{{serviceName}}"}, {"{{userName}}"}, {"{{userEmail}}"}, {"{{fullName}}"}, {"{{placeOfBirth}}"}, {"{{dateOfBirth}}"}, {"{{gender}}"}, {"{{religion}}"}, {"{{occupation}}"}, {"{{address}}"}, {"{{phone}}"}, {"{{identityNumber}}"}, {"{{purpose}}"}, {"{{status}}"}, {"{{createdAt}}"}
                </p>
              </div>
              <div className="min-h-[500px]">
                <EnhancedMDXEditor
                  value={formData.templateContent}
                  onChange={(value) => setFormData({...formData, templateContent: value})}
                  height={500}
                  placeholder="Mulai mengetik konten template di sini..."
                />
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </AdminSidebar>
  )
}