"use client";

import { useState, useEffect } from "react";
import useSWR from "swr";
import { toast } from "sonner";
import {
  ColumnDef,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  SortingState,
  useReactTable,
} from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
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 {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import AdminPoliLandingService from "@/services/admin.poli-landing.service";
import type { PoliLandingContent, CustomSection, CustomSectionItem } from "@/services/poli-landing.service";
import {
  Plus,
  Save,
  MoreHorizontal,
  Edit,
  Trash,
  ChevronLeft,
  ChevronRight,
  Loader2,
  FileText,
  List,
  Tag,
  LayoutGrid,
  Clock,
  Puzzle,
  Package,
  Stethoscope,
  ChevronDown,
  ChevronRight as ChevronRightIcon,
} from "lucide-react";

// Form Data Types
interface PageContentFormData {
  isPublished: boolean;
  heroTitle: string;
  heroSubtitle: string;
  heroImageUrl: string;
  heroPrimaryCtaLabel: string;
  heroPrimaryCtaUrl: string;
  heroSecondaryCtaLabel: string;
  heroSecondaryCtaUrl: string;
  heroBadgeTitle: string;
  heroBadgeDescription: string;
  heroBadgeCountLabel: string;
  serviceSectionTitle: string;
  serviceSectionSubtitle: string;
  doctorSectionTitle: string;
  doctorSectionSubtitle: string;
  scheduleSectionTitle: string;
  scheduleSectionSubtitle: string;
}

interface HighlightFormData {
  text: string;
  order: number;
}

interface ServiceChipFormData {
  label: string;
  order: number;
}

interface ServiceCardFormData {
  title: string;
  description: string;
  icon: string;
  imageUrl: string;
  order: number;
}

interface ScheduleRowFormData {
  day: string;
  hoursText: string;
  order: number;
}

interface CustomSectionFormData {
  type: 'GENERIC' | 'KB_METHODS';
  title: string;
  subtitle: string;
  ctaLabel: string;
  ctaUrl: string;
  order: number;
}

interface CustomItemFormData {
  title: string;
  description: string;
  imageUrl: string;
  order: number;
}

const PoliLandingAdminPage = () => {
  const [selectedPoli, setSelectedPoli] = useState<string>("poli-umum");
  const [activeTab, setActiveTab] = useState("content");
  const [sorting, setSorting] = useState<SortingState>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState<'highlight' | 'serviceChip' | 'serviceCard' | 'scheduleRow' | 'customSection' | 'customItem' | null>(null);
  const [editingItem, setEditingItem] = useState<any>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<any>(null);
  const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set());
  const [selectedSectionId, setSelectedSectionId] = useState<string | null>(null);

  // Fetch data
  const { data: content, isLoading, mutate } = useSWR<PoliLandingContent>(
    `/admin/poli-landing/${selectedPoli}`,
    () => AdminPoliLandingService.getAdminContent(selectedPoli),
    { revalidateOnFocus: false }
  );

  // Fetch list of all poli pages
  const { data: poliPages = [] } = useSWR(
    "/admin/poli-landings/pages",
    () => AdminPoliLandingService.getAllPages()
  );

  // Page Content Form
  const [pageForm, setPageForm] = useState<PageContentFormData>({
    isPublished: true,
    heroTitle: "",
    heroSubtitle: "",
    heroImageUrl: "",
    heroPrimaryCtaLabel: "",
    heroPrimaryCtaUrl: "",
    heroSecondaryCtaLabel: "",
    heroSecondaryCtaUrl: "",
    heroBadgeTitle: "",
    heroBadgeDescription: "",
    heroBadgeCountLabel: "",
    serviceSectionTitle: "",
    serviceSectionSubtitle: "",
    doctorSectionTitle: "",
    doctorSectionSubtitle: "",
    scheduleSectionTitle: "",
    scheduleSectionSubtitle: "",
  });

  // CRUD Forms
  const [highlightForm, setHighlightForm] = useState<HighlightFormData>({ text: "", order: 0 });
  const [serviceChipForm, setServiceChipForm] = useState<ServiceChipFormData>({ label: "", order: 0 });
  const [serviceCardForm, setServiceCardForm] = useState<ServiceCardFormData>({ 
    title: "", description: "", icon: "", imageUrl: "", order: 0 
  });
  const [scheduleRowForm, setScheduleRowForm] = useState<ScheduleRowFormData>({ 
    day: "", hoursText: "", order: 0 
  });
  const [customSectionForm, setCustomSectionForm] = useState<CustomSectionFormData>({ 
    type: 'GENERIC', title: "", subtitle: "", ctaLabel: "", ctaUrl: "", order: 0 
  });
  const [customItemForm, setCustomItemForm] = useState<CustomItemFormData>({ 
    title: "", description: "", imageUrl: "", order: 0 
  });

  // Update form when data loads
  useEffect(() => {
    if (content?.page) {
      setPageForm({
        isPublished: content.page.isPublished,
        heroTitle: content.page.heroTitle || "",
        heroSubtitle: content.page.heroSubtitle || "",
        heroImageUrl: content.page.heroImageUrl || "",
        heroPrimaryCtaLabel: content.page.heroPrimaryCtaLabel || "",
        heroPrimaryCtaUrl: content.page.heroPrimaryCtaUrl || "",
        heroSecondaryCtaLabel: content.page.heroSecondaryCtaLabel || "",
        heroSecondaryCtaUrl: content.page.heroSecondaryCtaUrl || "",
        heroBadgeTitle: content.page.heroBadgeTitle || "",
        heroBadgeDescription: content.page.heroBadgeDescription || "",
        heroBadgeCountLabel: content.page.heroBadgeCountLabel || "",
        serviceSectionTitle: content.page.serviceSectionTitle || "",
        serviceSectionSubtitle: content.page.serviceSectionSubtitle || "",
        doctorSectionTitle: content.page.doctorSectionTitle || "",
        doctorSectionSubtitle: content.page.doctorSectionSubtitle || "",
        scheduleSectionTitle: content.page.scheduleSectionTitle || "",
        scheduleSectionSubtitle: content.page.scheduleSectionSubtitle || "",
      });
    }
  }, [content]);

  // Handlers
  const handleSavePageContent = async () => {
    setIsSubmitting(true);
    try {
      await AdminPoliLandingService.updatePage(selectedPoli, {
        isPublished: pageForm.isPublished,
        heroTitle: pageForm.heroTitle,
        heroSubtitle: pageForm.heroSubtitle,
        heroImageUrl: pageForm.heroImageUrl,
        heroPrimaryCtaLabel: pageForm.heroPrimaryCtaLabel,
        heroPrimaryCtaUrl: pageForm.heroPrimaryCtaUrl,
        heroSecondaryCtaLabel: pageForm.heroSecondaryCtaLabel,
        heroSecondaryCtaUrl: pageForm.heroSecondaryCtaUrl,
        heroBadgeTitle: pageForm.heroBadgeTitle,
        heroBadgeDescription: pageForm.heroBadgeDescription,
        heroBadgeCountLabel: pageForm.heroBadgeCountLabel,
        serviceSectionTitle: pageForm.serviceSectionTitle,
        serviceSectionSubtitle: pageForm.serviceSectionSubtitle,
        doctorSectionTitle: pageForm.doctorSectionTitle,
        doctorSectionSubtitle: pageForm.doctorSectionSubtitle,
        scheduleSectionTitle: pageForm.scheduleSectionTitle,
        scheduleSectionSubtitle: pageForm.scheduleSectionSubtitle,
      });
      toast.success("Konten halaman berhasil diperbarui");
      mutate();
    } catch (error) {
      toast.error("Gagal memperbarui konten halaman");
    } finally {
      setIsSubmitting(false);
    }
  };

  // Dialog handlers
  const openCreateDialog = (type: 'highlight' | 'serviceChip' | 'serviceCard' | 'scheduleRow' | 'customSection' | 'customItem', sectionId?: string) => {
    setDialogType(type);
    setEditingItem(null);
    setSelectedSectionId(sectionId || null);
    
    const currentLength = 
      type === 'highlight' ? content?.highlights?.length || 0 :
      type === 'serviceChip' ? content?.serviceChips?.length || 0 :
      type === 'serviceCard' ? content?.serviceCards?.length || 0 :
      type === 'scheduleRow' ? content?.scheduleRows?.length || 0 :
      type === 'customSection' ? content?.customSections?.length || 0 :
      sectionId ? content?.customSections?.find(s => s.id === sectionId)?.items?.length || 0 : 0;

    if (type === 'highlight') {
      setHighlightForm({ text: "", order: currentLength });
    } else if (type === 'serviceChip') {
      setServiceChipForm({ label: "", order: currentLength });
    } else if (type === 'serviceCard') {
      setServiceCardForm({ title: "", description: "", icon: "", imageUrl: "", order: currentLength });
    } else if (type === 'scheduleRow') {
      setScheduleRowForm({ day: "", hoursText: "", order: currentLength });
    } else if (type === 'customSection') {
      setCustomSectionForm({ type: 'GENERIC', title: "", subtitle: "", ctaLabel: "", ctaUrl: "", order: currentLength });
    } else if (type === 'customItem' && sectionId) {
      setCustomItemForm({ title: "", description: "", imageUrl: "", order: currentLength });
    }
    setIsDialogOpen(true);
  };

  const openEditDialog = (type: 'highlight' | 'serviceChip' | 'serviceCard' | 'scheduleRow' | 'customSection' | 'customItem', item: any, sectionId?: string) => {
    setDialogType(type);
    setEditingItem(item);
    setSelectedSectionId(sectionId || null);

    if (type === 'highlight') {
      setHighlightForm({ text: item.text, order: item.order });
    } else if (type === 'serviceChip') {
      setServiceChipForm({ label: item.label, order: item.order });
    } else if (type === 'serviceCard') {
      setServiceCardForm({ 
        title: item.title, 
        description: item.description || "", 
        icon: item.icon || "", 
        imageUrl: item.imageUrl || "", 
        order: item.order 
      });
    } else if (type === 'scheduleRow') {
      setScheduleRowForm({ day: item.day, hoursText: item.hoursText, order: item.order });
    } else if (type === 'customSection') {
      setCustomSectionForm({ 
        type: item.type, 
        title: item.title, 
        subtitle: item.subtitle || "", 
        ctaLabel: item.ctaLabel || "", 
        ctaUrl: item.ctaUrl || "", 
        order: item.order 
      });
    } else if (type === 'customItem') {
      setCustomItemForm({ 
        title: item.title, 
        description: item.description || "", 
        imageUrl: item.imageUrl || "", 
        order: item.order 
      });
    }
    setIsDialogOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!dialogType) return;

    setIsSubmitting(true);
    try {
      if (dialogType === 'highlight') {
        if (editingItem) {
          await AdminPoliLandingService.updateHighlight(editingItem.id, highlightForm);
        } else {
          await AdminPoliLandingService.createHighlight(selectedPoli, highlightForm);
        }
      } else if (dialogType === 'serviceChip') {
        if (editingItem) {
          await AdminPoliLandingService.updateServiceChip(editingItem.id, serviceChipForm);
        } else {
          await AdminPoliLandingService.createServiceChip(selectedPoli, serviceChipForm);
        }
      } else if (dialogType === 'serviceCard') {
        if (editingItem) {
          await AdminPoliLandingService.updateServiceCard(editingItem.id, serviceCardForm);
        } else {
          await AdminPoliLandingService.createServiceCard(selectedPoli, serviceCardForm);
        }
      } else if (dialogType === 'scheduleRow') {
        if (editingItem) {
          await AdminPoliLandingService.updateScheduleRow(editingItem.id, scheduleRowForm);
        } else {
          await AdminPoliLandingService.createScheduleRow(selectedPoli, scheduleRowForm);
        }
      } else if (dialogType === 'customSection') {
        if (editingItem) {
          await AdminPoliLandingService.updateCustomSection(editingItem.id, customSectionForm);
        } else {
          await AdminPoliLandingService.createCustomSection(selectedPoli, customSectionForm);
        }
      } else if (dialogType === 'customItem' && selectedSectionId) {
        if (editingItem) {
          await AdminPoliLandingService.updateCustomItem(editingItem.id, customItemForm);
        } else {
          await AdminPoliLandingService.createCustomItem(selectedSectionId, customItemForm);
        }
      }

      const itemName = 
        dialogType === 'highlight' ? 'Highlight' :
        dialogType === 'serviceChip' ? 'Service Chip' :
        dialogType === 'serviceCard' ? 'Service Card' :
        dialogType === 'scheduleRow' ? 'Jadwal' :
        dialogType === 'customSection' ? 'Custom Section' : 'Item';
      
      toast.success(`${itemName} berhasil ${editingItem ? 'diperbarui' : 'ditambahkan'}`);
      mutate();
      setIsDialogOpen(false);
    } catch (error) {
      toast.error("Gagal menyimpan data");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleDelete = async () => {
    if (!itemToDelete || !dialogType) return;
    
    try {
      if (dialogType === 'highlight') {
        await AdminPoliLandingService.deleteHighlight(itemToDelete.id);
      } else if (dialogType === 'serviceChip') {
        await AdminPoliLandingService.deleteServiceChip(itemToDelete.id);
      } else if (dialogType === 'serviceCard') {
        await AdminPoliLandingService.deleteServiceCard(itemToDelete.id);
      } else if (dialogType === 'scheduleRow') {
        await AdminPoliLandingService.deleteScheduleRow(itemToDelete.id);
      } else if (dialogType === 'customSection') {
        await AdminPoliLandingService.deleteCustomSection(itemToDelete.id);
      } else if (dialogType === 'customItem') {
        await AdminPoliLandingService.deleteCustomItem(itemToDelete.id);
      }
      toast.success("Berhasil dihapus");
      mutate();
    } catch (error) {
      toast.error("Gagal menghapus");
    } finally {
      setDeleteDialogOpen(false);
      setItemToDelete(null);
    }
  };

  const toggleSection = (sectionId: string) => {
    const newExpanded = new Set(expandedSections);
    if (newExpanded.has(sectionId)) {
      newExpanded.delete(sectionId);
    } else {
      newExpanded.add(sectionId);
    }
    setExpandedSections(newExpanded);
  };

  // Table Columns
  const highlightColumns: ColumnDef<PoliLandingContent['highlights'][0]>[] = [
    { accessorKey: "text", header: "Teks", cell: ({ row }) => <span className="font-medium">{row.original.text}</span> },
    { accessorKey: "order", header: "Urutan" },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEditDialog('highlight', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('highlight'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const serviceChipColumns: ColumnDef<PoliLandingContent['serviceChips'][0]>[] = [
    { accessorKey: "label", header: "Label", cell: ({ row }) => <span className="font-medium">{row.original.label}</span> },
    { accessorKey: "order", header: "Urutan" },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEditDialog('serviceChip', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('serviceChip'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const serviceCardColumns: ColumnDef<PoliLandingContent['serviceCards'][0]>[] = [
    { accessorKey: "title", header: "Judul", cell: ({ row }) => <span className="font-medium">{row.original.title}</span> },
    { accessorKey: "description", header: "Deskripsi", cell: ({ row }) => <span className="text-sm text-slate-600 truncate max-w-xs">{row.original.description || '-'}</span> },
    { accessorKey: "icon", header: "Icon", cell: ({ row }) => <span className="text-sm text-slate-500">{row.original.icon || '-'}</span> },
    { accessorKey: "order", header: "Urutan" },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEditDialog('serviceCard', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('serviceCard'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const scheduleRowColumns: ColumnDef<PoliLandingContent['scheduleRows'][0]>[] = [
    { accessorKey: "day", header: "Hari", cell: ({ row }) => <span className="font-medium">{row.original.day}</span> },
    { accessorKey: "hoursText", header: "Jam", cell: ({ row }) => <span className="text-sm text-slate-600">{row.original.hoursText}</span> },
    { accessorKey: "order", header: "Urutan" },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEditDialog('scheduleRow', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('scheduleRow'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const customSectionColumns: ColumnDef<CustomSection>[] = [
    { accessorKey: "title", header: "Judul", cell: ({ row }) => <span className="font-medium">{row.original.title}</span> },
    { accessorKey: "type", header: "Tipe", cell: ({ row }) => <Badge variant="secondary">{row.original.type}</Badge> },
    { accessorKey: "order", header: "Urutan" },
    { 
      accessorKey: "items", 
      header: "Items", 
      cell: ({ row }) => <span className="text-sm text-slate-600">{row.original.items?.length || 0} items</span> 
    },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEditDialog('customSection', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('customSection'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const customItemColumns: ColumnDef<CustomSectionItem>[] = [
    { accessorKey: "title", header: "Judul", cell: ({ row }) => <span className="font-medium">{row.original.title}</span> },
    { accessorKey: "description", header: "Deskripsi", cell: ({ row }) => <span className="text-sm text-slate-600 truncate max-w-xs">{row.original.description || '-'}</span> },
    { accessorKey: "order", header: "Urutan" },
    {
      id: "actions",
      header: "Aksi",
      cell: ({ row }) => (
        <DropdownMenu>
          <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
          <DropdownMenuContent align="end">
            <DropdownMenuItem onClick={() => openEditDialog('customItem', row.original, selectedSectionId!)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('customItem'); setItemToDelete(row.original); setSelectedSectionId(content?.customSections?.find(s => s.items?.some(i => i.id === row.original.id))?.id || null); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  // Tables
  const highlightTable = useReactTable({
    data: content?.highlights || [],
    columns: highlightColumns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: { sorting },
  });

  const serviceChipTable = useReactTable({
    data: content?.serviceChips || [],
    columns: serviceChipColumns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: { sorting },
  });

  const serviceCardTable = useReactTable({
    data: content?.serviceCards || [],
    columns: serviceCardColumns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: { sorting },
  });

  const scheduleRowTable = useReactTable({
    data: content?.scheduleRows || [],
    columns: scheduleRowColumns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: { sorting },
  });

  const customSectionTable = useReactTable({
    data: content?.customSections || [],
    columns: customSectionColumns,
    getCoreRowModel: getCoreRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    getSortedRowModel: getSortedRowModel(),
    onSortingChange: setSorting,
    state: { sorting },
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Kelola Landing Poli</h1>
          <p className="text-slate-500">Edit konten landing page untuk setiap poli</p>
        </div>
        <div className="flex items-center gap-4">
          <Select value={selectedPoli} onValueChange={(value) => value && setSelectedPoli(value)}>
            <SelectTrigger className="w-[200px]">
              <Stethoscope className="h-4 w-4 mr-2" />
              <SelectValue />
            </SelectTrigger>
            <SelectContent>
              {poliPages.map((poli) => (
                <SelectItem key={poli.poliSlug} value={poli.poliSlug}>
                  <div className="flex items-center gap-2">
                    {poli.title}
                    {!poli.isPublished && (
                      <span className="text-xs text-amber-500">(Draft)</span>
                    )}
                  </div>
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* Poli Info Card */}
      {content?.poli && (
        <Card className="bg-primary/5 border-primary/20">
          <CardContent className="p-4">
            <div className="flex items-center gap-4">
              <div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center">
                <Stethoscope className="h-6 w-6 text-primary" />
              </div>
              <div>
                <h2 className="font-semibold text-slate-900">{content.poli.name}</h2>
                <p className="text-sm text-slate-500">Slug: {content.poli.slug}</p>
              </div>
              <Badge variant={content.page.isPublished ? "default" : "secondary"} className="ml-auto">
                {content.page.isPublished ? "Published" : "Draft"}
              </Badge>
            </div>
          </CardContent>
        </Card>
      )}

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList className="grid w-full grid-cols-6">
          <TabsTrigger value="content" className="flex items-center gap-2">
            <FileText className="h-4 w-4" /> Konten
          </TabsTrigger>
          <TabsTrigger value="highlights" className="flex items-center gap-2">
            <Tag className="h-4 w-4" /> Highlights ({content?.highlights?.length || 0})
          </TabsTrigger>
          <TabsTrigger value="chips" className="flex items-center gap-2">
            <List className="h-4 w-4" /> Chips ({content?.serviceChips?.length || 0})
          </TabsTrigger>
          <TabsTrigger value="cards" className="flex items-center gap-2">
            <LayoutGrid className="h-4 w-4" /> Cards ({content?.serviceCards?.length || 0})
          </TabsTrigger>
          <TabsTrigger value="schedule" className="flex items-center gap-2">
            <Clock className="h-4 w-4" /> Jadwal ({content?.scheduleRows?.length || 0})
          </TabsTrigger>
          <TabsTrigger value="custom" className="flex items-center gap-2">
            <Puzzle className="h-4 w-4" /> Custom ({content?.customSections?.length || 0})
          </TabsTrigger>
        </TabsList>

        {/* Page Content Tab */}
        <TabsContent value="content" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><FileText className="h-5 w-5" />Page Content</CardTitle>
              <Button onClick={handleSavePageContent} disabled={isSubmitting} size="sm">
                {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                <Save className="h-4 w-4 mr-2" />Simpan
              </Button>
            </CardHeader>
            <CardContent className="space-y-6">
              {/* Publish Status */}
              <div className="flex items-center justify-between p-4 border rounded-lg bg-slate-50">
                <div>
                  <Label className="font-medium">Status Publikasi</Label>
                  <p className="text-sm text-slate-500">Halaman akan terlihat di website jika dipublikasikan</p>
                </div>
                <Switch 
                  checked={pageForm.isPublished} 
                  onCheckedChange={(checked) => setPageForm({ ...pageForm, isPublished: checked })} 
                />
              </div>

              {/* Hero Section */}
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-900 border-b pb-2">Hero Section</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Judul Hero *</Label>
                    <Input value={pageForm.heroTitle} onChange={(e) => setPageForm({ ...pageForm, heroTitle: e.target.value })} placeholder="Contoh: Poli Umum" />
                  </div>
                  <div className="space-y-2">
                    <Label>Subtitle Hero *</Label>
                    <Input value={pageForm.heroSubtitle} onChange={(e) => setPageForm({ ...pageForm, heroSubtitle: e.target.value })} placeholder="Deskripsi singkat..." />
                  </div>
                </div>
                <div className="space-y-2">
                  <Label>URL Gambar Hero</Label>
                  <Input value={pageForm.heroImageUrl} onChange={(e) => setPageForm({ ...pageForm, heroImageUrl: e.target.value })} placeholder="https://..." />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Label CTA Primary</Label>
                    <Input value={pageForm.heroPrimaryCtaLabel} onChange={(e) => setPageForm({ ...pageForm, heroPrimaryCtaLabel: e.target.value })} placeholder="Daftar Sekarang" />
                  </div>
                  <div className="space-y-2">
                    <Label>URL CTA Primary</Label>
                    <Input value={pageForm.heroPrimaryCtaUrl} onChange={(e) => setPageForm({ ...pageForm, heroPrimaryCtaUrl: e.target.value })} placeholder="/book/poli-umum" />
                  </div>
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Label CTA Secondary</Label>
                    <Input value={pageForm.heroSecondaryCtaLabel} onChange={(e) => setPageForm({ ...pageForm, heroSecondaryCtaLabel: e.target.value })} placeholder="Pelajari Lebih" />
                  </div>
                  <div className="space-y-2">
                    <Label>URL CTA Secondary</Label>
                    <Input value={pageForm.heroSecondaryCtaUrl} onChange={(e) => setPageForm({ ...pageForm, heroSecondaryCtaUrl: e.target.value })} placeholder="#layanan" />
                  </div>
                </div>
                <div className="grid grid-cols-3 gap-4">
                  <div className="space-y-2">
                    <Label>Badge Title</Label>
                    <Input value={pageForm.heroBadgeTitle} onChange={(e) => setPageForm({ ...pageForm, heroBadgeTitle: e.target.value })} placeholder="Pasien Terlayani" />
                  </div>
                  <div className="space-y-2">
                    <Label>Badge Description</Label>
                    <Input value={pageForm.heroBadgeDescription} onChange={(e) => setPageForm({ ...pageForm, heroBadgeDescription: e.target.value })} placeholder="Lebih dari 10.000" />
                  </div>
                  <div className="space-y-2">
                    <Label>Badge Count Label</Label>
                    <Input value={pageForm.heroBadgeCountLabel} onChange={(e) => setPageForm({ ...pageForm, heroBadgeCountLabel: e.target.value })} placeholder="pasien" />
                  </div>
                </div>
              </div>

              {/* Service Section */}
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-900 border-b pb-2">Service Section</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Judul Section Layanan *</Label>
                    <Input value={pageForm.serviceSectionTitle} onChange={(e) => setPageForm({ ...pageForm, serviceSectionTitle: e.target.value })} placeholder="Layanan Kami" />
                  </div>
                  <div className="space-y-2">
                    <Label>Subtitle Section Layanan *</Label>
                    <Input value={pageForm.serviceSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, serviceSectionSubtitle: e.target.value })} placeholder="Berbagai layanan..." />
                  </div>
                </div>
              </div>

              {/* Doctor Section */}
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-900 border-b pb-2">Doctor Section</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Judul Section Dokter *</Label>
                    <Input value={pageForm.doctorSectionTitle} onChange={(e) => setPageForm({ ...pageForm, doctorSectionTitle: e.target.value })} placeholder="Dokter Kami" />
                  </div>
                  <div className="space-y-2">
                    <Label>Subtitle Section Dokter *</Label>
                    <Input value={pageForm.doctorSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, doctorSectionSubtitle: e.target.value })} placeholder="Tim dokter berpengalaman..." />
                  </div>
                </div>
              </div>

              {/* Schedule Section */}
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-900 border-b pb-2">Schedule Section</h3>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>Judul Section Jadwal *</Label>
                    <Input value={pageForm.scheduleSectionTitle} onChange={(e) => setPageForm({ ...pageForm, scheduleSectionTitle: e.target.value })} placeholder="Jadwal Praktik" />
                  </div>
                  <div className="space-y-2">
                    <Label>Subtitle Section Jadwal *</Label>
                    <Input value={pageForm.scheduleSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, scheduleSectionSubtitle: e.target.value })} placeholder="Kami siap melayani..." />
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Highlights Tab */}
        <TabsContent value="highlights" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><Tag className="h-5 w-5" />Highlights</CardTitle>
              <Button onClick={() => openCreateDialog('highlight')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {highlightTable.getHeaderGroups().map((hg) => (
                      <TableRow key={hg.id}>
                        {hg.headers.map((h) => (
                          <TableHead key={h.id}>{h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}</TableHead>
                        ))}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {highlightTable.getRowModel().rows?.length ? (
                      highlightTable.getRowModel().rows.map((row) => (
                        <TableRow key={row.id}>
                          {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow><TableCell colSpan={highlightColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Service Chips Tab */}
        <TabsContent value="chips" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><List className="h-5 w-5" />Service Chips</CardTitle>
              <Button onClick={() => openCreateDialog('serviceChip')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {serviceChipTable.getHeaderGroups().map((hg) => (
                      <TableRow key={hg.id}>
                        {hg.headers.map((h) => (
                          <TableHead key={h.id}>{h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}</TableHead>
                        ))}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {serviceChipTable.getRowModel().rows?.length ? (
                      serviceChipTable.getRowModel().rows.map((row) => (
                        <TableRow key={row.id}>
                          {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow><TableCell colSpan={serviceChipColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Service Cards Tab */}
        <TabsContent value="cards" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><LayoutGrid className="h-5 w-5" />Service Cards</CardTitle>
              <Button onClick={() => openCreateDialog('serviceCard')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {serviceCardTable.getHeaderGroups().map((hg) => (
                      <TableRow key={hg.id}>
                        {hg.headers.map((h) => (
                          <TableHead key={h.id}>{h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}</TableHead>
                        ))}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {serviceCardTable.getRowModel().rows?.length ? (
                      serviceCardTable.getRowModel().rows.map((row) => (
                        <TableRow key={row.id}>
                          {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow><TableCell colSpan={serviceCardColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Schedule Tab */}
        <TabsContent value="schedule" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><Clock className="h-5 w-5" />Jadwal Praktik</CardTitle>
              <Button onClick={() => openCreateDialog('scheduleRow')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {scheduleRowTable.getHeaderGroups().map((hg) => (
                      <TableRow key={hg.id}>
                        {hg.headers.map((h) => (
                          <TableHead key={h.id}>{h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}</TableHead>
                        ))}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {scheduleRowTable.getRowModel().rows?.length ? (
                      scheduleRowTable.getRowModel().rows.map((row) => (
                        <TableRow key={row.id}>
                          {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow><TableCell colSpan={scheduleRowColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Custom Sections Tab */}
        <TabsContent value="custom" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><Puzzle className="h-5 w-5" />Custom Sections</CardTitle>
              <Button onClick={() => openCreateDialog('customSection')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah Section</Button>
            </CardHeader>
            <CardContent className="space-y-4">
              {/* Custom Sections Table */}
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {customSectionTable.getHeaderGroups().map((hg) => (
                      <TableRow key={hg.id}>
                        {hg.headers.map((h) => (
                          <TableHead key={h.id}>{h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}</TableHead>
                        ))}
                      </TableRow>
                    ))}
                  </TableHeader>
                  <TableBody>
                    {customSectionTable.getRowModel().rows?.length ? (
                      customSectionTable.getRowModel().rows.map((row) => (
                        <TableRow key={row.id}>
                          {row.getVisibleCells().map((cell) => (
                            <TableCell key={cell.id}>{flexRender(cell.column.columnDef.cell, cell.getContext())}</TableCell>
                          ))}
                        </TableRow>
                      ))
                    ) : (
                      <TableRow><TableCell colSpan={customSectionColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>

              {/* Expandable Section Items */}
              {content?.customSections?.map((section) => (
                <Card key={section.id} className="border-l-4 border-l-primary">
                  <CardHeader 
                    className="flex flex-row items-center justify-between cursor-pointer hover:bg-slate-50"
                    onClick={() => toggleSection(section.id)}
                  >
                    <div className="flex items-center gap-3">
                      {expandedSections.has(section.id) ? <ChevronDown className="h-4 w-4" /> : <ChevronRightIcon className="h-4 w-4" />}
                      <div>
                        <CardTitle className="text-base">{section.title}</CardTitle>
                        <p className="text-sm text-slate-500">{section.subtitle || 'Tidak ada subtitle'}</p>
                      </div>
                    </div>
                    <Badge variant="outline">{section.items?.length || 0} items</Badge>
                  </CardHeader>
                  {expandedSections.has(section.id) && (
                    <CardContent className="space-y-4">
                      <div className="flex justify-end">
                        <Button size="sm" onClick={() => openCreateDialog('customItem', section.id)}>
                          <Plus className="h-4 w-4 mr-2" />Tambah Item
                        </Button>
                      </div>
                      {section.items && section.items.length > 0 ? (
                        <div className="rounded-md border">
                          <Table>
                            <TableHeader>
                              <TableRow>
                                <TableHead>Judul</TableHead>
                                <TableHead>Deskripsi</TableHead>
                                <TableHead>Urutan</TableHead>
                                <TableHead>Aksi</TableHead>
                              </TableRow>
                            </TableHeader>
                            <TableBody>
                              {section.items.map((item) => (
                                <TableRow key={item.id}>
                                  <TableCell className="font-medium">{item.title}</TableCell>
                                  <TableCell className="text-sm text-slate-600 truncate max-w-xs">{item.description || '-'}</TableCell>
                                  <TableCell>{item.order}</TableCell>
                                  <TableCell>
                                    <DropdownMenu>
                                      <DropdownMenuTrigger><Button variant="ghost" size="icon"><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
                                      <DropdownMenuContent align="end">
                                        <DropdownMenuItem onClick={() => openEditDialog('customItem', item, section.id)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
                                        <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('customItem'); setItemToDelete(item); setSelectedSectionId(section.id); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
                                      </DropdownMenuContent>
                                    </DropdownMenu>
                                  </TableCell>
                                </TableRow>
                              ))}
                            </TableBody>
                          </Table>
                        </div>
                      ) : (
                        <p className="text-center text-slate-500 py-4">Belum ada item di section ini</p>
                      )}
                    </CardContent>
                  )}
                </Card>
              ))}
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Create/Edit Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>
              {editingItem ? "Edit" : "Tambah"} {
                dialogType === 'highlight' ? 'Highlight' :
                dialogType === 'serviceChip' ? 'Service Chip' :
                dialogType === 'serviceCard' ? 'Service Card' :
                dialogType === 'scheduleRow' ? 'Jadwal' :
                dialogType === 'customSection' ? 'Custom Section' : 'Custom Item'
              }
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Highlight Form */}
            {dialogType === 'highlight' && (
              <div className="space-y-2">
                <Label>Teks *</Label>
                <Input value={highlightForm.text} onChange={(e) => setHighlightForm({ ...highlightForm, text: e.target.value })} required />
              </div>
            )}

            {/* Service Chip Form */}
            {dialogType === 'serviceChip' && (
              <div className="space-y-2">
                <Label>Label *</Label>
                <Input value={serviceChipForm.label} onChange={(e) => setServiceChipForm({ ...serviceChipForm, label: e.target.value })} required />
              </div>
            )}

            {/* Service Card Form */}
            {dialogType === 'serviceCard' && (
              <>
                <div className="space-y-2">
                  <Label>Judul *</Label>
                  <Input value={serviceCardForm.title} onChange={(e) => setServiceCardForm({ ...serviceCardForm, title: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label>Deskripsi</Label>
                  <Textarea value={serviceCardForm.description} onChange={(e) => setServiceCardForm({ ...serviceCardForm, description: e.target.value })} rows={2} />
                </div>
                <div className="space-y-2">
                  <Label>Icon (Lucide icon name)</Label>
                  <Input value={serviceCardForm.icon} onChange={(e) => setServiceCardForm({ ...serviceCardForm, icon: e.target.value })} placeholder="Stethoscope, Heart, etc" />
                </div>
                <div className="space-y-2">
                  <Label>URL Gambar</Label>
                  <Input value={serviceCardForm.imageUrl} onChange={(e) => setServiceCardForm({ ...serviceCardForm, imageUrl: e.target.value })} placeholder="https://..." />
                </div>
              </>
            )}

            {/* Schedule Row Form */}
            {dialogType === 'scheduleRow' && (
              <>
                <div className="space-y-2">
                  <Label>Hari *</Label>
                  <Input value={scheduleRowForm.day} onChange={(e) => setScheduleRowForm({ ...scheduleRowForm, day: e.target.value })} placeholder="Senin - Jumat" required />
                </div>
                <div className="space-y-2">
                  <Label>Jam *</Label>
                  <Input value={scheduleRowForm.hoursText} onChange={(e) => setScheduleRowForm({ ...scheduleRowForm, hoursText: e.target.value })} placeholder="08:00 - 16:00" required />
                </div>
              </>
            )}

            {/* Custom Section Form */}
            {dialogType === 'customSection' && (
              <>
                <div className="space-y-2">
                  <Label>Tipe *</Label>
                  <Select value={customSectionForm.type} onValueChange={(val) => setCustomSectionForm({ ...customSectionForm, type: val as 'GENERIC' | 'KB_METHODS' })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="GENERIC">Generic</SelectItem>
                      <SelectItem value="KB_METHODS">KB Methods</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <Label>Judul *</Label>
                  <Input value={customSectionForm.title} onChange={(e) => setCustomSectionForm({ ...customSectionForm, title: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label>Subtitle</Label>
                  <Input value={customSectionForm.subtitle} onChange={(e) => setCustomSectionForm({ ...customSectionForm, subtitle: e.target.value })} />
                </div>
                <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label>CTA Label</Label>
                    <Input value={customSectionForm.ctaLabel} onChange={(e) => setCustomSectionForm({ ...customSectionForm, ctaLabel: e.target.value })} placeholder="Pelajari Lebih" />
                  </div>
                  <div className="space-y-2">
                    <Label>CTA URL</Label>
                    <Input value={customSectionForm.ctaUrl} onChange={(e) => setCustomSectionForm({ ...customSectionForm, ctaUrl: e.target.value })} placeholder="/link" />
                  </div>
                </div>
              </>
            )}

            {/* Custom Item Form */}
            {dialogType === 'customItem' && (
              <>
                <div className="space-y-2">
                  <Label>Judul *</Label>
                  <Input value={customItemForm.title} onChange={(e) => setCustomItemForm({ ...customItemForm, title: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label>Deskripsi</Label>
                  <Textarea value={customItemForm.description} onChange={(e) => setCustomItemForm({ ...customItemForm, description: e.target.value })} rows={2} />
                </div>
                <div className="space-y-2">
                  <Label>URL Gambar</Label>
                  <Input value={customItemForm.imageUrl} onChange={(e) => setCustomItemForm({ ...customItemForm, imageUrl: e.target.value })} placeholder="https://..." />
                </div>
              </>
            )}

            {/* Order Field (for all types) */}
            {dialogType && dialogType !== 'customItem' && (
              <div className="space-y-2">
                <Label>Urutan</Label>
                <Input 
                  type="number" 
                  value={
                    dialogType === 'highlight' ? highlightForm.order :
                    dialogType === 'serviceChip' ? serviceChipForm.order :
                    dialogType === 'serviceCard' ? serviceCardForm.order :
                    dialogType === 'scheduleRow' ? scheduleRowForm.order :
                    customSectionForm.order
                  } 
                  onChange={(e) => {
                    const val = parseInt(e.target.value) || 0;
                    if (dialogType === 'highlight') setHighlightForm({ ...highlightForm, order: val });
                    else if (dialogType === 'serviceChip') setServiceChipForm({ ...serviceChipForm, order: val });
                    else if (dialogType === 'serviceCard') setServiceCardForm({ ...serviceCardForm, order: val });
                    else if (dialogType === 'scheduleRow') setScheduleRowForm({ ...scheduleRowForm, order: val });
                    else if (dialogType === 'customSection') setCustomSectionForm({ ...customSectionForm, order: val });
                  }} 
                  min={0} 
                />
              </div>
            )}
            {dialogType === 'customItem' && (
              <div className="space-y-2">
                <Label>Urutan</Label>
                <Input type="number" value={customItemForm.order} onChange={(e) => setCustomItemForm({ ...customItemForm, order: parseInt(e.target.value) || 0 })} min={0} />
              </div>
            )}

            <DialogFooter>
              <Button type="button" variant="outline" onClick={() => setIsDialogOpen(false)}>Batal</Button>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {editingItem ? "Simpan" : "Tambah"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Hapus {
              dialogType === 'highlight' ? 'Highlight' :
              dialogType === 'serviceChip' ? 'Service Chip' :
              dialogType === 'serviceCard' ? 'Service Card' :
              dialogType === 'scheduleRow' ? 'Jadwal' :
              dialogType === 'customSection' ? 'Custom Section' : 'Custom Item'
            }</AlertDialogTitle>
            <AlertDialogDescription>Yakin ingin menghapus "{itemToDelete?.text || itemToDelete?.label || itemToDelete?.title || itemToDelete?.day}"?</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Batal</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-red-600 hover:bg-red-700">Hapus</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default PoliLandingAdminPage;
