'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'
import { 
  Plus, 
  Edit, 
  Trash2, 
  Eye, 
  EyeOff, 
  Star, 
  StarOff,
  ExternalLink,
  Settings,
  RefreshCw
} from 'lucide-react'
import { toast } from 'sonner'
import { AdminSidebar } from '@/components/admin-sidebar'
import { useAdminAuth } from '@/hooks/useAdminAuth'

interface LandingPage {
  id: string
  name: string
  slug: string
  title: string
  description?: string
  type: 'CLASSIC' | 'MODERN' | 'MINIMAL' | 'CORPORATE'
  path: string
  isActive: boolean
  isDefault: boolean
  settings?: any
  metadata?: any
  createdAt: string
  updatedAt: string
}

export default function LandingPagesManagement() {
  const router = useRouter()
  const { user, loading, isAuthenticated, logout, getAuthHeaders } = useAdminAuth()
  const [landingPages, setLandingPages] = useState<LandingPage[]>([])
  const [dataLoading, setDataLoading] = useState(true)
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
  const [editingPage, setEditingPage] = useState<LandingPage | null>(null)
  const [formData, setFormData] = useState({
    name: '',
    slug: '',
    title: '',
    description: '',
    type: 'CLASSIC' as const,
    path: '',
    isActive: false,
    isDefault: false,
    settings: '',
    metadata: ''
  })

  useEffect(() => {
    if (!loading && !isAuthenticated) {
      router.push('/admin/login')
      return
    }

    if (isAuthenticated) {
      fetchLandingPages()
    }
  }, [loading, isAuthenticated, router])

  const fetchLandingPages = async () => {
    try {
      setDataLoading(true)
      const response = await fetch('/api/landing-pages')
      const result = await response.json()
      
      if (result.success) {
        setLandingPages(result.data)
      } else {
        toast.error('Failed to fetch landing pages')
      }
    } catch (error) {
      console.error('Error fetching landing pages:', error)
      toast.error('Error fetching landing pages')
    } finally {
      setDataLoading(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    try {
      const payload = {
        ...formData,
        settings: formData.settings ? JSON.parse(formData.settings) : null,
        metadata: formData.metadata ? JSON.parse(formData.metadata) : null
      }

      const url = editingPage ? `/api/landing-pages/${editingPage.id}` : '/api/landing-pages'
      const method = editingPage ? 'PUT' : 'POST'

      const response = await fetch(url, {
        method,
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(payload),
      })

      const result = await response.json()

      if (result.success) {
        toast.success(editingPage ? 'Landing page updated successfully' : 'Landing page created successfully')
        setIsCreateDialogOpen(false)
        setIsEditDialogOpen(false)
        setEditingPage(null)
        resetForm()
        fetchLandingPages()
      } else {
        toast.error(result.error || 'Failed to save landing page')
      }
    } catch (error) {
      console.error('Error saving landing page:', error)
      toast.error('Error saving landing page')
    }
  }

  const handleEdit = (page: LandingPage) => {
    setEditingPage(page)
    setFormData({
      name: page.name,
      slug: page.slug,
      title: page.title,
      description: page.description || '',
      type: page.type,
      path: page.path,
      isActive: page.isActive,
      isDefault: page.isDefault,
      settings: page.settings ? JSON.stringify(page.settings, null, 2) : '',
      metadata: page.metadata ? JSON.stringify(page.metadata, null, 2) : ''
    })
    setIsEditDialogOpen(true)
  }

  const handleDelete = async (id: string) => {
    try {
      const response = await fetch(`/api/landing-pages/${id}`, {
        method: 'DELETE',
      })

      const result = await response.json()

      if (result.success) {
        toast.success('Landing page deleted successfully')
        fetchLandingPages()
      } else {
        toast.error(result.error || 'Failed to delete landing page')
      }
    } catch (error) {
      console.error('Error deleting landing page:', error)
      toast.error('Error deleting landing page')
    }
  }

  const handleToggleActive = async (id: string, isActive: boolean) => {
    try {
      const response = await fetch(`/api/landing-pages/${id}/toggle`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ isActive }),
      })

      const result = await response.json()

      if (result.success) {
        toast.success(`Landing page ${isActive ? 'activated' : 'deactivated'} successfully`)
        fetchLandingPages()
      } else {
        toast.error(result.error || 'Failed to toggle landing page')
      }
    } catch (error) {
      console.error('Error toggling landing page:', error)
      toast.error('Error toggling landing page')
    }
  }

  const handleSetDefault = async (id: string) => {
    try {
      const response = await fetch(`/api/landing-pages/${id}/set-default`, {
        method: 'POST',
      })

      const result = await response.json()

      if (result.success) {
        toast.success('Landing page set as default successfully')
        fetchLandingPages()
      } else {
        toast.error(result.error || 'Failed to set default landing page')
      }
    } catch (error) {
      console.error('Error setting default landing page:', error)
      toast.error('Error setting default landing page')
    }
  }

  const resetForm = () => {
    setFormData({
      name: '',
      slug: '',
      title: '',
      description: '',
      type: 'CLASSIC',
      path: '',
      isActive: false,
      isDefault: false,
      settings: '',
      metadata: ''
    })
  }

  const generateSlug = (name: string) => {
    return name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '')
  }

  const handleNameChange = (value: string) => {
    setFormData(prev => ({
      ...prev,
      name: value,
      slug: generateSlug(value)
    }))
  }

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'CLASSIC': return 'bg-amber-100 text-amber-600'
      case 'MODERN': return 'bg-blue-100 text-blue-600'
      case 'MINIMAL': return 'bg-gray-100 text-gray-600'
      case 'CORPORATE': return 'bg-purple-100 text-purple-600'
      default: return 'bg-gray-100 text-gray-600'
    }
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <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...</p>
        </div>
      </div>
    )
  }

  return (
    <AdminSidebar user={user}>
      {/* Header Section */}
      <div className="mb-8">
        <h2 className="text-2xl font-bold text-gray-900">
          Manajemen Landing Pages
        </h2>
        <p className="text-gray-600">
          Kelola dan konfigurasi halaman landing pages sistem
        </p>
      </div>

      {/* Actions Section */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center gap-4">
          <div className="text-sm text-gray-500">
            Total {landingPages.length} landing pages
          </div>
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button onClick={resetForm}>
              <Plus className="w-4 h-4 mr-2" />
              Tambah Landing Page
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle>Buat Landing Page Baru</DialogTitle>
              <DialogDescription>
                Tambahkan landing page baru ke sistem
              </DialogDescription>
            </DialogHeader>
            <form onSubmit={handleSubmit} className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="name">Nama</Label>
                  <Input
                    id="name"
                    value={formData.name}
                    onChange={(e) => handleNameChange(e.target.value)}
                    required
                  />
                </div>
                <div>
                  <Label htmlFor="slug">Slug</Label>
                  <Input
                    id="slug"
                    value={formData.slug}
                    onChange={(e) => setFormData(prev => ({ ...prev, slug: e.target.value }))}
                    required
                  />
                </div>
              </div>
              <div>
                <Label htmlFor="title">Judul</Label>
                <Input
                  id="title"
                  value={formData.title}
                  onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                  required
                />
              </div>
              <div>
                <Label htmlFor="description">Deskripsi</Label>
                <Textarea
                  id="description"
                  value={formData.description}
                  onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
                />
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <Label htmlFor="type">Tipe</Label>
                  <Select value={formData.type} onValueChange={(value: any) => setFormData(prev => ({ ...prev, type: value }))}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="CLASSIC">Classic</SelectItem>
                      <SelectItem value="MODERN">Modern</SelectItem>
                      <SelectItem value="MINIMAL">Minimal</SelectItem>
                      <SelectItem value="CORPORATE">Corporate</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div>
                  <Label htmlFor="path">Path</Label>
                  <Input
                    id="path"
                    value={formData.path}
                    onChange={(e) => setFormData(prev => ({ ...prev, path: e.target.value }))}
                    placeholder="/landing-pages/classic/page"
                    required
                  />
                </div>
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="isActive"
                  checked={formData.isActive}
                  onCheckedChange={(checked) => setFormData(prev => ({ ...prev, isActive: checked }))}
                />
                <Label htmlFor="isActive">Aktif</Label>
              </div>
              <div className="flex items-center space-x-2">
                <Switch
                  id="isDefault"
                  checked={formData.isDefault}
                  onCheckedChange={(checked) => setFormData(prev => ({ ...prev, isDefault: checked }))}
                />
                <Label htmlFor="isDefault">Default</Label>
              </div>
              <div>
                <Label htmlFor="settings">Settings (JSON)</Label>
                <Textarea
                  id="settings"
                  value={formData.settings}
                  onChange={(e) => setFormData(prev => ({ ...prev, settings: e.target.value }))}
                  placeholder='{"key": "value"}'
                  rows={3}
                />
              </div>
              <div>
                <Label htmlFor="metadata">Metadata (JSON)</Label>
                <Textarea
                  id="metadata"
                  value={formData.metadata}
                  onChange={(e) => setFormData(prev => ({ ...prev, metadata: e.target.value }))}
                  placeholder='{"seo": {"title": "Custom Title"}}'
                  rows={3}
                />
              </div>
              <DialogFooter>
                <Button type="button" variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
                  Batal
                </Button>
                <Button type="submit">Buat Landing Page</Button>
              </DialogFooter>
            </form>
          </DialogContent>
        </Dialog>
      </div>

      {/* Loading State */}
      {dataLoading ? (
        <Card>
          <CardContent className="flex items-center justify-center py-12">
            <div className="text-center">
              <RefreshCw className="w-8 h-8 animate-spin mx-auto mb-4 text-amber-600" />
              <p className="text-gray-600">Memuat landing pages...</p>
            </div>
          </CardContent>
        </Card>
      ) : (
        /* Landing Pages List */
        <div className="space-y-6">
          {landingPages.length === 0 ? (
            <Card>
              <CardContent className="flex items-center justify-center py-12">
                <div className="text-center">
                  <div className="w-16 h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <Settings className="w-8 h-8 text-gray-400" />
                  </div>
                  <h3 className="text-lg font-medium text-gray-900 mb-2">Belum ada landing pages</h3>
                  <p className="text-gray-500 mb-4">Mulai dengan membuat landing page pertama Anda</p>
                  <Button onClick={() => setIsCreateDialogOpen(true)}>
                    <Plus className="w-4 h-4 mr-2" />
                    Buat Landing Page
                  </Button>
                </div>
              </CardContent>
            </Card>
          ) : (
            landingPages.map((page) => (
              <Card key={page.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">
                        <CardTitle className="text-lg">{page.name}</CardTitle>
                        <Badge className={getTypeColor(page.type)}>
                          {page.type}
                        </Badge>
                        {page.isDefault && (
                          <Badge className="bg-yellow-100 text-yellow-600">
                            <Star className="w-3 h-3 mr-1" />
                            Default
                          </Badge>
                        )}
                        {page.isActive ? (
                          <Badge className="bg-green-100 text-green-600">
                            <Eye className="w-3 h-3 mr-1" />
                            Aktif
                          </Badge>
                        ) : (
                          <Badge className="bg-red-100 text-red-600">
                            <EyeOff className="w-3 h-3 mr-1" />
                            Tidak Aktif
                          </Badge>
                        )}
                      </div>
                      <CardDescription className="text-sm">{page.description}</CardDescription>
                      <p className="text-sm text-gray-500 mt-2">
                        <span className="font-medium">Path:</span> {page.path} | <span className="font-medium">Slug:</span> {page.slug}
                      </p>
                      <p className="text-xs text-gray-400 mt-1">
                        Dibuat: {new Date(page.createdAt).toLocaleString('id-ID')} | 
                        Diperbarui: {new Date(page.updatedAt).toLocaleString('id-ID')}
                      </p>
                    </div>
                    <div className="flex gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => window.open(page.path, '_blank')}
                        title="Preview"
                      >
                        <ExternalLink className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEdit(page)}
                        title="Edit"
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleToggleActive(page.id, !page.isActive)}
                        title={page.isActive ? 'Deactivate' : 'Activate'}
                      >
                        {page.isActive ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </Button>
                      {!page.isDefault && (
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleSetDefault(page.id)}
                          title="Set as Default"
                        >
                          <Star className="w-4 h-4" />
                        </Button>
                      )}
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button variant="outline" size="sm" title="Delete">
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>Apakah Anda yakin?</AlertDialogTitle>
                            <AlertDialogDescription>
                              Tindakan ini tidak dapat dibatalkan. Ini akan menghapus landing page "{page.name}" secara permanen.
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>Batal</AlertDialogCancel>
                            <AlertDialogAction onClick={() => handleDelete(page.id)} className="bg-red-600 hover:bg-red-700">
                              Hapus
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </div>
                </CardHeader>
              </Card>
            ))
          )}
        </div>
      )}

      {/* Edit Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>Edit Landing Page</DialogTitle>
            <DialogDescription>
              Perbarui informasi landing page
            </DialogDescription>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="edit-name">Nama</Label>
                <Input
                  id="edit-name"
                  value={formData.name}
                  onChange={(e) => handleNameChange(e.target.value)}
                  required
                />
              </div>
              <div>
                <Label htmlFor="edit-slug">Slug</Label>
                <Input
                  id="edit-slug"
                  value={formData.slug}
                  onChange={(e) => setFormData(prev => ({ ...prev, slug: e.target.value }))}
                  required
                />
              </div>
            </div>
            <div>
              <Label htmlFor="edit-title">Judul</Label>
              <Input
                id="edit-title"
                value={formData.title}
                onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                required
              />
            </div>
            <div>
              <Label htmlFor="edit-description">Deskripsi</Label>
              <Textarea
                id="edit-description"
                value={formData.description}
                onChange={(e) => setFormData(prev => ({ ...prev, description: e.target.value }))}
              />
            </div>
            <div className="grid grid-cols-2 gap-4">
              <div>
                <Label htmlFor="edit-type">Tipe</Label>
                <Select value={formData.type} onValueChange={(value: any) => setFormData(prev => ({ ...prev, type: value }))}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="CLASSIC">Classic</SelectItem>
                    <SelectItem value="MODERN">Modern</SelectItem>
                    <SelectItem value="MINIMAL">Minimal</SelectItem>
                    <SelectItem value="CORPORATE">Corporate</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="edit-path">Path</Label>
                <Input
                  id="edit-path"
                  value={formData.path}
                  onChange={(e) => setFormData(prev => ({ ...prev, path: e.target.value }))}
                  placeholder="/landing-pages/classic/page"
                  required
                />
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Switch
                id="edit-isActive"
                checked={formData.isActive}
                onCheckedChange={(checked) => setFormData(prev => ({ ...prev, isActive: checked }))}
              />
              <Label htmlFor="edit-isActive">Aktif</Label>
            </div>
            <div className="flex items-center space-x-2">
              <Switch
                id="edit-isDefault"
                checked={formData.isDefault}
                onCheckedChange={(checked) => setFormData(prev => ({ ...prev, isDefault: checked }))}
              />
              <Label htmlFor="edit-isDefault">Default</Label>
            </div>
            <div>
              <Label htmlFor="edit-settings">Settings (JSON)</Label>
              <Textarea
                id="edit-settings"
                value={formData.settings}
                onChange={(e) => setFormData(prev => ({ ...prev, settings: e.target.value }))}
                placeholder='{"key": "value"}'
                rows={3}
              />
            </div>
            <div>
              <Label htmlFor="edit-metadata">Metadata (JSON)</Label>
              <Textarea
                id="edit-metadata"
                value={formData.metadata}
                onChange={(e) => setFormData(prev => ({ ...prev, metadata: e.target.value }))}
                placeholder='{"seo": {"title": "Custom Title"}}'
                rows={3}
              />
            </div>
            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setIsEditDialogOpen(false)}>
                Batal
              </Button>
              <Button type="submit">Perbarui Landing Page</Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>
    </AdminSidebar>
  )
}
