"use client";

import {
  FormEvent,
  useEffect,
  useState,
} from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";

type ArticleImage = {
  id: number;
  image: string;
  articleId: number;
  createdAt: string;
};

type Article = {
  id: number;
  title: string;
  slug: string;
  excerpt: string | null;
  content: string;
  thumbnail: string | null;
  category: string | null;
  published: boolean;
  publishedAt: string | null;
  articleimage: ArticleImage[];
};

export default function EditArticlePage() {
  const router = useRouter();
  const params = useParams();

  const id = params.id as string;

  const [form, setForm] = useState({
    title: "",
    slug: "",
    excerpt: "",
    content: "",
    thumbnail: "",
    category: "",
    published: false,
    publishedAt: "",
  });

  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [deletingImageId, setDeletingImageId] =
    useState<number | null>(null);

  const [sidebarOpen, setSidebarOpen] = useState(false);

  // ======================
  // GAMBAR LAMA
  // ======================

  const [images, setImages] = useState<ArticleImage[]>(
    []
  );

  // ======================
  // GAMBAR BARU
  // ======================

  const [newImages, setNewImages] = useState<File[]>([]);

  const [newPreviews, setNewPreviews] = useState<
    string[]
  >([]);

  // ======================
  // GET ARTICLE
  // ======================

  useEffect(() => {
    const getArticle = async () => {
      try {
        const response = await fetch(
          `/api/articles/${id}`
        );

        const result = await response.json();

        if (!response.ok || !result.success) {
          alert(
            result.message ||
              "Gagal mengambil data Article"
          );
          return;
        }

        const article: Article = result.data;

        setForm({
          title: article.title || "",
          slug: article.slug || "",
          excerpt: article.excerpt || "",
          content: article.content || "",
          thumbnail: article.thumbnail || "",
          category: article.category || "",
          published: article.published,
          publishedAt: article.publishedAt
            ? article.publishedAt.substring(0, 10)
            : "",
        });

        setImages(article.articleimage || []);
      } catch (error) {
        console.error(
          "GET ARTICLE BY ID ERROR:",
          error
        );

        alert("Gagal mengambil data Article");
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      getArticle();
    }
  }, [id]);

  // ======================
  // FORM CHANGE
  // ======================

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement
    >
  ) => {
    const { name, value, type } = e.target;

    setForm((previous) => ({
      ...previous,
      [name]:
        type === "checkbox"
          ? (e.target as HTMLInputElement).checked
          : value,
    }));
  };

  // ======================
  // SELECT GAMBAR BARU
  // ======================

  const handleNewImagesChange = (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = Array.from(e.target.files || []);

    if (files.length === 0) {
      return;
    }

    const imageFiles = files.filter((file) =>
      file.type.startsWith("image/")
    );

    if (imageFiles.length === 0) {
      alert("File yang dipilih bukan gambar");
      return;
    }

    setNewImages((previous) => [
      ...previous,
      ...imageFiles,
    ]);

    const previews = imageFiles.map((file) =>
      URL.createObjectURL(file)
    );

    setNewPreviews((previous) => [
      ...previous,
      ...previews,
    ]);

    e.target.value = "";
  };

  // ======================
  // REMOVE GAMBAR BARU
  // ======================

  const removeNewImage = (index: number) => {
    const preview = newPreviews[index];

    if (preview) {
      URL.revokeObjectURL(preview);
    }

    setNewImages((previous) =>
      previous.filter(
        (_, imageIndex) => imageIndex !== index
      )
    );

    setNewPreviews((previous) =>
      previous.filter(
        (_, imageIndex) => imageIndex !== index
      )
    );
  };

  // ======================
  // DELETE GAMBAR LAMA
  // ======================

  const handleDeleteImage = async (
    imageId: number
  ) => {
    const confirmed = window.confirm(
      "Apakah Anda yakin ingin menghapus gambar ini?"
    );

    if (!confirmed) {
      return;
    }

    setDeletingImageId(imageId);

    try {
      const response = await fetch(
        `/api/articles/images/${imageId}`,
        {
          method: "DELETE",
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Gagal menghapus gambar"
        );
      }

      setImages((previous) =>
        previous.filter(
          (image) => image.id !== imageId
        )
      );

      alert("Gambar Article berhasil dihapus");
    } catch (error) {
      console.error(
        "DELETE ARTICLE IMAGE ERROR:",
        error
      );

      alert(
        error instanceof Error
          ? error.message
          : "Gagal menghapus gambar"
      );
    } finally {
      setDeletingImageId(null);
    }
  };

  // ======================
  // UPLOAD GAMBAR BARU
  // ======================

  const uploadNewImages = async () => {
    if (newImages.length === 0) {
      return [];
    }

    const formData = new FormData();

    newImages.forEach((file) => {
      formData.append("files", file);
    });

    setUploading(true);

    try {
      const response = await fetch(
        "/api/articles/upload",
        {
          method: "POST",
          body: formData,
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Gagal mengupload gambar baru"
        );
      }

      return result.data as string[];
    } finally {
      setUploading(false);
    }
  };

  // ======================
  // SUBMIT
  // ======================

  const handleSubmit = async (
    e: FormEvent
  ) => {
    e.preventDefault();

    if (!form.title.trim()) {
      alert("Judul Article wajib diisi");
      return;
    }

    if (!form.slug.trim()) {
      alert("Slug Article wajib diisi");
      return;
    }

    if (!form.content.trim()) {
      alert("Content Article wajib diisi");
      return;
    }

    setSaving(true);

    try {
      const uploadedImages =
        await uploadNewImages();

      const response = await fetch(
        `/api/articles/${id}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            title: form.title.trim(),

            slug: form.slug.trim(),

            excerpt:
              form.excerpt.trim() || null,

            content: form.content.trim(),

            thumbnail:
              form.thumbnail.trim() || null,

            category:
              form.category.trim() || null,

            published: form.published,

            publishedAt:
              form.publishedAt || null,

            images: uploadedImages,
          }),
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Gagal memperbarui Article"
        );
      }

      alert("Article berhasil diperbarui");

      router.push("/secure-panel/articles");
      router.refresh();
    } catch (error) {
      console.error(
        "UPDATE ARTICLE ERROR:",
        error
      );

      alert(
        error instanceof Error
          ? error.message
          : "Gagal memperbarui Article"
      );
    } finally {
      setSaving(false);
    }
  };

  // ======================
  // LOADING
  // ======================

  if (loading) {
    return (
      <>
        <style>{`
          * {
            box-sizing: border-box;
          }

          .admin-loading-page {
            min-height: 100vh;
            background: #f5f7f9;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 30px;
          }

          .admin-loading-box {
            text-align: center;
          }

          .loading-spinner {
            width: 42px;
            height: 42px;
            border: 3px solid #dcefe4;
            border-top-color: #198754;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            margin: 0 auto 15px;
          }

          .admin-loading-box h5 {
            font-size: 15px;
            font-weight: 700;
            color: #344054;
            margin-bottom: 5px;
          }

          .admin-loading-box p {
            color: #98a2b3;
            font-size: 12px;
            margin: 0;
          }

          @keyframes spin {
            to {
              transform: rotate(360deg);
            }
          }
        `}</style>

        <main className="admin-loading-page">
          <div className="admin-loading-box">
            <div className="loading-spinner"></div>

            <h5>Memuat data Article</h5>

            <p>
              Sedang mengambil informasi dari
              database...
            </p>
          </div>
        </main>
      </>
    );
  }

  return (
    <>
      <style>{`
        * {
          box-sizing: border-box;
        }

        html,
        body {
          margin: 0;
          padding: 0;
        }

        .admin-layout {
          min-height: 100vh;
          background: #f5f7f9;
          color: #1f2937;
        }

        /* =========================
           SIDEBAR
        ========================= */

        .admin-sidebar {
          position: fixed;
          top: 0;
          left: 0;
          width: 260px;
          height: 100vh;
          background: #ffffff;
          border-right: 1px solid #e9ecef;
          z-index: 1050;
          transition: transform 0.3s ease;
          overflow-y: auto;
        }

        .sidebar-inner {
          min-height: 100%;
          display: flex;
          flex-direction: column;
          padding: 22px 16px;
        }

        .sidebar-brand {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 4px 8px 24px;
          border-bottom: 1px solid #eef0f2;
        }

        .brand-icon {
          width: 42px;
          height: 42px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #198754;
          color: white;
          font-size: 19px;
          box-shadow: 0 8px 20px rgba(25, 135, 84, 0.18);
          flex-shrink: 0;
        }

        .brand-text {
          min-width: 0;
          line-height: 1.15;
        }

        .brand-text strong {
          display: block;
          font-size: 15px;
          font-weight: 700;
          color: #17202a;
        }

        .brand-text span {
          display: block;
          margin-top: 4px;
          font-size: 11px;
          color: #8a94a6;
          letter-spacing: 0.4px;
        }

        .sidebar-close {
          margin-left: auto;
          border: 0;
          background: transparent;
          color: #6c757d;
          font-size: 18px;
        }

        .sidebar-section-label {
          padding: 20px 10px 8px;
          font-size: 10px;
          font-weight: 700;
          color: #a0a8b3;
          letter-spacing: 1.1px;
        }

        .sidebar-nav {
          display: flex;
          flex-direction: column;
          gap: 3px;
        }

        .sidebar-link {
          display: flex;
          align-items: center;
          gap: 12px;
          min-height: 44px;
          padding: 9px 12px;
          border-radius: 10px;
          color: #667085;
          text-decoration: none;
          font-size: 13px;
          font-weight: 500;
          transition:
            background 0.2s ease,
            color 0.2s ease,
            transform 0.2s ease;
        }

        .sidebar-link:hover {
          background: #f0f9f4;
          color: #198754;
          transform: translateX(2px);
        }

        .sidebar-link.active {
          background: #e9f7ef;
          color: #198754;
          font-weight: 600;
        }

        .sidebar-link-icon {
          width: 20px;
          display: flex;
          justify-content: center;
          font-size: 16px;
          flex-shrink: 0;
        }

        .sidebar-bottom {
          margin-top: auto;
          padding-top: 20px;
          border-top: 1px solid #eef0f2;
        }

        .sidebar-website {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 11px 12px;
          border-radius: 10px;
          color: #667085;
          text-decoration: none;
          font-size: 13px;
          transition: all 0.2s ease;
        }

        .sidebar-website:hover {
          background: #f5f7f9;
          color: #198754;
        }

        /* =========================
           MAIN
        ========================= */

        .admin-main {
          margin-left: 260px;
          min-height: 100vh;
          width: calc(100% - 260px);
        }

        /* =========================
           TOPBAR
        ========================= */

        .admin-topbar {
          height: 76px;
          background: rgba(255, 255, 255, 0.96);
          border-bottom: 1px solid #e9ecef;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 0 32px;
          position: sticky;
          top: 0;
          z-index: 1000;
          backdrop-filter: blur(12px);
        }

        .topbar-left,
        .topbar-right {
          display: flex;
          align-items: center;
        }

        .topbar-left {
          gap: 14px;
        }

        .topbar-right {
          gap: 10px;
        }

        .mobile-menu-button {
          width: 40px;
          height: 40px;
          border: 1px solid #e5e7eb;
          background: #ffffff;
          color: #475467;
          border-radius: 9px;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 20px;
        }

        .topbar-label {
          font-size: 10px;
          font-weight: 700;
          color: #98a2b3;
          letter-spacing: 1px;
          margin-bottom: 2px;
        }

        .topbar-title {
          font-size: 15px;
          font-weight: 700;
          color: #1d2939;
        }

        .topbar-website,
        .topbar-logout {
          min-height: 40px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          padding: 8px 13px;
          border-radius: 9px;
          text-decoration: none;
          font-size: 13px;
          font-weight: 600;
          transition: all 0.2s ease;
          white-space: nowrap;
        }

        .topbar-website {
          color: #475467;
          border: 1px solid #e4e7ec;
          background: #ffffff;
        }

        .topbar-website:hover {
          color: #198754;
          border-color: #b7dfc9;
          background: #f4fbf7;
        }

        .topbar-logout {
          color: #dc3545;
          background: #fff5f5;
          border: 1px solid #ffd6d9;
        }

        .topbar-logout:hover {
          background: #dc3545;
          border-color: #dc3545;
          color: #ffffff;
        }

        /* =========================
           CONTENT
        ========================= */

        .admin-content {
          padding: 32px;
          max-width: 1600px;
          margin: 0 auto;
        }

        .page-heading {
          display: flex;
          align-items: flex-end;
          justify-content: space-between;
          gap: 25px;
          margin-bottom: 28px;
        }

        .page-heading-left {
          min-width: 0;
        }

        .back-dashboard {
          display: inline-flex;
          align-items: center;
          gap: 7px;
          color: #667085;
          text-decoration: none;
          font-size: 12px;
          font-weight: 600;
          margin-bottom: 17px;
          transition: color 0.2s ease;
        }

        .back-dashboard:hover {
          color: #198754;
        }

        .page-title-row {
          display: flex;
          align-items: center;
          gap: 14px;
        }

        .page-title-icon {
          width: 48px;
          height: 48px;
          border-radius: 13px;
          background: #e9f7ef;
          color: #198754;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 21px;
          flex-shrink: 0;
        }

        .page-eyebrow {
          color: #198754;
          font-size: 10px;
          font-weight: 700;
          letter-spacing: 1.2px;
          margin-bottom: 4px;
        }

        .page-title {
          margin: 0;
          font-size: clamp(24px, 3vw, 32px);
          line-height: 1.15;
          font-weight: 750;
          color: #101828;
        }

        .page-description {
          margin: 7px 0 0;
          color: #667085;
          font-size: 13px;
          line-height: 1.7;
          max-width: 680px;
          text-align: justify;
        }

        /* =========================
           FORM CARD
        ========================= */

        .form-card {
          background: #ffffff;
          border: 1px solid #eaecf0;
          border-radius: 16px;
          overflow: hidden;
          box-shadow: 0 3px 12px rgba(16, 24, 40, 0.035);
        }

        .form-card-header {
          padding: 21px 24px;
          border-bottom: 1px solid #eaecf0;
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 20px;
        }

        .form-card-eyebrow {
          font-size: 10px;
          font-weight: 700;
          color: #198754;
          letter-spacing: 1px;
          margin-bottom: 4px;
        }

        .form-card-title {
          font-size: 17px;
          font-weight: 750;
          color: #101828;
          margin: 0;
        }

        .form-card-description {
          margin: 5px 0 0;
          color: #667085;
          font-size: 12px;
          line-height: 1.65;
          text-align: justify;
        }

        .form-card-icon {
          width: 40px;
          height: 40px;
          flex-shrink: 0;
          border-radius: 10px;
          background: #e9f7ef;
          color: #198754;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 17px;
        }

        .form-card-body {
          padding: 26px 24px;
        }

        /* =========================
           FORM
        ========================= */

        .article-form {
          width: 100%;
        }

        .form-section {
          padding: 22px;
          border: 1px solid #edf0f2;
          border-radius: 14px;
          background: #ffffff;
          margin-bottom: 18px;
        }

        .form-section:last-child {
          margin-bottom: 0;
        }

        .form-section-header {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          margin-bottom: 20px;
          padding-bottom: 15px;
          border-bottom: 1px solid #eef0f2;
        }

        .form-section-icon {
          width: 38px;
          height: 38px;
          border-radius: 10px;
          flex-shrink: 0;
          background: #e9f7ef;
          color: #198754;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
        }

        .form-section-title {
          margin: 0;
          color: #101828;
          font-size: 15px;
          font-weight: 750;
        }

        .form-section-description {
          margin: 4px 0 0;
          color: #98a2b3;
          font-size: 11px;
          line-height: 1.65;
          text-align: justify;
        }

        .custom-label {
          display: block;
          margin-bottom: 7px;
          color: #344054;
          font-size: 12px;
          font-weight: 700;
        }

        .custom-input,
        .custom-textarea {
          display: block;
          width: 100%;
          border: 1px solid #d0d5dd;
          border-radius: 9px;
          background: #ffffff;
          color: #101828;
          font-size: 13px;
          line-height: 1.55;
          padding: 10px 12px;
          outline: none;
          transition:
            border-color 0.2s ease,
            box-shadow 0.2s ease,
            background 0.2s ease;
        }

        .custom-input {
          min-height: 43px;
        }

        .custom-textarea {
          resize: vertical;
          min-height: 100px;
        }

        .custom-textarea.content-area {
          min-height: 300px;
        }

        .custom-input:focus,
        .custom-textarea:focus {
          border-color: #198754;
          box-shadow: 0 0 0 3px rgba(25, 135, 84, 0.1);
        }

        .custom-input::placeholder,
        .custom-textarea::placeholder {
          color: #98a2b3;
        }

        .form-help {
          margin-top: 6px;
          color: #98a2b3;
          font-size: 10px;
          line-height: 1.6;
        }

        .text-content-justify {
          text-align: justify;
        }

        /* =========================
           EXISTING IMAGES
        ========================= */

        .image-grid {
          display: grid;
          grid-template-columns: repeat(
            4,
            minmax(0, 1fr)
          );
          gap: 14px;
        }

        .image-item {
          position: relative;
          min-width: 0;
        }

        .image-preview-wrapper {
          position: relative;
          overflow: hidden;
          border: 1px solid #e4e7ec;
          border-radius: 12px;
          background: #f8faf9;
        }

        .image-preview {
          display: block;
          width: 100%;
          height: 180px;
          object-fit: cover;
        }

        .image-number {
          position: absolute;
          top: 9px;
          left: 9px;
          min-width: 27px;
          height: 27px;
          padding: 0 7px;
          border-radius: 7px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          background: rgba(16, 24, 40, 0.78);
          color: #ffffff;
          font-size: 10px;
          font-weight: 700;
        }

        .thumbnail-badge {
          position: absolute;
          left: 9px;
          bottom: 9px;
          padding: 5px 8px;
          border-radius: 6px;
          background: #198754;
          color: #ffffff;
          font-size: 9px;
          font-weight: 700;
        }

        .image-delete-button {
          position: absolute;
          top: 9px;
          right: 9px;
          width: 31px;
          height: 31px;
          padding: 0;
          border: 1px solid rgba(255, 255, 255, 0.3);
          border-radius: 8px;
          background: #dc3545;
          color: #ffffff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 13px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .image-delete-button:hover {
          background: #bb2d3b;
          transform: translateY(-1px);
        }

        .image-delete-button:disabled {
          opacity: 0.65;
          cursor: not-allowed;
          transform: none;
        }

        /* =========================
           NEW IMAGE UPLOAD
        ========================= */

        .upload-box {
          border: 1px dashed #b7dfc9;
          border-radius: 12px;
          padding: 18px;
          background: #f8fcf9;
        }

        .upload-input {
          width: 100%;
          border: 1px solid #d0d5dd;
          border-radius: 9px;
          background: #ffffff;
          color: #475467;
          font-size: 12px;
          padding: 9px;
        }

        .upload-input:focus {
          outline: none;
          border-color: #198754;
          box-shadow: 0 0 0 3px rgba(25, 135, 84, 0.1);
        }

        .new-image-grid {
          display: grid;
          grid-template-columns: repeat(
            4,
            minmax(0, 1fr)
          );
          gap: 14px;
          margin-top: 16px;
        }

        .new-image-item {
          position: relative;
        }

        .new-image-preview {
          display: block;
          width: 100%;
          height: 180px;
          object-fit: cover;
          border: 1px solid #e4e7ec;
          border-radius: 12px;
        }

        .new-image-label {
          position: absolute;
          left: 9px;
          bottom: 9px;
          padding: 5px 8px;
          border-radius: 6px;
          background: #ffffff;
          color: #198754;
          border: 1px solid #cfe8d9;
          font-size: 9px;
          font-weight: 700;
        }

        .new-image-remove {
          position: absolute;
          top: 9px;
          right: 9px;
          width: 31px;
          height: 31px;
          padding: 0;
          border: 0;
          border-radius: 8px;
          background: #dc3545;
          color: #ffffff;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 14px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .new-image-remove:hover {
          background: #bb2d3b;
          transform: translateY(-1px);
        }

        /* =========================
           STATUS
        ========================= */

        .status-box {
          min-height: 43px;
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 9px 12px;
          border: 1px solid #e4e7ec;
          border-radius: 9px;
          background: #f8fafc;
        }

        .status-checkbox {
          width: 17px;
          height: 17px;
          margin: 0;
          accent-color: #198754;
          cursor: pointer;
          flex-shrink: 0;
        }

        .status-label {
          margin: 0;
          color: #344054;
          font-size: 12px;
          font-weight: 600;
          cursor: pointer;
        }

        .published-info {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          margin-top: 7px;
          color: #198754;
          font-size: 10px;
          font-weight: 600;
        }

        /* =========================
           ACTIONS
        ========================= */

        .form-actions {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 15px;
          margin-top: 22px;
          padding-top: 20px;
          border-top: 1px solid #eaecf0;
        }

        .action-button {
          min-height: 43px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          padding: 9px 15px;
          border-radius: 9px;
          font-size: 12px;
          font-weight: 700;
          text-decoration: none;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .cancel-button {
          color: #667085;
          background: #ffffff;
          border: 1px solid #d0d5dd;
        }

        .cancel-button:hover {
          color: #344054;
          background: #f8fafc;
          border-color: #98a2b3;
        }

        .save-button {
          color: #ffffff;
          background: #198754;
          border: 1px solid #198754;
          box-shadow: 0 7px 18px rgba(25, 135, 84, 0.14);
        }

        .save-button:hover {
          color: #ffffff;
          background: #157347;
          border-color: #157347;
          transform: translateY(-1px);
          box-shadow: 0 10px 22px rgba(25, 135, 84, 0.2);
        }

        .save-button:disabled {
          opacity: 0.65;
          cursor: not-allowed;
          transform: none;
          box-shadow: none;
        }

        .actions-right {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 8px;
        }

        /* =========================
           FOOTER
        ========================= */

        .admin-page-footer {
          padding: 22px 2px 8px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 15px;
          color: #98a2b3;
          font-size: 11px;
        }

        .admin-page-footer-left {
          display: flex;
          align-items: center;
          gap: 7px;
        }

        .admin-page-footer a {
          color: #667085;
          text-decoration: none;
          font-weight: 600;
        }

        .admin-page-footer a:hover {
          color: #198754;
        }

        /* =========================
           OVERLAY
        ========================= */

        .sidebar-overlay {
          display: none;
          position: fixed;
          inset: 0;
          background: rgba(15, 23, 42, 0.38);
          z-index: 1040;
          backdrop-filter: blur(2px);
        }

        /* =========================
           TABLET
        ========================= */

        @media (max-width: 1199.98px) {
          .image-grid,
          .new-image-grid {
            grid-template-columns: repeat(
              3,
              minmax(0, 1fr)
            );
          }
        }

        /* =========================
           MOBILE / TABLET
        ========================= */

        @media (max-width: 991.98px) {
          .admin-sidebar {
            transform: translateX(-100%);
            box-shadow: 12px 0 30px rgba(15, 23, 42, 0.1);
          }

          .admin-sidebar.sidebar-open {
            transform: translateX(0);
          }

          .sidebar-overlay.sidebar-overlay-show {
            display: block;
          }

          .admin-main {
            width: 100%;
            margin-left: 0;
          }

          .admin-topbar {
            padding: 0 20px;
          }

          .admin-content {
            padding: 25px 20px;
          }

          .page-heading {
            align-items: flex-start;
            flex-direction: column;
          }

          .form-card-body {
            padding: 20px;
          }

          .form-section {
            padding: 18px;
          }

          .image-grid,
          .new-image-grid {
            grid-template-columns: repeat(
              2,
              minmax(0, 1fr)
            );
          }
        }

        /* =========================
           SMALL MOBILE
        ========================= */

        @media (max-width: 575.98px) {
          .admin-topbar {
            height: 68px;
            padding: 0 14px;
          }

          .topbar-right {
            gap: 6px;
          }

          .topbar-website,
          .topbar-logout {
            width: 38px;
            height: 38px;
            min-height: 38px;
            padding: 0;
          }

          .topbar-website span,
          .topbar-logout span {
            display: none !important;
          }

          .admin-content {
            padding: 20px 14px;
          }

          .page-title-row {
            align-items: flex-start;
          }

          .page-title-icon {
            width: 43px;
            height: 43px;
            border-radius: 11px;
            font-size: 18px;
          }

          .page-title {
            font-size: 25px;
          }

          .page-description {
            font-size: 12px;
          }

          .form-card-header {
            padding: 17px;
          }

          .form-card-title {
            font-size: 15px;
          }

          .form-card-description {
            font-size: 11px;
          }

          .form-card-body {
            padding: 13px;
          }

          .form-section {
            padding: 14px;
            margin-bottom: 12px;
          }

          .form-section-header {
            margin-bottom: 15px;
            padding-bottom: 12px;
          }

          .form-section-icon {
            width: 34px;
            height: 34px;
            font-size: 14px;
          }

          .form-section-title {
            font-size: 13px;
          }

          .form-section-description {
            font-size: 10px;
          }

          .custom-input,
          .custom-textarea {
            font-size: 12px;
          }

          .custom-textarea.content-area {
            min-height: 240px;
          }

          .image-grid,
          .new-image-grid {
            grid-template-columns: 1fr 1fr;
            gap: 10px;
          }

          .image-preview,
          .new-image-preview {
            height: 140px;
          }

          .form-actions {
            flex-direction: column;
            align-items: stretch;
          }

          .actions-right {
            width: 100%;
          }

          .actions-right .action-button {
            flex: 1;
          }

          .cancel-button {
            width: 100%;
          }

          .admin-page-footer {
            flex-direction: column;
            align-items: flex-start;
          }
        }

        @media (max-width: 380px) {
          .image-grid,
          .new-image-grid {
            grid-template-columns: 1fr;
          }

          .image-preview,
          .new-image-preview {
            height: 190px;
          }

          .page-title {
            font-size: 23px;
          }

          .page-title-icon {
            width: 40px;
            height: 40px;
          }
        }
      `}</style>

      <div className="admin-layout">
        {/* =========================
            MOBILE OVERLAY
        ========================= */}

        <div
          className={`sidebar-overlay ${
            sidebarOpen
              ? "sidebar-overlay-show"
              : ""
          }`}
          onClick={() => setSidebarOpen(false)}
        />

        {/* =========================
            SIDEBAR
        ========================= */}

        <aside
          className={`admin-sidebar ${
            sidebarOpen ? "sidebar-open" : ""
          }`}
        >
          <div className="sidebar-inner">
            <div className="sidebar-brand">
              <div className="brand-icon">
                <i className="bi bi-grid-1x2-fill"></i>
              </div>

              <div className="brand-text">
                <strong>GloVaTech</strong>
                <span>Admin Panel</span>
              </div>

              <button
                type="button"
                className="sidebar-close d-lg-none"
                onClick={() =>
                  setSidebarOpen(false)
                }
                aria-label="Tutup sidebar"
              >
                <i className="bi bi-x-lg"></i>
              </button>
            </div>

            <div className="sidebar-section-label">
              MAIN MENU
            </div>

            <nav className="sidebar-nav">
              <Link
                href="/secure-panel"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-speedometer2"></i>
                </span>
                <span>Dashboard</span>
              </Link>
            </nav>

            <div className="sidebar-section-label">
              CONTENT
            </div>

            <nav className="sidebar-nav">
              <Link
                href="/secure-panel/hero"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-stars"></i>
                </span>
                <span>Hero</span>
              </Link>

              <Link
                href="/secure-panel/about"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-person-vcard"></i>
                </span>
                <span>About</span>
              </Link>

              <Link
                href="/secure-panel/about/stats"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-bar-chart"></i>
                </span>
                <span>About Stats</span>
              </Link>

              <Link
                href="/secure-panel/education"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-mortarboard"></i>
                </span>
                <span>Education</span>
              </Link>

              <Link
                href="/secure-panel/skills"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-tools"></i>
                </span>
                <span>Skills</span>
              </Link>

              <Link
                href="/secure-panel/experience"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-briefcase"></i>
                </span>
                <span>Experience</span>
              </Link>

              <Link
                href="/secure-panel/projects"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-code-square"></i>
                </span>
                <span>Projects</span>
              </Link>

              <Link
                href="/secure-panel/certifications"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-patch-check"></i>
                </span>
                <span>Certification</span>
              </Link>

              <Link
                href="/secure-panel/achievements"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-trophy"></i>
                </span>
                <span>Achievement</span>
              </Link>

              <Link
                href="/secure-panel/services"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-gear-wide-connected"></i>
                </span>
                <span>Services</span>
              </Link>

              <Link
                href="/secure-panel/gallery"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-images"></i>
                </span>
                <span>Gallery</span>
              </Link>

              <Link
                href="/secure-panel/contact-info"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-person-lines-fill"></i>
                </span>
                <span>Contact</span>
              </Link>

              <Link
                href="/secure-panel/contact-info/list"
                className="sidebar-link"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-share-fill"></i>
                </span>
                <span>Contact Sosial Media</span>
              </Link>

              <Link
                href="/secure-panel/articles"
                className="sidebar-link active"
                onClick={() =>
                  setSidebarOpen(false)
                }
              >
                <span className="sidebar-link-icon">
                  <i className="bi bi-journal-text"></i>
                </span>
                <span>Articles</span>
              </Link>

              <Link
  href="/secure-panel/contact-messages"
  className="sidebar-link"
  onClick={() => setSidebarOpen(false)}
>
  <span className="sidebar-link-icon">
    <i className="bi bi-chat-left-text"></i>
  </span>
  <span>Contact Messages</span>
</Link>

<Link
  href="/secure-panel/contact-users"
  className="sidebar-link"
  onClick={() => setSidebarOpen(false)}
>
  <span className="sidebar-link-icon">
    <i className="bi bi-people-fill"></i>
  </span>
  <span>Contact User</span>
</Link>
            </nav>

            <div className="sidebar-bottom">
              <Link
                href="/"
                className="sidebar-website"
              >
                <i className="bi bi-globe2"></i>
                <span>View Website</span>
                <i className="bi bi-arrow-up-right ms-auto"></i>
              </Link>
            </div>
          </div>
        </aside>

        {/* =========================
            MAIN
        ========================= */}

        <div className="admin-main">
          {/* =========================
              TOPBAR
          ========================= */}

          <header className="admin-topbar">
            <div className="topbar-left">
              <button
                type="button"
                className="mobile-menu-button d-lg-none"
                onClick={() =>
                  setSidebarOpen(true)
                }
                aria-label="Buka menu"
              >
                <i className="bi bi-list"></i>
              </button>

              <div>
                <div className="topbar-label">
                  ADMIN PANEL
                </div>

                <h6 className="topbar-title mb-0">
                  Article Management
                </h6>
              </div>
            </div>

            <div className="topbar-right">
              <Link
                href="/"
                className="topbar-website"
                title="Lihat Website"
              >
                <i className="bi bi-globe2"></i>
                <span>Website</span>
              </Link>

              <Link
                href="/secure-panel/login"
                className="topbar-logout"
                title="Logout"
              >
                <i className="bi bi-box-arrow-right"></i>
                <span>Logout</span>
              </Link>
            </div>
          </header>

          {/* =========================
              CONTENT
          ========================= */}

          <main className="admin-content">
            {/* =========================
                PAGE HEADING
            ========================= */}

            <section className="page-heading">
              <div className="page-heading-left">
                <Link
                  href="/secure-panel/articles"
                  className="back-dashboard"
                >
                  <i className="bi bi-arrow-left"></i>
                  <span>Kembali ke Articles</span>
                </Link>

                <div className="page-title-row">
                  <div className="page-title-icon">
                    <i className="bi bi-pencil-square"></i>
                  </div>

                  <div>
                    <div className="page-eyebrow">
                      CONTENT MANAGEMENT
                    </div>

                    <h1 className="page-title">
                      Edit Article
                    </h1>

                    <p className="page-description">
                      Perbarui informasi artikel,
                      konten, gambar, kategori, dan
                      status publikasi yang digunakan
                      pada website GloVaTech.
                    </p>
                  </div>
                </div>
              </div>
            </section>

            {/* =========================
                FORM CARD
            ========================= */}

            <section className="form-card">
              <div className="form-card-header">
                <div>
                  <div className="form-card-eyebrow">
                    ARTICLE EDITOR
                  </div>

                  <h2 className="form-card-title">
                    Informasi Article
                  </h2>

                  <p className="form-card-description">
                    Kelola seluruh informasi artikel
                    melalui formulir berikut. Data
                    yang sudah tersimpan tetap
                    dipertahankan kecuali Anda
                    mengubahnya.
                  </p>
                </div>

                <div className="form-card-icon">
                  <i className="bi bi-journal-richtext"></i>
                </div>
              </div>

              <div className="form-card-body">
                <form
                  onSubmit={handleSubmit}
                  className="article-form"
                >
                  {/* ======================
                      INFORMASI DASAR
                  ====================== */}

                  <div className="form-section">
                    <div className="form-section-header">
                      <div className="form-section-icon">
                        <i className="bi bi-info-circle"></i>
                      </div>

                      <div>
                        <h3 className="form-section-title">
                          Informasi Dasar
                        </h3>

                        <p className="form-section-description">
                          Atur judul, slug, dan kategori
                          artikel.
                        </p>
                      </div>
                    </div>

                    <div className="row g-3">
                      <div className="col-12 col-lg-8">
                        <label className="custom-label">
                          Judul Article
                        </label>

                        <input
                          type="text"
                          name="title"
                          className="custom-input"
                          value={form.title}
                          onChange={handleChange}
                          placeholder="Masukkan judul article"
                          required
                        />
                      </div>

                      <div className="col-12 col-lg-4">
                        <label className="custom-label">
                          Slug
                        </label>

                        <input
                          type="text"
                          name="slug"
                          className="custom-input"
                          value={form.slug}
                          onChange={handleChange}
                          placeholder="contoh-judul-article"
                          required
                        />

                        <div className="form-help">
                          Slug digunakan sebagai
                          identitas URL artikel.
                        </div>
                      </div>

                      <div className="col-12 col-md-6">
                        <label className="custom-label">
                          Kategori
                        </label>

                        <input
                          type="text"
                          name="category"
                          className="custom-input"
                          value={form.category}
                          onChange={handleChange}
                          placeholder="Contoh: Technology"
                        />
                      </div>

                      <div className="col-12 col-md-6">
                        <label className="custom-label">
                          URL Gambar Thumbnail
                        </label>

                        <input
                          type="text"
                          name="thumbnail"
                          className="custom-input"
                          value={form.thumbnail}
                          onChange={handleChange}
                          placeholder="https://..."
                        />
                      </div>
                    </div>
                  </div>

                  {/* ======================
                      GAMBAR ARTICLE
                  ====================== */}

                  <div className="form-section">
                    <div className="form-section-header">
                      <div className="form-section-icon">
                        <i className="bi bi-images"></i>
                      </div>

                      <div>
                        <h3 className="form-section-title">
                          Gambar Article
                        </h3>

                        <p className="form-section-description">
                          Kelola gambar yang sudah
                          tersimpan dan tambahkan gambar
                          baru ke artikel.
                        </p>
                      </div>
                    </div>

                    {images.length > 0 ? (
                      <div className="mb-4">
                        <label className="custom-label">
                          Gambar Tersimpan
                        </label>

                        <div className="image-grid">
                          {images.map(
                            (item, index) => (
                              <div
                                key={item.id}
                                className="image-item"
                              >
                                <div className="image-preview-wrapper">
                                  <img
                                    src={item.image}
                                    alt={`Gambar Article ${
                                      index + 1
                                    }`}
                                    className="image-preview"
                                  />

                                  <span className="image-number">
                                    {index + 1}
                                  </span>

                                  {index === 0 && (
                                    <span className="thumbnail-badge">
                                      Thumbnail
                                    </span>
                                  )}

                                  <button
                                    type="button"
                                    className="image-delete-button"
                                    onClick={() =>
                                      handleDeleteImage(
                                        item.id
                                      )
                                    }
                                    disabled={
                                      deletingImageId ===
                                      item.id
                                    }
                                    title="Hapus gambar"
                                  >
                                    {deletingImageId ===
                                    item.id ? (
                                      <span
                                        className="spinner-border spinner-border-sm"
                                        role="status"
                                      ></span>
                                    ) : (
                                      <i className="bi bi-trash"></i>
                                    )}
                                  </button>
                                </div>
                              </div>
                            )
                          )}
                        </div>
                      </div>
                    ) : (
                      <div className="mb-4">
                        <div className="form-help">
                          Belum ada gambar Article
                          yang tersimpan.
                        </div>
                      </div>
                    )}

                    <div className="upload-box">
                      <label className="custom-label">
                        Tambah Gambar Article
                      </label>

                      <input
                        type="file"
                        className="upload-input"
                        accept="image/*"
                        multiple
                        onChange={
                          handleNewImagesChange
                        }
                      />

                      <div className="form-help">
                        Pilih satu atau beberapa gambar
                        baru. Gambar akan diupload ketika
                        Anda menyimpan perubahan.
                      </div>

                      {newPreviews.length > 0 && (
                        <div>
                          <label className="custom-label mt-3">
                            Preview Gambar Baru
                          </label>

                          <div className="new-image-grid">
                            {newPreviews.map(
                              (
                                preview,
                                index
                              ) => (
                                <div
                                  key={`${preview}-${index}`}
                                  className="new-image-item"
                                >
                                  <img
                                    src={preview}
                                    alt={`Gambar baru ${
                                      index + 1
                                    }`}
                                    className="new-image-preview"
                                  />

                                  <span className="new-image-label">
                                    Gambar Baru
                                  </span>

                                  <button
                                    type="button"
                                    className="new-image-remove"
                                    onClick={() =>
                                      removeNewImage(
                                        index
                                      )
                                    }
                                    title="Batalkan gambar"
                                  >
                                    <i className="bi bi-x-lg"></i>
                                  </button>
                                </div>
                              )
                            )}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* ======================
                      CONTENT
                  ====================== */}

                  <div className="form-section">
                    <div className="form-section-header">
                      <div className="form-section-icon">
                        <i className="bi bi-file-text"></i>
                      </div>

                      <div>
                        <h3 className="form-section-title">
                          Isi Article
                        </h3>

                        <p className="form-section-description">
                          Tulis ringkasan dan isi lengkap
                          artikel. Teks ditata dengan
                          perataan justify agar lebih
                          rapi.
                        </p>
                      </div>
                    </div>

                    <div className="row g-3">
                      <div className="col-12">
                        <label className="custom-label">
                          Ringkasan
                        </label>

                        <textarea
                          name="excerpt"
                          className="custom-textarea text-content-justify"
                          rows={4}
                          value={form.excerpt}
                          onChange={handleChange}
                          placeholder="Tulis ringkasan singkat artikel..."
                        />

                        <div className="form-help">
                          Ringkasan singkat yang
                          menggambarkan isi artikel.
                        </div>
                      </div>

                      <div className="col-12">
                        <label className="custom-label">
                          Isi Article
                        </label>

                        <textarea
                          name="content"
                          className="custom-textarea content-area text-content-justify"
                          rows={14}
                          value={form.content}
                          onChange={handleChange}
                          placeholder="Tulis isi artikel..."
                          required
                        />

                        <div className="form-help">
                          Gunakan paragraf yang jelas agar
                          konten mudah dibaca pada website.
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* ======================
                      PUBLIKASI
                  ====================== */}

                  <div className="form-section">
                    <div className="form-section-header">
                      <div className="form-section-icon">
                        <i className="bi bi-send-check"></i>
                      </div>

                      <div>
                        <h3 className="form-section-title">
                          Publikasi
                        </h3>

                        <p className="form-section-description">
                          Atur tanggal publikasi dan status
                          artikel.
                        </p>
                      </div>
                    </div>

                    <div className="row g-3">
                      <div className="col-12 col-md-6">
                        <label className="custom-label">
                          Tanggal Publikasi
                        </label>

                        <input
                          type="date"
                          name="publishedAt"
                          className="custom-input"
                          value={
                            form.publishedAt
                          }
                          onChange={handleChange}
                        />

                        <div className="form-help">
                          Kosongkan jika artikel belum
                          memiliki tanggal publikasi.
                        </div>
                      </div>

                      <div className="col-12 col-md-6">
                        <label className="custom-label">
                          Status Article
                        </label>

                        <div className="status-box">
                          <input
                            type="checkbox"
                            name="published"
                            id="published"
                            className="status-checkbox"
                            checked={
                              form.published
                            }
                            onChange={handleChange}
                          />

                          <label
                            htmlFor="published"
                            className="status-label"
                          >
                            Publikasikan Article
                          </label>
                        </div>

                        {form.published && (
                          <div className="published-info">
                            <i className="bi bi-check-circle-fill"></i>
                            <span>
                              Article akan berstatus
                              Published
                            </span>
                          </div>
                        )}

                        {!form.published && (
                          <div className="form-help">
                            Article akan disimpan sebagai
                            Draft.
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* ======================
                      ACTION
                  ====================== */}

                  <div className="form-actions">
                    <Link
                      href="/secure-panel/articles"
                      className="action-button cancel-button"
                    >
                      <i className="bi bi-arrow-left"></i>
                      <span>Batal</span>
                    </Link>

                    <div className="actions-right">
                      <button
                        type="submit"
                        className="action-button save-button"
                        disabled={
                          saving || uploading
                        }
                      >
                        {saving || uploading ? (
                          <>
                            <span
                              className="spinner-border spinner-border-sm"
                              role="status"
                            ></span>

                            <span>
                              {uploading
                                ? "Mengupload..."
                                : "Menyimpan..."}
                            </span>
                          </>
                        ) : (
                          <>
                            <i className="bi bi-check-lg"></i>
                            <span>
                              Simpan Perubahan
                            </span>
                          </>
                        )}
                      </button>
                    </div>
                  </div>
                </form>
              </div>
            </section>

            {/* =========================
                FOOTER
            ========================= */}

            <footer className="admin-page-footer">
              <div className="admin-page-footer-left">
                <i className="bi bi-shield-check"></i>

                <span>
                  Admin Content Management System
                </span>
              </div>

              <Link href="/secure-panel/articles">
                <i className="bi bi-journal-text me-1"></i>
                Articles
              </Link>
            </footer>
          </main>
        </div>
      </div>
    </>
  );
}
