"use client";

import { useState } 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 {
  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 { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import AdminSunatRacingService from "@/services/admin.sunat-racing.service";
import type { SunatRacingContent } from "@/services/sunat-racing.service";
import {
  Plus,
  Save,
  MoreHorizontal,
  Edit,
  Trash,
  ChevronLeft,
  ChevronRight,
  Loader2,
  Trophy,
  Footprints,
  HelpCircle,
  ImageIcon,
} from "lucide-react";

interface AdvantageFormData {
  title: string;
  description: string;
  icon: string;
  order: number;
  slug: string;
  detailTitle: string;
  detailImageUrl: string;
  detailItems: string;
}

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

interface FaqFormData {
  question: string;
  answer: string;
  order: number;
}

const SunatRacingAdminPage = () => {
  const [activeTab, setActiveTab] = useState("hero");
  const [sorting, setSorting] = useState<SortingState>([]);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [dialogType, setDialogType] = useState<'advantage' | 'step' | 'faq' | null>(null);
  const [editingItem, setEditingItem] = useState<any>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [itemToDelete, setItemToDelete] = useState<any>(null);

  const { data: content, isLoading, mutate } = useSWR<SunatRacingContent>(
    "/admin/sunat-racing",
    () => AdminSunatRacingService.getAdminContent()
  );

  // Hero Form
  const [heroForm, setHeroForm] = useState({
    title: "",
    subtitle: "",
    imageUrl: "",
    primaryCtaLabel: "",
    primaryCtaLink: "",
    secondaryCtaLabel: "",
    secondaryCtaLink: "",
  });

  // Page Content Form
  const [pageForm, setPageForm] = useState({
    advantageSectionTitle: "",
    advantageSectionSubtitle: "",
    aftercareSectionTitle: "",
    aftercareSectionSubtitle: "",
    doctorSectionTitle: "",
    doctorSectionSubtitle: "",
    newsSectionTitle: "",
    newsSectionSubtitle: "",
    faqSectionTitle: "",
    faqSectionSubtitle: "",
  });

  // Forms for CRUD
  const [advantageForm, setAdvantageForm] = useState<AdvantageFormData>({
    title: "", description: "", icon: "", order: 0,
    slug: "", detailTitle: "", detailImageUrl: "", detailItems: ""
  });
  const [stepForm, setStepForm] = useState<StepFormData>({
    title: "", description: "", imageUrl: "", order: 0
  });
  const [faqForm, setFaqForm] = useState<FaqFormData>({
    question: "", answer: "", order: 0
  });

  const handleSaveHero = async () => {
    setIsSubmitting(true);
    try {
      await AdminSunatRacingService.updateHero(heroForm);
      toast.success("Hero berhasil diperbarui");
      mutate();
    } catch (error) {
      toast.error("Gagal memperbarui hero");
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleSavePageContent = async () => {
    setIsSubmitting(true);
    try {
      await AdminSunatRacingService.updatePageContent(pageForm);
      toast.success("Konten halaman berhasil diperbarui");
      mutate();
    } catch (error) {
      toast.error("Gagal memperbarui konten");
    } finally {
      setIsSubmitting(false);
    }
  };

  const openCreateDialog = (type: 'advantage' | 'step' | 'faq') => {
    setDialogType(type);
    setEditingItem(null);
    if (type === 'advantage') {
      setAdvantageForm({ title: "", description: "", icon: "", order: content?.advantages?.length || 0, slug: "", detailTitle: "", detailImageUrl: "", detailItems: "" });
    } else if (type === 'step') {
      setStepForm({ title: "", description: "", imageUrl: "", order: content?.steps?.length || 0 });
    } else {
      setFaqForm({ question: "", answer: "", order: content?.faqs?.length || 0 });
    }
    setIsDialogOpen(true);
  };

  const openEditDialog = (type: 'advantage' | 'step' | 'faq', item: any) => {
    setDialogType(type);
    setEditingItem(item);
    if (type === 'advantage') {
      setAdvantageForm({
        title: item.title,
        description: item.description,
        icon: item.icon || "",
        order: item.order,
        slug: item.slug || "",
        detailTitle: item.detailTitle || "",
        detailImageUrl: item.detailImageUrl || "",
        detailItems: item.detailItems?.join("\n") || ""
      });
    } else if (type === 'step') {
      setStepForm({
        title: item.title,
        description: item.description,
        imageUrl: item.imageUrl || "",
        order: item.order
      });
    } else {
      setFaqForm({
        question: item.question,
        answer: item.answer,
        order: item.order
      });
    }
    setIsDialogOpen(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSubmitting(true);
    try {
      if (dialogType === 'advantage') {
        const data = { ...advantageForm, detailItems: advantageForm.detailItems.split("\n").filter(Boolean) };
        if (editingItem) {
          await AdminSunatRacingService.updateAdvantage(editingItem.id, data);
        } else {
          await AdminSunatRacingService.createAdvantage(data);
        }
      } else if (dialogType === 'step') {
        if (editingItem) {
          await AdminSunatRacingService.updateStep(editingItem.id, stepForm);
        } else {
          await AdminSunatRacingService.createStep(stepForm);
        }
      } else if (dialogType === 'faq') {
        if (editingItem) {
          await AdminSunatRacingService.updateFaq(editingItem.id, faqForm);
        } else {
          await AdminSunatRacingService.createFaq(faqForm);
        }
      }
      toast.success(`${dialogType === 'advantage' ? 'Keunggulan' : dialogType === 'step' ? 'Langkah' : 'FAQ'} 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 === 'advantage') {
        await AdminSunatRacingService.deleteAdvantage(itemToDelete.id);
      } else if (dialogType === 'step') {
        await AdminSunatRacingService.deleteStep(itemToDelete.id);
      } else if (dialogType === 'faq') {
        await AdminSunatRacingService.deleteFaq(itemToDelete.id);
      }
      toast.success("Berhasil dihapus");
      mutate();
    } catch (error) {
      toast.error("Gagal menghapus");
    } finally {
      setDeleteDialogOpen(false);
      setItemToDelete(null);
    }
  };

  // Columns for tables
  const advantageColumns: ColumnDef<SunatRacingContent['advantages'][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: "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('advantage', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('advantage'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const stepColumns: ColumnDef<SunatRacingContent['steps'][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: "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('step', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('step'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

  const faqColumns: ColumnDef<SunatRacingContent['faqs'][0]>[] = [
    { accessorKey: "question", header: "Pertanyaan", cell: ({ row }) => <span className="font-medium">{row.original.question}</span> },
    { accessorKey: "answer", header: "Jawaban", cell: ({ row }) => <span className="text-sm text-slate-600 truncate max-w-xs">{row.original.answer}</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('faq', row.original)}><Edit className="h-4 w-4 mr-2" />Edit</DropdownMenuItem>
            <DropdownMenuItem className="text-red-600" onClick={() => { setDialogType('faq'); setItemToDelete(row.original); setDeleteDialogOpen(true); }}><Trash className="h-4 w-4 mr-2" />Hapus</DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
      ),
    },
  ];

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

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

  const faqTable = useReactTable({
    data: content?.faqs || [],
    columns: faqColumns,
    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">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900">Kelola Sunat Racing</h1>
          <p className="text-slate-500">Edit konten landing page Sunat Racing</p>
        </div>
      </div>

      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="hero">Hero</TabsTrigger>
          <TabsTrigger value="content">Konten</TabsTrigger>
          <TabsTrigger value="advantages">Keunggulan ({content?.advantages?.length || 0})</TabsTrigger>
          <TabsTrigger value="steps">Langkah ({content?.steps?.length || 0})</TabsTrigger>
          <TabsTrigger value="faqs">FAQ ({content?.faqs?.length || 0})</TabsTrigger>
        </TabsList>

        {/* Hero Tab */}
        <TabsContent value="hero" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>Hero Section</CardTitle>
              <Button onClick={handleSaveHero} 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-4">
              <div className="space-y-2">
                <Label>Judul</Label>
                <Input value={heroForm.title} onChange={(e) => setHeroForm({ ...heroForm, title: e.target.value })} placeholder="Sunat Racing" />
              </div>
              <div className="space-y-2">
                <Label>Subtitle</Label>
                <Textarea value={heroForm.subtitle} onChange={(e) => setHeroForm({ ...heroForm, subtitle: e.target.value })} placeholder="Deskripsi..." rows={2} />
              </div>
              <div className="space-y-2">
                <Label>URL Gambar</Label>
                <Input value={heroForm.imageUrl} onChange={(e) => setHeroForm({ ...heroForm, imageUrl: 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={heroForm.primaryCtaLabel} onChange={(e) => setHeroForm({ ...heroForm, primaryCtaLabel: e.target.value })} placeholder="Daftar Sekarang" />
                </div>
                <div className="space-y-2">
                  <Label>Link CTA Primary</Label>
                  <Input value={heroForm.primaryCtaLink} onChange={(e) => setHeroForm({ ...heroForm, primaryCtaLink: e.target.value })} placeholder="/sunat-racing/paket" />
                </div>
              </div>
              <div className="grid grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label>Label CTA Secondary</Label>
                  <Input value={heroForm.secondaryCtaLabel} onChange={(e) => setHeroForm({ ...heroForm, secondaryCtaLabel: e.target.value })} placeholder="Pelajari Lebih" />
                </div>
                <div className="space-y-2">
                  <Label>Link CTA Secondary</Label>
                  <Input value={heroForm.secondaryCtaLink} onChange={(e) => setHeroForm({ ...heroForm, secondaryCtaLink: e.target.value })} placeholder="#keunggulan" />
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Page Content Tab */}
        <TabsContent value="content" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle>Section Titles</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-4">
              <div className="space-y-2">
                <Label>Judul Section Keunggulan</Label>
                <Input value={pageForm.advantageSectionTitle} onChange={(e) => setPageForm({ ...pageForm, advantageSectionTitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Subtitle Section Keunggulan</Label>
                <Input value={pageForm.advantageSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, advantageSectionSubtitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Judul Section Pasca</Label>
                <Input value={pageForm.aftercareSectionTitle} onChange={(e) => setPageForm({ ...pageForm, aftercareSectionTitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Subtitle Section Pasca</Label>
                <Input value={pageForm.aftercareSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, aftercareSectionSubtitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Judul Section Dokter</Label>
                <Input value={pageForm.doctorSectionTitle} onChange={(e) => setPageForm({ ...pageForm, doctorSectionTitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Subtitle Section Dokter</Label>
                <Input value={pageForm.doctorSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, doctorSectionSubtitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Judul Section FAQ</Label>
                <Input value={pageForm.faqSectionTitle} onChange={(e) => setPageForm({ ...pageForm, faqSectionTitle: e.target.value })} />
              </div>
              <div className="space-y-2">
                <Label>Subtitle Section FAQ</Label>
                <Input value={pageForm.faqSectionSubtitle} onChange={(e) => setPageForm({ ...pageForm, faqSectionSubtitle: e.target.value })} />
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Advantages Tab */}
        <TabsContent value="advantages" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><Trophy className="h-5 w-5" />Keunggulan</CardTitle>
              <Button onClick={() => openCreateDialog('advantage')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {advantageTable.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>
                    {advantageTable.getRowModel().rows?.length ? (
                      advantageTable.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={advantageColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Steps Tab */}
        <TabsContent value="steps" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><Footprints className="h-5 w-5" />Langkah</CardTitle>
              <Button onClick={() => openCreateDialog('step')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {stepTable.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>
                    {stepTable.getRowModel().rows?.length ? (
                      stepTable.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={stepColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* FAQs Tab */}
        <TabsContent value="faqs" className="space-y-4">
          <Card>
            <CardHeader className="flex flex-row items-center justify-between">
              <CardTitle className="flex items-center gap-2"><HelpCircle className="h-5 w-5" />FAQ</CardTitle>
              <Button onClick={() => openCreateDialog('faq')} size="sm"><Plus className="h-4 w-4 mr-2" />Tambah</Button>
            </CardHeader>
            <CardContent>
              <div className="rounded-md border">
                <Table>
                  <TableHeader>
                    {faqTable.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>
                    {faqTable.getRowModel().rows?.length ? (
                      faqTable.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={faqColumns.length} className="h-24 text-center">Tidak ada data.</TableCell></TableRow>
                    )}
                  </TableBody>
                </Table>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>

      {/* Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>
              {editingItem ? "Edit" : "Tambah"} {dialogType === 'advantage' ? 'Keunggulan' : dialogType === 'step' ? 'Langkah' : 'FAQ'}
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit} className="space-y-4">
            {dialogType === 'advantage' && (
              <>
                <div className="space-y-2">
                  <Label>Judul *</Label>
                  <Input value={advantageForm.title} onChange={(e) => setAdvantageForm({ ...advantageForm, title: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label>Deskripsi *</Label>
                  <Textarea value={advantageForm.description} onChange={(e) => setAdvantageForm({ ...advantageForm, description: e.target.value })} required rows={3} />
                </div>
                <div className="space-y-2">
                  <Label>Icon</Label>
                  <Input value={advantageForm.icon} onChange={(e) => setAdvantageForm({ ...advantageForm, icon: e.target.value })} placeholder="check, star, shield, dll" />
                </div>
                <div className="space-y-2">
                  <Label>Slug (URL)</Label>
                  <Input value={advantageForm.slug} onChange={(e) => setAdvantageForm({ ...advantageForm, slug: e.target.value })} placeholder="modern-minim-sakit" />
                </div>
                <div className="space-y-2">
                  <Label>Detail Title</Label>
                  <Input value={advantageForm.detailTitle} onChange={(e) => setAdvantageForm({ ...advantageForm, detailTitle: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>Detail Image URL</Label>
                  <Input value={advantageForm.detailImageUrl} onChange={(e) => setAdvantageForm({ ...advantageForm, detailImageUrl: e.target.value })} />
                </div>
                <div className="space-y-2">
                  <Label>Detail Items (satu per baris)</Label>
                  <Textarea value={advantageForm.detailItems} onChange={(e) => setAdvantageForm({ ...advantageForm, detailItems: e.target.value })} rows={4} />
                </div>
              </>
            )}
            {dialogType === 'step' && (
              <>
                <div className="space-y-2">
                  <Label>Judul *</Label>
                  <Input value={stepForm.title} onChange={(e) => setStepForm({ ...stepForm, title: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label>Deskripsi *</Label>
                  <Textarea value={stepForm.description} onChange={(e) => setStepForm({ ...stepForm, description: e.target.value })} required rows={3} />
                </div>
                <div className="space-y-2">
                  <Label>URL Gambar</Label>
                  <Input value={stepForm.imageUrl} onChange={(e) => setStepForm({ ...stepForm, imageUrl: e.target.value })} />
                </div>
              </>
            )}
            {dialogType === 'faq' && (
              <>
                <div className="space-y-2">
                  <Label>Pertanyaan *</Label>
                  <Input value={faqForm.question} onChange={(e) => setFaqForm({ ...faqForm, question: e.target.value })} required />
                </div>
                <div className="space-y-2">
                  <Label>Jawaban *</Label>
                  <Textarea value={faqForm.answer} onChange={(e) => setFaqForm({ ...faqForm, answer: e.target.value })} required rows={4} />
                </div>
              </>
            )}
            <div className="space-y-2">
              <Label>Urutan</Label>
              <Input type="number" value={dialogType === 'advantage' ? advantageForm.order : dialogType === 'step' ? stepForm.order : faqForm.order} onChange={(e) => {
                const val = parseInt(e.target.value) || 0;
                if (dialogType === 'advantage') setAdvantageForm({ ...advantageForm, order: val });
                else if (dialogType === 'step') setStepForm({ ...stepForm, order: val });
                else setFaqForm({ ...faqForm, order: val });
              }} 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 === 'advantage' ? 'Keunggulan' : dialogType === 'step' ? 'Langkah' : 'FAQ'}</AlertDialogTitle>
            <AlertDialogDescription>Yakin ingin menghapus "{itemToDelete?.title || itemToDelete?.question}"?</AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Batal</AlertDialogCancel>
            <AlertDialogAction onClick={handleDelete} className="bg-red-600">Hapus</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
};

export default SunatRacingAdminPage;
