"use client";

import { useEffect, useState } from "react";
import ArticleTable from "@/components/table/article-table";
import { Button } from "@/components/ui/button";
import { Plus } from "lucide-react";
import { BannerDialog } from "@/components/form/banner-dialog";
import { createBanner } from "@/service/banner";
import router from "next/router";
import { useRouter } from "next/navigation";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import Cookies from "js-cookie";

export default function BasicPage() {
  const [openDialog, setOpenDialog] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);
  const [userRoleId, setUserRoleId] = useState<string | null>(null);

  const router = useRouter();
  const MySwal = withReactContent(Swal);

  // 🔹 Ambil userlevelId dari cookies
  useEffect(() => {
    const ulne = Cookies.get("urie"); // contoh: "3"
    setUserRoleId(ulne ?? null);
  }, []);

  const handleSubmitBanner = async (formData: FormData) => {
    try {
      const response = await createBanner(formData);
      console.log("Banner created:", response);
    } catch (error) {
      console.error("Error creating banner:", error);
    }
  };

  const successSubmit = () => {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        setRefreshKey((prev) => prev + 1); // ⬅️ trigger refresh
      }
    });
  };

  return (
    <div>
      <div className="overflow-x-hidden overflow-y-scroll w-full">
        <div className="px-2 md:px-4 md:py-4 w-full">
          <div className="pl-3">
            <h1 className="text-[#1F6779] text-2xl font-semibold">Banner</h1>
            <p>Kelola gambar banner yang tampil di halaman Utama website</p>
          </div>

          <div className="dark:bg-[#18181b] rounded-xl p-3">
            {userRoleId !== "1" && (
              <Button
                className="bg-[#1F6779] text-white w-full lg:w-fit hover:bg-[#1a9bb5] flex items-center gap-2"
                onClick={() => setOpenDialog(true)}
              >
                <Plus className="h-4 w-4" />
                Tambah Banner
              </Button>
            )}

            <ArticleTable />
          </div>
        </div>
      </div>

      {/* Dialog Tambah Banner */}
      <BannerDialog
        open={openDialog}
        onOpenChange={setOpenDialog}
        onSubmit={handleSubmitBanner}
        onSuccess={successSubmit}
      />
    </div>
  );
}
