'use client';

import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, 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 { Switch } from '@/components/ui/switch';
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
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, 
  MoveUp, 
  MoveDown, 
  Image as ImageIcon,
  Eye,
  EyeOff,
  GripVertical,
  FileText,
  Settings
} from 'lucide-react';
import { AdminSidebar } from '@/components/admin-sidebar';
import { useAdminAuth } from '@/hooks/useAdminAuth';
import { toast } from 'sonner';
import { useRouter } from 'next/navigation';

interface Slider {
  id: string;
  title?: string;
  subtitle?: string;
  description?: string;
  imageFile?: string;  // Uploaded image file path
  imageUrl?: string;   // External image URL (fallback)
  linkUrl?: string;
  displayType: string; // WITH_TEXT or BACKGROUND_ONLY
  isActive: boolean;
  order: number;
  createdAt: string;
  updatedAt: string;
}

export default function SlidersPage() {
  const { user, loading, isAuthenticated, logout, getAuthHeaders } = useAdminAuth();
  const router = useRouter();
  const [sliders, setSliders] = useState<Slider[]>([]);
  const [pageLoading, setPageLoading] = useState(true);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [editingSlider, setEditingSlider] = useState<Slider | null>(null);
  const [formData, setFormData] = useState({
    title: '',
    subtitle: '',
    description: '',
    imageFile: '',
    imageUrl: '',
    linkUrl: '',
    displayType: 'WITH_TEXT',
    isActive: true,
    order: 1
  });
  const [uploadingImage, setUploadingImage] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);

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

    if (isAuthenticated) {
      fetchSliders();
    }
  }, [loading, isAuthenticated, router]);

  const fetchSliders = async () => {
    try {
      const response = await fetch('/api/sliders');
      if (response.ok) {
        const data = await response.json();
        setSliders(data.data);
      }
    } catch (error) {
      console.error('Error fetching sliders:', error);
      toast.error('Gagal memuat data slider');
    } finally {
      setPageLoading(false);
    }
  };

  const resetForm = () => {
    setFormData({
      title: '',
      subtitle: '',
      description: '',
      imageFile: '',
      imageUrl: '',
      linkUrl: '',
      displayType: 'WITH_TEXT',
      isActive: true,
      order: 1
    });
    setSelectedFile(null);
    setEditingSlider(null);
  };

  const compressImage = async (file: File, maxWidth: number = 1920, maxHeight: number = 1080, quality: number = 0.8): Promise<File> => {
    return new Promise((resolve) => {
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      const img = new Image()
      
      img.onload = () => {
        // Calculate new dimensions
        let { width, height } = img
        
        if (width > maxWidth || height > maxHeight) {
          const ratio = Math.min(maxWidth / width, maxHeight / height)
          width *= ratio
          height *= ratio
        }
        
        canvas.width = width
        canvas.height = height
        
        // Draw and compress image
        ctx?.drawImage(img, 0, 0, width, height)
        
        canvas.toBlob((blob) => {
          if (blob) {
            const compressedFile = new File([blob], file.name, {
              type: file.type,
              lastModified: Date.now()
            })
            resolve(compressedFile)
          } else {
            resolve(file) // Return original if compression fails
          }
        }, file.type, quality)
      }
      
      img.onerror = () => resolve(file) // Return original if loading fails
      img.src = URL.createObjectURL(file)
    })
  }

  const handleImageUpload = async (file: File) => {
    if (!file) return null;

    try {
      setUploadingImage(true);
      
      // Compress image before upload
      const compressedFile = await compressImage(file, 1920, 1080, 0.8)
      
      // Log compression results
      const originalSize = (file.size / 1024 / 1024).toFixed(2)
      const compressedSize = (compressedFile.size / 1024 / 1024).toFixed(2)
      const compressionRatio = ((1 - compressedFile.size / file.size) * 100).toFixed(1)
      
      console.log(`Image compression: ${originalSize}MB → ${compressedSize}MB (${compressionRatio}% reduction)`)
      
      const formData = new FormData();
      formData.append('file', compressedFile);

      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const result = await response.json();
        toast.success(`Gambar berhasil diupload (Terkompres: ${compressionRatio}% smaller)`)
        return result.path; // Return the uploaded file path
      } else {
        const error = await response.json();
        toast.error(error.error || 'Gagal mengupload gambar');
        return null;
      }
    } catch (error) {
      console.error('Error uploading image:', error);
      toast.error('Gagal mengupload gambar');
      return null;
    } finally {
      setUploadingImage(false);
    }
  };

  const handleFileSelect = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file) return;

    // Validate file type
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
      toast.error('Tipe file tidak diizinkan. Hanya JPEG, PNG, GIF, dan WebP yang diperbolehkan');
      return;
    }

    // Validate file size (max 50MB)
    const maxSize = 50 * 1024 * 1024;
    if (file.size > maxSize) {
      toast.error('File terlalu besar. Ukuran maksimal adalah 50MB');
      return;
    }

    setSelectedFile(file);
    const uploadedPath = await handleImageUpload(file);
    if (uploadedPath) {
      setFormData(prev => ({ ...prev, imageFile: uploadedPath, imageUrl: '' }));
      toast.success('Gambar berhasil diupload');
    }
  };

  const handleCreate = async () => {
    try {
      const response = await fetch('/api/sliders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getAuthHeaders()
        },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        toast.success('Slider berhasil dibuat');
        setIsCreateDialogOpen(false);
        resetForm();
        fetchSliders();
      } else {
        const error = await response.json();
        toast.error(error.error || 'Gagal membuat slider');
      }
    } catch (error) {
      console.error('Error creating slider:', error);
      toast.error('Gagal membuat slider');
    }
  };

  const handleUpdate = async () => {
    if (!editingSlider) return;

    try {
      const response = await fetch(`/api/sliders/${editingSlider.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          ...getAuthHeaders()
        },
        body: JSON.stringify(formData)
      });

      if (response.ok) {
        toast.success('Slider berhasil diperbarui');
        setIsEditDialogOpen(false);
        resetForm();
        fetchSliders();
      } else {
        const error = await response.json();
        toast.error(error.error || 'Gagal memperbarui slider');
      }
    } catch (error) {
      console.error('Error updating slider:', error);
      toast.error('Gagal memperbarui slider');
    }
  };

  const handleDelete = async (id: string) => {
    try {
      const response = await fetch(`/api/sliders/${id}`, {
        method: 'DELETE',
        headers: getAuthHeaders()
      });

      if (response.ok) {
        toast.success('Slider berhasil dihapus');
        fetchSliders();
      } else {
        const error = await response.json();
        toast.error(error.error || 'Gagal menghapus slider');
      }
    } catch (error) {
      console.error('Error deleting slider:', error);
      toast.error('Gagal menghapus slider');
    }
  };

  const handleToggleActive = async (slider: Slider) => {
    try {
      const response = await fetch(`/api/sliders/${slider.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          ...getAuthHeaders()
        },
        body: JSON.stringify({
          ...slider,
          isActive: !slider.isActive
        })
      });

      if (response.ok) {
        toast.success(`Slider ${!slider.isActive ? 'diaktifkan' : 'dinonaktifkan'}`);
        fetchSliders();
      } else {
        const error = await response.json();
        toast.error(error.error || 'Gagal mengubah status slider');
      }
    } catch (error) {
      console.error('Error toggling slider:', error);
      toast.error('Gagal mengubah status slider');
    }
  };

  const moveSlider = async (index: number, direction: 'up' | 'down') => {
    const newSliders = [...sliders];
    const targetIndex = direction === 'up' ? index - 1 : index + 1;
    
    if (targetIndex < 0 || targetIndex >= newSliders.length) return;
    
    // Swap positions
    [newSliders[index], newSliders[targetIndex]] = [newSliders[targetIndex], newSliders[index]];
    
    // Update order values
    newSliders.forEach((slider, idx) => {
      slider.order = idx + 1;
    });
    
    try {
      const response = await fetch('/api/sliders/reorder', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...getAuthHeaders()
        },
        body: JSON.stringify({
          sliderIds: newSliders.map(s => s.id)
        })
      });

      if (response.ok) {
        setSliders(newSliders);
        toast.success('Urutan slider berhasil diperbarui');
      } else {
        const error = await response.json();
        toast.error(error.error || 'Gagal mengubah urutan slider');
      }
    } catch (error) {
      console.error('Error reordering sliders:', error);
      toast.error('Gagal mengubah urutan slider');
    }
  };

  const openEditDialog = (slider: Slider) => {
    setEditingSlider(slider);
    setFormData({
      title: slider.title || '',
      subtitle: slider.subtitle || '',
      description: slider.description || '',
      imageFile: slider.imageFile || '',
      imageUrl: slider.imageUrl || '',
      linkUrl: slider.linkUrl || '',
      displayType: slider.displayType || 'WITH_TEXT',
      isActive: slider.isActive,
      order: slider.order
    });
    setSelectedFile(null);
    setIsEditDialogOpen(true);
  };

  if (loading || pageLoading) {
    return (
      <AdminSidebar user={user}>
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-amber-600"></div>
        </div>
      </AdminSidebar>
    );
  }

  return (
    <AdminSidebar user={user}>
      <div className="space-y-8">
        {/* Header Section - No Card Background */}
        <div className="mb-8">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <div className="w-12 h-12 bg-gray-100 rounded-lg flex items-center justify-center">
                <ImageIcon className="w-6 h-6 text-gray-600" />
              </div>
              <div>
                <h1 className="text-3xl font-bold text-gray-900">Manajemen Slider/Banner</h1>
                <p className="text-gray-600 mt-1">Kelola slider dan banner untuk halaman utama</p>
                <div className="flex items-center gap-4 mt-2 text-sm text-gray-500">
                  <span>Total: {sliders.length} slider</span>
                  <span>•</span>
                  <span>Aktif: {sliders.filter(s => s.isActive).length} slider</span>
                </div>
              </div>
            </div>
            <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
              <DialogTrigger asChild>
                <Button 
                  className="bg-gray-900 hover:bg-gray-800 text-white shadow-sm transition-all duration-200"
                  onClick={resetForm}
                  size="lg"
                >
                  <Plus className="w-5 h-5 mr-2" />
                  Tambah Slider Baru
                </Button>
              </DialogTrigger>
          <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
            <DialogHeader>
              <DialogTitle className="text-xl font-semibold">Tambah Slider Baru</DialogTitle>
              <DialogDescription className="text-gray-600">
                Buat slider baru untuk ditampilkan di halaman utama. Upload gambar atau gunakan URL eksternal.
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-6 py-4">
              {/* Text Content Section */}
              <div className="space-y-4">
                <h3 className="text-lg font-medium text-gray-900 flex items-center gap-2">
                  <FileText className="w-5 h-5 text-gray-600" />
                  Konten Slider
                </h3>
                <div className="grid gap-4 pl-7">
                  <div className="grid gap-2">
                    <Label htmlFor="title" className="text-sm font-medium">Judul</Label>
                    <Input
                      id="title"
                      value={formData.title}
                      onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                      placeholder="Masukkan judul slider (opsional)"
                      className="h-11"
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="subtitle" className="text-sm font-medium">Subjudul</Label>
                    <Input
                      id="subtitle"
                      value={formData.subtitle}
                      onChange={(e) => setFormData({ ...formData, subtitle: e.target.value })}
                      placeholder="Masukkan subjudul"
                      className="h-11"
                    />
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="description" className="text-sm font-medium">Deskripsi</Label>
                    <Textarea
                      id="description"
                      value={formData.description}
                      onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                      placeholder="Masukkan deskripsi slider"
                      rows={3}
                      className="resize-none"
                    />
                  </div>
                </div>
              </div>

              {/* Image Section */}
              <div className="space-y-4">
                <h3 className="text-lg font-medium text-gray-900 flex items-center gap-2">
                  <ImageIcon className="w-5 h-5 text-gray-600" />
                  Gambar Slider
                </h3>
                <div className="grid gap-4 pl-7">
                  <div className="grid gap-2">
                    <Label htmlFor="imageFile" className="text-sm font-medium">Upload Gambar</Label>
                    <div className="space-y-3">
                      <div className="border-2 border-dashed border-gray-300 rounded-lg p-6 hover:border-gray-400 transition-colors">
                        <div className="text-center">
                          <ImageIcon className="w-12 h-12 text-gray-400 mx-auto mb-3" />
                          <div className="space-y-2">
                            <p className="text-sm text-gray-600">
                              Klik untuk upload atau drag and drop
                            </p>
                            <p className="text-xs text-gray-500">
                              PNG, JPG, GIF, WebP (Max. 50MB) - Otomatis dikompres ke ukuran optimal
                            </p>
                            <p className="text-xs text-blue-600">
                              💡 Gambar akan dikompres ke max 1920x1080px dengan kualitas 80% untuk mempercepat loading
                            </p>
                          </div>
                          <Input
                            id="imageFile"
                            type="file"
                            accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                            onChange={handleFileSelect}
                            disabled={uploadingImage}
                            className="mt-3 cursor-pointer"
                          />
                        </div>
                      </div>
                      {uploadingImage && (
                        <div className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg border border-gray-200">
                          <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-600"></div>
                          <span className="text-sm text-gray-700">Mengupload gambar...</span>
                        </div>
                      )}
                      {formData.imageFile && (
                        <div className="flex items-center gap-3 p-3 bg-green-50 rounded-lg border border-green-200">
                          <ImageIcon className="w-5 h-5 text-green-600" />
                          <div className="flex-1">
                            <span className="text-sm font-medium text-green-700">Gambar berhasil diupload</span>
                            <p className="text-xs text-green-600">{formData.imageFile}</p>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="imageUrl" className="text-sm font-medium">URL Gambar (Opsional - Fallback)</Label>
                    <Input
                      id="imageUrl"
                      value={formData.imageUrl}
                      onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value, imageFile: '' })}
                      placeholder="https://example.com/image.jpg"
                      disabled={!!formData.imageFile}
                      className="h-11 disabled:bg-gray-100 disabled:cursor-not-allowed"
                    />
                    {formData.imageFile && (
                      <p className="text-xs text-amber-600 bg-amber-50 p-2 rounded">
                        URL gambar dinonaktifkan karena gambar sudah diupload
                      </p>
                    )}
                  </div>
                </div>
              </div>

              {/* Settings Section */}
              <div className="space-y-4">
                <h3 className="text-lg font-medium text-gray-900 flex items-center gap-2">
                  <Settings className="w-5 h-5 text-gray-600" />
                  Pengaturan
                </h3>
                <div className="grid gap-4 pl-7">
                  <div className="grid gap-2">
                    <Label className="text-sm font-medium">Tipe Tampilan</Label>
                    <RadioGroup
                      value={formData.displayType}
                      onValueChange={(value) => setFormData({ ...formData, displayType: value })}
                      className="flex flex-col space-y-2"
                    >
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="WITH_TEXT" id="with-text" />
                        <Label htmlFor="with-text" className="text-sm font-normal cursor-pointer">
                          Dengan Teks - Menampilkan gambar dengan judul dan subjudul
                        </Label>
                      </div>
                      <div className="flex items-center space-x-2">
                        <RadioGroupItem value="BACKGROUND_ONLY" id="background-only" />
                        <Label htmlFor="background-only" className="text-sm font-normal cursor-pointer">
                          Background Only - Hanya menampilkan gambar tanpa teks
                        </Label>
                      </div>
                    </RadioGroup>
                  </div>
                  <div className="grid gap-2">
                    <Label htmlFor="linkUrl" className="text-sm font-medium">URL Link (Opsional)</Label>
                    <Input
                      id="linkUrl"
                      value={formData.linkUrl}
                      onChange={(e) => setFormData({ ...formData, linkUrl: e.target.value })}
                      placeholder="https://example.com"
                      className="h-11"
                    />
                  </div>
                  <div className="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
                    <Switch
                      id="isActive"
                      checked={formData.isActive}
                      onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
                    />
                    <Label htmlFor="isActive" className="text-sm font-medium cursor-pointer">
                      Slider Aktif
                    </Label>
                  </div>
                </div>
              </div>
            </div>
            <DialogFooter className="flex gap-3 pt-4">
              <Button 
                type="button" 
                variant="outline" 
                onClick={() => setIsCreateDialogOpen(false)}
                className="flex-1"
              >
                Batal
              </Button>
              <Button 
                type="button" 
                onClick={handleCreate}
                disabled={uploadingImage}
                className="flex-1 bg-gray-900 hover:bg-gray-800 text-white"
              >
                {uploadingImage ? (
                  <>
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    Menyimpan...
                  </>
                ) : (
                  <>
                    <Plus className="w-4 h-4 mr-2" />
                    Simpan Slider
                  </>
                )}
              </Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
        </div>

      {/* Sliders Grid */}
      <div className="space-y-6">
        {sliders.length === 0 ? (
          <Card className="border-2 border-dashed border-gray-300 bg-gray-50">
            <CardContent className="flex flex-col items-center justify-center py-16">
              <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mb-6">
                <ImageIcon className="w-10 h-10 text-gray-600" />
              </div>
              <h3 className="text-xl font-semibold text-gray-900 mb-3">Belum ada slider</h3>
              <p className="text-gray-600 text-center mb-6 max-w-md">
                Buat slider pertama untuk ditampilkan di halaman utama. Upload gambar menarik dan tambahkan teks yang relevan.
              </p>
              <Button 
                onClick={() => setIsCreateDialogOpen(true)}
                className="bg-gray-900 hover:bg-gray-800 text-white shadow-sm transition-all duration-200"
                size="lg"
              >
                <Plus className="w-5 h-5 mr-2" />
                Tambah Slider Pertama
              </Button>
            </CardContent>
          </Card>
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {sliders.map((slider, index) => (
              <Card key={slider.id} className="group hover:shadow-lg transition-all duration-300 border border-gray-200 shadow-sm overflow-hidden">
                {/* Card Header with Image */}
                <div className="relative h-48 bg-gray-100 overflow-hidden">
                  {(slider.imageFile || slider.imageUrl) ? (
                    <img 
                      src={slider.imageFile || slider.imageUrl} 
                      alt={slider.title}
                      className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center">
                      <ImageIcon className="w-16 h-16 text-gray-400" />
                    </div>
                  )}
                  
                  {/* Status Badge */}
                  <div className="absolute top-4 left-4">
                    <Badge className={`${
                      slider.isActive 
                        ? 'bg-green-500 hover:bg-green-600' 
                        : 'bg-gray-500 hover:bg-gray-600'
                    } text-white border-0`}>
                      {slider.isActive ? 'Aktif' : 'Nonaktif'}
                    </Badge>
                  </div>
                  
                  {/* Order Badge */}
                  <div className="absolute top-4 right-4">
                    <div className="bg-white/90 backdrop-blur-sm rounded-full w-8 h-8 flex items-center justify-center shadow-md">
                      <span className="text-sm font-bold text-gray-700">#{slider.order}</span>
                    </div>
                  </div>
                  
                  {/* Overlay Actions */}
                  <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity duration-300 flex items-center justify-center gap-2">
                    <Button
                      variant="secondary"
                      size="sm"
                      onClick={() => openEditDialog(slider)}
                      className="bg-white/90 hover:bg-white text-gray-900"
                    >
                      <Edit className="w-4 h-4 mr-1" />
                      Edit
                    </Button>
                    {slider.linkUrl && (
                      <Button
                        variant="secondary"
                        size="sm"
                        onClick={() => window.open(slider.linkUrl, '_blank')}
                        className="bg-white/90 hover:bg-white text-gray-900"
                      >
                        <Eye className="w-4 h-4 mr-1" />
                        Preview
                      </Button>
                    )}
                  </div>
                </div>
                
                {/* Card Content */}
                <CardContent className="p-6">
                  <div className="space-y-4">
                    {/* Title and Subtitle */}
                    <div>
                      <h3 className="text-xl font-bold text-gray-900 mb-2 line-clamp-2">
                        {slider.title}
                      </h3>
                      {slider.subtitle && (
                        <p className="text-gray-600 text-sm line-clamp-2">{slider.subtitle}</p>
                      )}
                    </div>
                    
                    {/* Description */}
                    {slider.description && (
                      <p className="text-gray-500 text-sm line-clamp-3">
                        {slider.description}
                      </p>
                    )}
                    
                    {/* Meta Info */}
                    <div className="flex items-center gap-4 text-xs text-gray-500 pt-2 border-t">
                      <div className="flex items-center gap-1">
                        {(slider.imageFile || slider.imageUrl) ? (
                          <>
                            <ImageIcon className="w-3 h-3" />
                            <span>{slider.imageFile ? 'Diupload' : 'URL'}</span>
                          </>
                        ) : (
                          <>
                            <ImageIcon className="w-3 h-3 text-gray-400" />
                            <span>Tidak ada gambar</span>
                          </>
                        )}
                      </div>
                      <div className="flex items-center gap-1">
                        <Settings className="w-3 h-3" />
                        <span>{slider.displayType === 'WITH_TEXT' ? 'Dengan Teks' : 'Background Saja'}</span>
                      </div>
                      {slider.linkUrl && (
                        <div className="flex items-center gap-1">
                          <span>•</span>
                          <span>Ada link</span>
                        </div>
                      )}
                    </div>
                    
                    {/* Action Buttons */}
                    <div className="flex items-center gap-2 pt-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleToggleActive(slider)}
                        className={`flex-1 ${
                          slider.isActive 
                            ? 'hover:bg-red-50 hover:text-red-600 hover:border-red-200' 
                            : 'hover:bg-green-50 hover:text-green-600 hover:border-green-200'
                        }`}
                      >
                        {slider.isActive ? (
                          <>
                            <EyeOff className="w-4 h-4 mr-1" />
                            Nonaktifkan
                          </>
                        ) : (
                          <>
                            <Eye className="w-4 h-4 mr-1" />
                            Aktifkan
                          </>
                        )}
                      </Button>
                      
                      <div className="flex items-center gap-1">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => moveSlider(index, 'up')}
                          disabled={index === 0}
                          className="h-8 w-8 p-0 disabled:opacity-50"
                        >
                          <MoveUp className="w-4 h-4" />
                        </Button>
                        
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => moveSlider(index, 'down')}
                          disabled={index === sliders.length - 1}
                          className="h-8 w-8 p-0 disabled:opacity-50"
                        >
                          <MoveDown className="w-4 h-4" />
                        </Button>
                      </div>
                      
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => openEditDialog(slider)}
                        className="h-8 w-8 p-0"
                      >
                        <Edit className="w-4 h-4" />
                      </Button>
                      
                      <AlertDialog>
                        <AlertDialogTrigger asChild>
                          <Button
                            variant="outline"
                            size="sm"
                            className="h-8 w-8 p-0 text-red-600 hover:text-red-700 hover:border-red-200"
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </AlertDialogTrigger>
                        <AlertDialogContent>
                          <AlertDialogHeader>
                            <AlertDialogTitle>Hapus Slider?</AlertDialogTitle>
                            <AlertDialogDescription>
                              Apakah Anda yakin ingin menghapus slider "{slider.title}"? 
                              Tindakan ini tidak dapat dibatalkan.
                            </AlertDialogDescription>
                          </AlertDialogHeader>
                          <AlertDialogFooter>
                            <AlertDialogCancel>Batal</AlertDialogCancel>
                            <AlertDialogAction
                              onClick={() => handleDelete(slider.id)}
                              className="bg-red-600 hover:bg-red-700"
                            >
                              Hapus
                            </AlertDialogAction>
                          </AlertDialogFooter>
                        </AlertDialogContent>
                      </AlertDialog>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>

      {/* Edit Dialog */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>Edit Slider</DialogTitle>
            <DialogDescription>
              Perbarui informasi slider
            </DialogDescription>
          </DialogHeader>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="edit-title">Judul</Label>
              <Input
                id="edit-title"
                value={formData.title}
                onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                placeholder="Masukkan judul slider (opsional)"
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="edit-subtitle">Subjudul</Label>
              <Input
                id="edit-subtitle"
                value={formData.subtitle}
                onChange={(e) => setFormData({ ...formData, subtitle: e.target.value })}
                placeholder="Masukkan subjudul"
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="edit-description">Deskripsi</Label>
              <Textarea
                id="edit-description"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
                placeholder="Masukkan deskripsi slider"
                rows={3}
              />
            </div>
            <div className="grid gap-2">
              <Label htmlFor="edit-imageFile">Upload Gambar</Label>
              <div className="space-y-2">
                <p className="text-xs text-blue-600">
                  💡 Gambar akan otomatis dikompres ke max 1920x1080px dengan kualitas 80%
                </p>
                <Input
                  id="edit-imageFile"
                  type="file"
                  accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
                  onChange={handleFileSelect}
                  disabled={uploadingImage}
                />
                {uploadingImage && (
                  <div className="flex items-center gap-2 text-sm text-amber-600">
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-amber-600"></div>
                    <span>Mengupload & mengompres gambar...</span>
                  </div>
                )}
                {formData.imageFile && (
                  <div className="flex items-center gap-2 p-2 bg-green-50 rounded border border-green-200">
                    <ImageIcon className="w-4 h-4 text-green-600" />
                    <span className="text-sm text-green-700">Gambar berhasil diupload & dikompres</span>
                  </div>
                )}
                {editingSlider?.imageFile && !formData.imageFile && (
                  <div className="flex items-center gap-2 p-2 bg-blue-50 rounded border border-blue-200">
                    <ImageIcon className="w-4 h-4 text-blue-600" />
                    <span className="text-sm text-blue-700">Gambar existing: {editingSlider.imageFile}</span>
                  </div>
                )}
              </div>
            </div>
            <div className="grid gap-2">
              <Label htmlFor="edit-imageUrl">URL Gambar (Opsional - fallback)</Label>
              <Input
                id="edit-imageUrl"
                value={formData.imageUrl}
                onChange={(e) => setFormData({ ...formData, imageUrl: e.target.value, imageFile: '' })}
                placeholder="https://example.com/image.jpg"
                disabled={!!formData.imageFile}
              />
              {formData.imageFile && (
                <p className="text-xs text-gray-500">
                  URL gambar dinonaktifkan karena gambar sudah diupload
                </p>
              )}
            </div>
            <div className="grid gap-2">
              <Label htmlFor="edit-linkUrl">URL Link (Opsional)</Label>
              <Input
                id="edit-linkUrl"
                value={formData.linkUrl}
                onChange={(e) => setFormData({ ...formData, linkUrl: e.target.value })}
                placeholder="https://example.com"
              />
            </div>
            <div className="grid gap-2">
              <Label className="text-sm font-medium">Tipe Tampilan</Label>
              <RadioGroup
                value={formData.displayType}
                onValueChange={(value) => setFormData({ ...formData, displayType: value })}
                className="space-y-2"
              >
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="WITH_TEXT" id="edit-with-text" />
                  <Label htmlFor="edit-with-text" className="text-sm cursor-pointer">
                    <div className="font-medium">Dengan Teks</div>
                    <div className="text-gray-500 text-xs">Tampilkan gambar dengan judul, subjudul, dan deskripsi</div>
                  </Label>
                </div>
                <div className="flex items-center space-x-2">
                  <RadioGroupItem value="BACKGROUND_ONLY" id="edit-background-only" />
                  <Label htmlFor="edit-background-only" className="text-sm cursor-pointer">
                    <div className="font-medium">Hanya Background</div>
                    <div className="text-gray-500 text-xs">Tampilkan gambar sebagai background tanpa teks</div>
                  </Label>
                </div>
              </RadioGroup>
            </div>
            <div className="flex items-center space-x-2">
              <Switch
                id="edit-isActive"
                checked={formData.isActive}
                onCheckedChange={(checked) => setFormData({ ...formData, isActive: checked })}
              />
              <Label htmlFor="edit-isActive">Aktif</Label>
            </div>
          </div>
          <DialogFooter className="flex gap-3 pt-4">
            <Button 
              type="button" 
              variant="outline" 
              onClick={() => setIsEditDialogOpen(false)}
              className="flex-1"
            >
              Batal
            </Button>
            <Button 
              type="button" 
              onClick={handleUpdate}
              disabled={uploadingImage}
              className="flex-1 bg-gray-900 hover:bg-gray-800 text-white"
            >
              {uploadingImage ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  Menyimpan...
                </>
              ) : (
                <>
                  <Edit className="w-4 h-4 mr-2" />
                  Perbarui Slider
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
        </div>
      </div>
    </AdminSidebar>
  );
}