"use client";

import {
  FormEvent,
  useEffect,
  useRef,
  useState,
} from "react";
import Link from "next/link";
import { useParams, useRouter } from "next/navigation";

type AchievementImage = {
  id: number;
  image: string;
  achievementId: number;
  createdAt: string;
};

type Achievement = {
  id: number;
  title: string;
  issuer: string | null;
  date: string | null;
  description: string | null;
  image: string | null;
  url: string | null;
  achievementimage: AchievementImage[];
};

type ImageItem = {
  id: string;
  url: string;
  isNew?: boolean;
};

export default function EditAchievementPage() {
  const params = useParams();
  const router = useRouter();

  const id = params.id as string;

  const fileInputRef = useRef<HTMLInputElement>(null);

  const [form, setForm] = useState({
    title: "",
    issuer: "",
    date: "",
    description: "",
    url: "",
  });

  const [images, setImages] = useState<ImageItem[]>([]);

  const [loading, setLoading] = useState(true);
  const [uploading, setUploading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [sidebarOpen, setSidebarOpen] = useState(false);

  // =========================================================
  // GET ACHIEVEMENT
  // =========================================================

  useEffect(() => {
    const getAchievement = async () => {
      try {
        setLoading(true);

        const response = await fetch(
          `/api/achievements/${id}`,
          {
            cache: "no-store",
          }
        );

        const result = await response.json();

        if (!result.success) {
          alert(
            result.message ||
              "Achievement tidak ditemukan"
          );

          router.push("/secure-panel/achievements");
          return;
        }

        const achievement: Achievement =
          result.data;

        setForm({
          title: achievement.title || "",
          issuer: achievement.issuer || "",
          date: achievement.date
            ? achievement.date.substring(0, 10)
            : "",
          description:
            achievement.description || "",
          url: achievement.url || "",
        });

        // =====================================================
        // LOAD ALL IMAGES
        // =====================================================

        const savedImages =
          Array.isArray(
            achievement.achievementimage
          )
            ? achievement.achievementimage.map(
                (item) => ({
                  id: String(item.id),
                  url: item.image,
                  isNew: false,
                })
              )
            : [];

        // Support data lama
        if (
          savedImages.length === 0 &&
          achievement.image
        ) {
          savedImages.push({
            id: `old-${achievement.id}`,
            url: achievement.image,
            isNew: false,
          });
        }

        setImages(savedImages);
      } catch (error) {
        console.error(
          "GET ACHIEVEMENT:",
          error
        );

        alert(
          "Gagal mengambil data Achievement"
        );

        router.push("/secure-panel/achievements");
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      getAchievement();
    }
  }, [id, router]);

  // =========================================================
  // FORM CHANGE
  // =========================================================

  const handleChange = (
    e: React.ChangeEvent<
      HTMLInputElement | HTMLTextAreaElement
    >
  ) => {
    const { name, value } = e.target;

    setForm((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  // =========================================================
  // OPEN FILE PICKER
  // =========================================================

  const handleAddImage = () => {
    if (uploading || saving) return;

    fileInputRef.current?.click();
  };

  // =========================================================
  // UPLOAD IMAGE
  // =========================================================

  const handleFileChange = async (
    e: React.ChangeEvent<HTMLInputElement>
  ) => {
    const files = e.target.files;

    if (!files || files.length === 0) {
      return;
    }

    setUploading(true);

    try {
      const formData = new FormData();

      Array.from(files).forEach((file) => {
        formData.append("files", file);
      });

      const response = await fetch(
        "/api/achievements/upload",
        {
          method: "POST",
          body: formData,
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Gagal mengupload gambar"
        );
      }

      const uploadedImages = Array.isArray(
        result.data
      )
        ? result.data
        : [];

      const newImages: ImageItem[] =
        uploadedImages
          .filter(
            (item: {
              url?: string;
            }) =>
              typeof item.url === "string" &&
              item.url.trim() !== ""
          )
          .map(
            (
              item: {
                url: string;
              },
              index: number
            ) => ({
              id: `new-${Date.now()}-${index}`,
              url: item.url,
              isNew: true,
            })
          );

      if (newImages.length === 0) {
        throw new Error(
          "Tidak ada gambar yang berhasil diupload"
        );
      }

      setImages((prev) => [
        ...prev,
        ...newImages,
      ]);
    } catch (error) {
      console.error(
        "UPLOAD ACHIEVEMENT IMAGE:",
        error
      );

      alert(
        error instanceof Error
          ? error.message
          : "Gagal mengupload gambar"
      );
    } finally {
      setUploading(false);

      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  };

  // =========================================================
  // REMOVE IMAGE
  // =========================================================

  const removeImage = (imageId: string) => {
    if (saving || uploading) return;

    setImages((prev) =>
      prev.filter(
        (item) => item.id !== imageId
      )
    );
  };

  // =========================================================
  // SUBMIT
  // =========================================================

  const handleSubmit = async (
    e: FormEvent
  ) => {
    e.preventDefault();

    if (!form.title.trim()) {
      alert(
        "Judul Achievement wajib diisi"
      );
      return;
    }

    if (saving || uploading) {
      return;
    }

    setSaving(true);

    try {
      const imageUrls = images
        .map((item) => item.url)
        .filter(
          (url) =>
            typeof url === "string" &&
            url.trim() !== ""
        );

      const response = await fetch(
        `/api/achievements/${id}`,
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            title: form.title.trim(),

            issuer:
              form.issuer.trim() || null,

            date: form.date || null,

            description:
              form.description.trim() || null,

            url: form.url.trim() || null,

            // SEMUA GAMBAR
            images: imageUrls,

            // GAMBAR PERTAMA SEBAGAI GAMBAR UTAMA
            image: imageUrls[0] || null,
          }),
        }
      );

      const result = await response.json();

      if (!response.ok || !result.success) {
        throw new Error(
          result.message ||
            "Gagal memperbarui Achievement"
        );
      }

      alert(
        "Achievement berhasil diperbarui"
      );

      router.push(
        "/secure-panel/achievements"
      );

      router.refresh();
    } catch (error) {
      console.error(
        "UPDATE ACHIEVEMENT:",
        error
      );

      alert(
        error instanceof Error
          ? error.message
          : "Gagal memperbarui Achievement"
      );
    } finally {
      setSaving(false);
    }
  };

  // =========================================================
  // LOADING
  // =========================================================

  if (loading) {
    return (
      <>
        <style>{`
          * {
            box-sizing: border-box;
          }

          .edit-loading-page {
            min-height: 100vh;
            background: #f5f7f9;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 30px;
          }

          .edit-loading-box {
            text-align: center;
          }

          .edit-loading-spinner {
            width: 44px;
            height: 44px;
            border: 3px solid #dcefe4;
            border-top-color: #198754;
            border-radius: 50%;
            animation: editSpin 0.8s linear infinite;
            margin: 0 auto 16px;
          }

          .edit-loading-title {
            color: #344054;
            font-size: 15px;
            font-weight: 700;
            margin-bottom: 5px;
          }

          .edit-loading-text {
            color: #98a2b3;
            font-size: 12px;
            margin: 0;
          }

          @keyframes editSpin {
            to {
              transform: rotate(360deg);
            }
          }
        `}</style>

        <main className="edit-loading-page">
          <div className="edit-loading-box">
            <div className="edit-loading-spinner"></div>

            <div className="edit-loading-title">
              Memuat data Achievement
            </div>

            <p className="edit-loading-text">
              Sedang mengambil data dari database...
            </p>
          </div>
        </main>
      </>
    );
  }

  // =========================================================
  // PAGE
  // =========================================================

  return (
    <>
      <style>{`
        * {
          box-sizing: border-box;
        }

        body {
          margin: 0;
        }

        /* =====================================================
           LAYOUT
        ===================================================== */

        .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: #ffffff;
          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;
          cursor: pointer;
        }

        .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;
          cursor: pointer;
        }

        .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
        ===================================================== */

        .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: 720px;
          text-align: justify;
        }

        .page-heading-action {
          flex-shrink: 0;
        }

        .back-list-button {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          min-height: 44px;
          padding: 10px 17px;
          border-radius: 10px;
          background: #ffffff;
          color: #475467;
          border: 1px solid #e4e7ec;
          text-decoration: none;
          font-size: 13px;
          font-weight: 600;
          transition: all 0.2s ease;
        }

        .back-list-button:hover {
          color: #198754;
          border-color: #b7dfc9;
          background: #f4fbf7;
          transform: translateY(-1px);
        }

        /* =====================================================
           EDIT CARD
        ===================================================== */

        .edit-card {
          background: #ffffff;
          border: 1px solid #eaecf0;
          border-radius: 16px;
          overflow: hidden;
          box-shadow: 0 3px 12px rgba(16, 24, 40, 0.035);
        }

        .edit-card-header {
          padding: 21px 24px;
          border-bottom: 1px solid #eaecf0;
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 20px;
        }

        .edit-card-eyebrow {
          font-size: 10px;
          font-weight: 700;
          color: #198754;
          letter-spacing: 1px;
          margin-bottom: 4px;
        }

        .edit-card-title {
          font-size: 17px;
          font-weight: 750;
          color: #101828;
          margin: 0;
        }

        .edit-card-description {
          margin: 5px 0 0;
          color: #667085;
          font-size: 12px;
          line-height: 1.65;
          text-align: justify;
          max-width: 800px;
        }

        .achievement-id-badge {
          min-width: 70px;
          min-height: 38px;
          padding: 0 11px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          border-radius: 10px;
          background: #f5f7f9;
          color: #667085;
          font-size: 11px;
          font-weight: 700;
          white-space: nowrap;
        }

        .edit-card-body {
          padding: 24px;
        }

        /* =====================================================
           FORM
        ===================================================== */

        .form-section {
          border: 1px solid #edf0f2;
          border-radius: 13px;
          padding: 20px;
          background: #ffffff;
        }

        .form-section + .form-section {
          margin-top: 18px;
        }

        .form-section-heading {
          display: flex;
          align-items: flex-start;
          gap: 12px;
          margin-bottom: 20px;
        }

        .form-section-icon {
          width: 38px;
          height: 38px;
          border-radius: 10px;
          background: #e9f7ef;
          color: #198754;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          flex-shrink: 0;
        }

        .form-section-title {
          margin: 0;
          color: #101828;
          font-size: 14px;
          font-weight: 750;
        }

        .form-section-description {
          margin: 4px 0 0;
          color: #98a2b3;
          font-size: 11px;
          line-height: 1.65;
          text-align: justify;
        }

        .form-label-custom {
          display: block;
          margin-bottom: 7px;
          color: #344054;
          font-size: 12px;
          font-weight: 700;
        }

        .required-mark {
          color: #dc3545;
          margin-left: 3px;
        }

        .custom-input,
        .custom-textarea {
          width: 100%;
          border: 1px solid #d0d5dd;
          background: #ffffff;
          color: #101828;
          border-radius: 9px;
          padding: 10px 12px;
          font-size: 13px;
          outline: none;
          transition:
            border-color 0.2s ease,
            box-shadow 0.2s ease,
            background 0.2s ease;
        }

        .custom-input {
          min-height: 43px;
        }

        .custom-textarea {
          min-height: 150px;
          resize: vertical;
          line-height: 1.7;
        }

        .custom-input::placeholder,
        .custom-textarea::placeholder {
          color: #a0a8b3;
        }

        .custom-input:focus,
        .custom-textarea:focus {
          border-color: #198754;
          box-shadow: 0 0 0 3px rgba(25, 135, 84, 0.1);
        }

        .custom-input:disabled,
        .custom-textarea:disabled {
          background: #f8f9fa;
          cursor: not-allowed;
        }

        .input-with-icon {
          position: relative;
        }

        .input-with-icon i {
          position: absolute;
          left: 13px;
          top: 50%;
          transform: translateY(-50%);
          color: #98a2b3;
          font-size: 15px;
          pointer-events: none;
        }

        .input-with-icon .custom-input {
          padding-left: 39px;
        }

        .field-help {
          margin-top: 6px;
          color: #98a2b3;
          font-size: 10px;
          line-height: 1.55;
        }

        /* =====================================================
           IMAGE SECTION
        ===================================================== */

        .image-toolbar {
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 15px;
          margin-bottom: 17px;
        }

        .image-toolbar-title {
          color: #101828;
          font-size: 13px;
          font-weight: 700;
        }

        .image-toolbar-text {
          margin-top: 4px;
          color: #98a2b3;
          font-size: 10px;
          line-height: 1.6;
          text-align: justify;
        }

        .upload-button {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 7px;
          min-height: 40px;
          padding: 8px 13px;
          border-radius: 9px;
          border: 1px solid #b7dfc9;
          background: #f4fbf7;
          color: #198754;
          font-size: 11px;
          font-weight: 700;
          cursor: pointer;
          transition: all 0.2s ease;
          white-space: nowrap;
        }

        .upload-button:hover {
          background: #198754;
          border-color: #198754;
          color: #ffffff;
        }

        .upload-button:disabled {
          opacity: 0.65;
          cursor: not-allowed;
        }

        .image-grid {
          display: grid;
          grid-template-columns: repeat(3, minmax(0, 1fr));
          gap: 14px;
        }

        .image-card {
          border: 1px solid #edf0f2;
          border-radius: 13px;
          overflow: hidden;
          background: #ffffff;
          transition:
            border-color 0.2s ease,
            box-shadow 0.2s ease,
            transform 0.2s ease;
        }

        .image-card:hover {
          border-color: #cfe8d9;
          box-shadow: 0 8px 22px rgba(25, 135, 84, 0.07);
          transform: translateY(-2px);
        }

        .image-preview {
          position: relative;
          height: 215px;
          background: #f5f7f9;
          overflow: hidden;
        }

        .image-preview img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          display: block;
        }

        .image-number {
          position: absolute;
          left: 10px;
          top: 10px;
          min-width: 30px;
          height: 28px;
          padding: 0 8px;
          border-radius: 7px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          background: rgba(16, 24, 40, 0.72);
          color: #ffffff;
          font-size: 10px;
          font-weight: 700;
          backdrop-filter: blur(6px);
        }

        .main-image-label {
          position: absolute;
          left: 10px;
          bottom: 10px;
          display: inline-flex;
          align-items: center;
          gap: 5px;
          padding: 5px 8px;
          border-radius: 6px;
          background: rgba(25, 135, 84, 0.92);
          color: #ffffff;
          font-size: 9px;
          font-weight: 700;
        }

        .image-delete-button {
          position: absolute;
          top: 10px;
          right: 10px;
          width: 34px;
          height: 34px;
          border: 0;
          border-radius: 9px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: rgba(220, 53, 69, 0.94);
          color: #ffffff;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .image-delete-button:hover {
          background: #b02a37;
          transform: scale(1.04);
        }

        .image-delete-button:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }

        .image-card-body {
          padding: 12px;
        }

        .image-card-title {
          color: #344054;
          font-size: 11px;
          font-weight: 700;
        }

        .image-card-status {
          display: inline-flex;
          align-items: center;
          gap: 5px;
          margin-top: 5px;
          color: #198754;
          font-size: 9px;
          font-weight: 600;
        }

        .image-card-status.new-image {
          color: #0d6efd;
        }

        .empty-images {
          min-height: 230px;
          border: 1px dashed #d0d5dd;
          border-radius: 13px;
          background: #fafbfc;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          padding: 30px 20px;
          text-align: center;
        }

        .empty-images-icon {
          width: 58px;
          height: 58px;
          border-radius: 15px;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #f2f4f7;
          color: #98a2b3;
          font-size: 24px;
          margin-bottom: 13px;
        }

        .empty-images-title {
          color: #344054;
          font-size: 14px;
          font-weight: 700;
          margin-bottom: 5px;
        }

        .empty-images-text {
          max-width: 390px;
          margin: 0;
          color: #98a2b3;
          font-size: 11px;
          line-height: 1.7;
          text-align: justify;
        }

        /* =====================================================
           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;
        }

        .form-actions-info {
          display: flex;
          align-items: center;
          gap: 7px;
          color: #98a2b3;
          font-size: 10px;
          line-height: 1.5;
        }

        .form-actions-info i {
          color: #198754;
          font-size: 14px;
        }

        .action-buttons {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 8px;
        }

        .cancel-button,
        .save-button {
          min-height: 42px;
          padding: 9px 15px;
          border-radius: 9px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 7px;
          font-size: 12px;
          font-weight: 700;
          text-decoration: none;
          transition: all 0.2s ease;
          cursor: pointer;
        }

        .cancel-button {
          background: #ffffff;
          color: #667085;
          border: 1px solid #d0d5dd;
        }

        .cancel-button:hover {
          background: #f5f7f9;
          color: #344054;
          border-color: #bfc5cd;
        }

        .save-button {
          background: #198754;
          color: #ffffff;
          border: 1px solid #198754;
          box-shadow: 0 6px 16px rgba(25, 135, 84, 0.15);
        }

        .save-button:hover {
          background: #157347;
          border-color: #157347;
          color: #ffffff;
          transform: translateY(-1px);
          box-shadow: 0 9px 20px rgba(25, 135, 84, 0.2);
        }

        .save-button:disabled {
          opacity: 0.65;
          cursor: not-allowed;
          transform: none;
        }

        /* =====================================================
           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 {
            grid-template-columns: repeat(2, 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;
          }

          .page-heading-action {
            width: 100%;
          }

          .back-list-button {
            width: 100%;
          }

          .edit-card-body {
            padding: 20px;
          }

          .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;
          }

          .edit-card-header {
            padding: 17px;
          }

          .edit-card-body {
            padding: 13px;
          }

          .edit-card-title {
            font-size: 15px;
          }

          .edit-card-description {
            font-size: 11px;
          }

          .achievement-id-badge {
            display: none;
          }

          .form-section {
            padding: 15px;
          }

          .form-section-heading {
            margin-bottom: 16px;
          }

          .image-toolbar {
            align-items: flex-start;
            flex-direction: column;
          }

          .upload-button {
            width: 100%;
          }

          .image-grid {
            grid-template-columns: 1fr;
          }

          .image-preview {
            height: 220px;
          }

          .custom-input {
            min-height: 42px;
          }

          .custom-textarea {
            min-height: 145px;
          }

          .form-actions {
            align-items: stretch;
            flex-direction: column;
          }

          .form-actions-info {
            align-items: flex-start;
          }

          .action-buttons {
            width: 100%;
          }

          .cancel-button,
          .save-button {
            flex: 1;
          }

          .admin-page-footer {
            flex-direction: column;
            align-items: flex-start;
          }
        }
      `}</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">

            {/* BRAND */}

            <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>

            {/* MAIN MENU */}

            <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>

            {/* CONTENT */}

            <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>

              {/* ACTIVE ACHIEVEMENT */}

              <Link
                href="/secure-panel/achievements"
                className="sidebar-link active"
                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"
                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 Social Media</span>
            </Link>

              <Link
                href="/secure-panel/articles"
                className="sidebar-link"
                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>

            {/* BOTTOM */}

            <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">
                  Achievement 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/achievements"
                  className="back-dashboard"
                >
                  <i className="bi bi-arrow-left"></i>

                  <span>
                    Kembali ke Achievement
                  </span>
                </Link>

                <div className="page-title-row">

                  <div className="page-title-icon">
                    <i className="bi bi-trophy-fill"></i>
                  </div>

                  <div>

                    <div className="page-eyebrow">
                      ACHIEVEMENT MANAGEMENT
                    </div>

                    <h1 className="page-title">
                      Edit Achievement
                    </h1>

                    <p className="page-description">
                      Perbarui informasi achievement,
                      penyelenggara, tanggal, deskripsi,
                      URL, serta gambar yang ditampilkan
                      pada website portfolio GloVaTech.
                    </p>

                  </div>

                </div>

              </div>

              <div className="page-heading-action">

                <Link
                  href="/secure-panel/achievements"
                  className="back-list-button"
                >
                  <i className="bi bi-list-ul"></i>

                  <span>
                    Daftar Achievement
                  </span>
                </Link>

              </div>

            </section>

            {/* =================================================
                EDIT CARD
            ================================================= */}

            <section className="edit-card">

              {/* CARD HEADER */}

              <div className="edit-card-header">

                <div>

                  <div className="edit-card-eyebrow">
                    CONTENT MANAGEMENT
                  </div>

                  <h2 className="edit-card-title">
                    Achievement Information
                  </h2>

                  <p className="edit-card-description">
                    Kelola informasi detail achievement
                    yang akan digunakan pada website.
                    Pastikan data yang dimasukkan sudah
                    sesuai sebelum menyimpan perubahan.
                  </p>

                </div>

                <div className="achievement-id-badge">
                  <i className="bi bi-hash"></i>

                  <span>
                    {id}
                  </span>
                </div>

              </div>

              {/* CARD BODY */}

              <div className="edit-card-body">

                <form onSubmit={handleSubmit}>

                  {/* =================================================
                      BASIC INFORMATION
                  ================================================= */}

                  <section className="form-section">

                    <div className="form-section-heading">

                      <div className="form-section-icon">
                        <i className="bi bi-info-circle"></i>
                      </div>

                      <div>

                        <h3 className="form-section-title">
                          Informasi Achievement
                        </h3>

                        <p className="form-section-description">
                          Masukkan informasi utama achievement
                          seperti judul, penerbit, tanggal,
                          dan URL referensi.
                        </p>

                      </div>

                    </div>

                    <div className="row g-3">

                      {/* TITLE */}

                      <div className="col-md-8">

                        <label
                          htmlFor="title"
                          className="form-label-custom"
                        >
                          Judul Achievement
                          <span className="required-mark">
                            *
                          </span>
                        </label>

                        <input
                          id="title"
                          type="text"
                          name="title"
                          className="custom-input"
                          value={form.title}
                          onChange={handleChange}
                          placeholder="Masukkan judul achievement"
                          required
                          disabled={
                            saving ||
                            uploading
                          }
                        />

                      </div>

                      {/* ISSUER */}

                      <div className="col-md-4">

                        <label
                          htmlFor="issuer"
                          className="form-label-custom"
                        >
                          Penerbit /
                          Penyelenggara
                        </label>

                        <input
                          id="issuer"
                          type="text"
                          name="issuer"
                          className="custom-input"
                          value={form.issuer}
                          onChange={handleChange}
                          placeholder="Nama penerbit atau penyelenggara"
                          disabled={
                            saving ||
                            uploading
                          }
                        />

                      </div>

                      {/* DATE */}

                      <div className="col-md-6">

                        <label
                          htmlFor="date"
                          className="form-label-custom"
                        >
                          Tanggal
                        </label>

                        <input
                          id="date"
                          type="date"
                          name="date"
                          className="custom-input"
                          value={form.date}
                          onChange={handleChange}
                          disabled={
                            saving ||
                            uploading
                          }
                        />

                      </div>

                      {/* URL */}

                      <div className="col-md-6">

                        <label
                          htmlFor="url"
                          className="form-label-custom"
                        >
                          URL Achievement
                        </label>

                        <div className="input-with-icon">

                          <i className="bi bi-link-45deg"></i>

                          <input
                            id="url"
                            type="url"
                            name="url"
                            className="custom-input"
                            value={form.url}
                            onChange={handleChange}
                            placeholder="https://..."
                            disabled={
                              saving ||
                              uploading
                            }
                          />

                        </div>

                        <div className="field-help">
                          Masukkan link sertifikat,
                          dokumentasi, atau referensi
                          achievement jika tersedia.
                        </div>

                      </div>

                    </div>

                  </section>

                  {/* =================================================
                      DESCRIPTION
                  ================================================= */}

                  <section className="form-section">

                    <div className="form-section-heading">

                      <div className="form-section-icon">
                        <i className="bi bi-text-paragraph"></i>
                      </div>

                      <div>

                        <h3 className="form-section-title">
                          Deskripsi
                        </h3>

                        <p className="form-section-description">
                          Jelaskan achievement secara
                          singkat, jelas, dan informatif.
                        </p>

                      </div>

                    </div>

                    <label
                      htmlFor="description"
                      className="form-label-custom"
                    >
                      Deskripsi Achievement
                    </label>

                    <textarea
                      id="description"
                      name="description"
                      className="custom-textarea"
                      rows={6}
                      value={
                        form.description
                      }
                      onChange={handleChange}
                      placeholder="Tuliskan deskripsi achievement..."
                      disabled={
                        saving ||
                        uploading
                      }
                    />

                    <div className="field-help">
                      Gunakan deskripsi yang informatif
                      agar pengunjung website memahami
                      pencapaian tersebut dengan mudah.
                    </div>

                  </section>

                  {/* =================================================
                      IMAGES
                  ================================================= */}

                  <section className="form-section">

                    <div className="form-section-heading">

                      <div className="form-section-icon">
                        <i className="bi bi-images"></i>
                      </div>

                      <div>

                        <h3 className="form-section-title">
                          Gambar Achievement
                        </h3>

                        <p className="form-section-description">
                          Kelola semua gambar achievement.
                          Gambar pertama otomatis digunakan
                          sebagai gambar utama.
                        </p>

                      </div>

                    </div>

                    <div className="image-toolbar">

                      <div>

                        <div className="image-toolbar-title">
                          Media Achievement
                        </div>

                        <div className="image-toolbar-text">
                          Anda dapat memilih beberapa gambar
                          sekaligus dari komputer.
                        </div>

                      </div>

                      {/* HIDDEN INPUT */}

                      <input
                        ref={fileInputRef}
                        type="file"
                        accept="image/*"
                        multiple
                        className="d-none"
                        onChange={
                          handleFileChange
                        }
                      />

                      <button
                        type="button"
                        className="upload-button"
                        onClick={
                          handleAddImage
                        }
                        disabled={
                          uploading ||
                          saving
                        }
                      >
                        {uploading ? (
                          <>
                            <span
                              className="spinner-border spinner-border-sm"
                              aria-hidden="true"
                            ></span>

                            <span>
                              Mengupload...
                            </span>
                          </>
                        ) : (
                          <>
                            <i className="bi bi-cloud-arrow-up"></i>

                            <span>
                              Tambah Gambar
                            </span>
                          </>
                        )}
                      </button>

                    </div>

                    {/* IMAGE PREVIEW */}

                    {images.length > 0 ? (

                      <div className="image-grid">

                        {images.map(
                          (
                            item,
                            index
                          ) => (

                            <article
                              key={item.id}
                              className="image-card"
                            >

                              <div className="image-preview">

                                <img
                                  src={item.url}
                                  alt={`Achievement ${
                                    index + 1
                                  }`}
                                />

                                <span className="image-number">
                                  #{index + 1}
                                </span>

                                {index === 0 && (
                                  <span className="main-image-label">
                                    <i className="bi bi-star-fill"></i>

                                    Gambar Utama
                                  </span>
                                )}

                                <button
                                  type="button"
                                  className="image-delete-button"
                                  onClick={() =>
                                    removeImage(
                                      item.id
                                    )
                                  }
                                  disabled={
                                    saving ||
                                    uploading
                                  }
                                  title="Hapus gambar"
                                  aria-label={`Hapus gambar ${
                                    index + 1
                                  }`}
                                >
                                  <i className="bi bi-trash"></i>
                                </button>

                              </div>

                              <div className="image-card-body">

                                <div className="image-card-title">
                                  Achievement{" "}
                                  {index + 1}
                                </div>

                                {item.isNew ? (
                                  <div className="image-card-status new-image">
                                    <i className="bi bi-cloud-check"></i>

                                    Gambar baru
                                  </div>
                                ) : (
                                  <div className="image-card-status">
                                    <i className="bi bi-check-circle"></i>

                                    Gambar tersimpan
                                  </div>
                                )}

                              </div>

                            </article>

                          )
                        )}

                      </div>

                    ) : (

                      <div className="empty-images">

                        <div className="empty-images-icon">
                          <i className="bi bi-images"></i>
                        </div>

                        <div className="empty-images-title">
                          Belum ada gambar
                        </div>

                        <p className="empty-images-text">
                          Belum terdapat gambar pada
                          achievement ini. Tambahkan gambar
                          menggunakan tombol Tambah Gambar
                          di atas.
                        </p>

                      </div>

                    )}

                  </section>

                  {/* =================================================
                      ACTIONS
                  ================================================= */}

                  <div className="form-actions">

                    <div className="form-actions-info">

                      <i className="bi bi-shield-check"></i>

                      <span>
                        Perubahan akan disimpan ke
                        database setelah tombol simpan
                        ditekan.
                      </span>

                    </div>

                    <div className="action-buttons">

                      <Link
                        href="/secure-panel/achievements"
                        className="cancel-button"
                      >
                        <i className="bi bi-x-lg"></i>

                        <span>
                          Batal
                        </span>
                      </Link>

                      <button
                        type="submit"
                        className="save-button"
                        disabled={
                          saving ||
                          uploading
                        }
                      >
                        {saving ? (
                          <>
                            <span
                              className="spinner-border spinner-border-sm"
                              aria-hidden="true"
                            ></span>

                            <span>
                              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/achievements"
              >
                <i className="bi bi-arrow-left me-1"></i>

                Achievement
              </Link>

            </footer>

          </main>

        </div>
      </div>
    </>
  );
}

