﻿"use client";

import { useEffect, useState } from "react";

type ContentPixelProps = {
  type: "page" | "blog" | "event";
  id: number;
};

export default function ContentPixel({
  type,
  id,
}: ContentPixelProps) {
  const [enabled, setEnabled] = useState(false);
  const [pixelId, setPixelId] = useState("");
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [message, setMessage] = useState("");

  useEffect(() => {
    fetch(`/api/cms/content-pixel?type=${type}&id=${id}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          setEnabled(Boolean(data.data.enabled));
          setPixelId(data.data.pixelId || "");
        }
      })
      .catch(() => {
        setMessage("Gagal mengambil pengaturan Pixel.");
      })
      .finally(() => setLoading(false));
  }, [type, id]);

  async function save() {
    setSaving(true);
    setMessage("");

    try {
      const res = await fetch("/api/cms/content-pixel", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          type,
          id,
          enabled,
          pixelId: pixelId.trim(),
        }),
      });

      const data = await res.json();

      if (!res.ok || !data.success) {
        throw new Error(data.error || "Gagal menyimpan Pixel.");
      }

      setMessage("Pixel berhasil disimpan.");
    } catch (error) {
      setMessage(
        error instanceof Error
          ? error.message
          : "Gagal menyimpan Pixel."
      );
    } finally {
      setSaving(false);
    }
  }

  if (loading) {
    return (
      <section
        style={{
          marginTop: 28,
          padding: 24,
          border: "1px solid #dce3e8",
          borderRadius: 14,
        }}
      >
        Memuat pengaturan Pixel...
      </section>
    );
  }

  return (
    <section
      style={{
        marginTop: 28,
        padding: 24,
        border: "1px solid #dce3e8",
        borderRadius: 14,
        background: "#fff",
      }}
    >
      <div
        style={{
          fontSize: 12,
          fontWeight: 800,
          letterSpacing: "0.08em",
          color: "#009dcc",
          marginBottom: 6,
        }}
      >
        META / FACEBOOK PIXEL
      </div>

      <h2
        style={{
          margin: "0 0 6px",
          fontSize: 20,
          color: "#102033",
        }}
      >
        Pixel khusus konten
      </h2>

      <p
        style={{
          margin: "0 0 20px",
          color: "#657384",
          fontSize: 14,
          lineHeight: 1.6,
        }}
      >
        Pixel ini hanya digunakan untuk konten ini. Jika tidak
        diaktifkan, sistem dapat menggunakan Global Pixel.
      </p>

      <label
        style={{
          display: "flex",
          alignItems: "center",
          gap: 10,
          fontWeight: 700,
          color: "#102033",
          marginBottom: 18,
        }}
      >
        <input
          type="checkbox"
          checked={enabled}
          onChange={(e) => setEnabled(e.target.checked)}
          style={{ width: 19, height: 19 }}
        />
        Aktifkan Pixel khusus
      </label>

      <label
        style={{
          display: "block",
          fontWeight: 700,
          color: "#102033",
          marginBottom: 8,
        }}
      >
        Facebook Pixel ID
      </label>

      <input
        type="text"
        value={pixelId}
        onChange={(e) => setPixelId(e.target.value)}
        placeholder="Contoh: 123456789012345"
        style={{
          width: "100%",
          height: 46,
          padding: "0 13px",
          border: "1px solid #cfd8df",
          borderRadius: 9,
          fontSize: 15,
        }}
      />

      <button
        type="button"
        onClick={save}
        disabled={saving}
        style={{
          marginTop: 18,
          height: 44,
          padding: "0 20px",
          border: 0,
          borderRadius: 9,
          background: "#00BFFF",
          color: "#102033",
          fontWeight: 800,
          cursor: saving ? "wait" : "pointer",
        }}
      >
        {saving ? "Menyimpan..." : "Simpan Pixel"}
      </button>

      {message && (
        <div
          style={{
            marginTop: 12,
            fontSize: 14,
            fontWeight: 600,
          }}
        >
          {message}
        </div>
      )}
    </section>
  );
}
