mediahub-fe/components/form/content/spit-convert-form.tsx

1124 lines
40 KiB
TypeScript

"use client";
import React, { ChangeEvent, useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card } from "@/components/ui/card";
import { zodResolver } from "@hookform/resolvers/zod";
import * as z from "zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { useParams, useRouter } from "next/navigation";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import JoditEditor from "jodit-react";
import { register } from "module";
import { Switch } from "@/components/ui/switch";
import Cookies from "js-cookie";
import {
convertSPIT,
createMedia,
deleteSPIT,
detailSPIT,
getTagsBySubCategoryId,
listCategory,
listEnableCategory,
} from "@/service/content/content";
import { detailMedia } from "@/service/curated-content/curated-content";
import { Badge } from "@/components/ui/badge";
import { MailIcon } from "lucide-react";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/free-mode";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/thumbs";
import "swiper/css";
import "swiper/css/navigation";
import { FreeMode, Navigation, Pagination, Thumbs } from "swiper/modules";
import { request } from "http";
import {
generateDataArticle,
generateDataRewrite,
getDetailArticle,
} from "@/service/content/ai";
import { getCookiesDecrypt } from "@/lib/utils";
import dynamic from "next/dynamic";
import { error } from "@/lib/swal";
import { useTranslations } from "next-intl";
import { contextType } from "cleave.js/react";
import { Form } from "@/components/ui/form";
type Category = {
id: number;
name: string;
};
type Detail = {
id: string;
contentTitle: string;
contentDescription: string;
slug: string;
content: {
id: number;
name: string;
};
contentCreator: string;
creatorName: string;
contentThumbnail: string;
contentTag: string;
};
type Option = {
id: string;
label: string;
};
interface FileData {
contentId: number;
placement?: string[];
[key: string]: any; // Extendable for additional properties
}
interface PlacementData {
mediaFileId: number;
placements: string;
}
type FileType = {
contentId: number;
contentFile: string;
thumbnailFileUrl: string;
fileName: string;
};
const CustomEditor = dynamic(
() => {
return import("@/components/editor/custom-editor");
},
{ ssr: false }
);
export default function FormConvertSPIT() {
const MySwal = withReactContent(Swal);
const router = useRouter();
const { id } = useParams() as { id: string };
console.log(id);
const editor = useRef(null);
// type ImageSchema = z.infer<typeof imageSchema>;
const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
const taskId = Cookies.get("taskId");
const scheduleId = Cookies.get("scheduleId");
const scheduleType = Cookies.get("scheduleType");
const [categories, setCategories] = useState<Category[]>([]);
const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(
null
);
const [tags, setTags] = useState<any[]>([]);
const [detail, setDetail] = useState<any>();
const [refresh, setRefresh] = useState(false);
const [selectedPublishers, setSelectedPublishers] = useState<number[]>([]);
const [detailThumb, setDetailThumb] = useState<any>([]);
const [thumbsSwiper, setThumbsSwiper] = useState<any>(null);
const [selectedAdvConfig, setSelectedAdvConfig] = useState<string>("");
const [title, setTitle] = useState<string>("");
const [articleIds, setArticleIds] = useState<string[]>([]);
const [isGeneratedArticle, setIsGeneratedArticle] = useState(false);
const [articleBody, setArticleBody] = useState<string>("");
const [selectedArticleId, setSelectedArticleId] = useState<string | null>(
null
);
const [isContentRewriteClicked, setIsContentRewriteClicked] = useState(false);
const t = useTranslations("Form");
const [detailData, setDetailData] = useState<any>(null);
const [selectedFileType, setSelectedFileType] = useState("original");
const [isLoadingData, setIsLoadingData] = useState<boolean>(false);
const userLevelId = getCookiesDecrypt("ulie");
const userLevelNumber = getCookiesDecrypt("ulne");
const roleId = getCookiesDecrypt("urie");
const [isMabesApprover, setIsMabesApprover] = useState(false);
const [selectedTarget, setSelectedTarget] = useState("");
const [unitSelection, setUnitSelection] = useState({
allUnit: false,
mabes: false,
polda: false,
polres: false,
});
const [publishedFor, setPublishedFor] = useState<string[]>([]);
const [filePlacements, setFilePlacements] = useState<string[][]>([]);
const [isUserMabesApprover, setIsUserMabesApprover] = useState(false);
const [files, setFiles] = useState<FileType[]>([]);
const [selectedWritingStyle, setSelectedWritingStyle] =
useState("Professional");
const imageSchema = z
.object({
contentTitle: z.string().min(1, { message: "Judul diperlukan" }),
contentDescription: z
.string()
.min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }),
contentCreator: z.string().min(1, { message: "Creator diperlukan" }),
contentRewriteDescription: z.string().optional(),
})
.refine(
(data) => {
// Jika tombol rewrite diklik, pastikan field-nya tidak kosong
if (isContentRewriteClicked) {
return detail?.contentRewriteDescription?.trim().length > 0;
}
return true; // tidak diklik => tidak wajib
},
{
path: ["contentRewriteDescription"],
message: "File hasil rewrite wajib diisi",
}
);
const options: Option[] = [
{ id: "all", label: "SEMUA" },
{ id: "5", label: "UMUM" },
{ id: "6", label: "JOURNALIS" },
{ id: "7", label: "POLRI" },
{ id: "8", label: "KSP" },
];
let fileTypeId = "1";
// const {
// control,
// handleSubmit,
// setValue,
// formState: { errors },
// } = useForm<ImageSchema>({
// resolver: zodResolver(imageSchema),
// defaultValues: {
// contentTitle: detail?.contentTitle || "",
// contentDescription: detail?.contentDescription || "",
// contentCreator: detail?.contentCreator || "",
// contentRewriteDescription: detail?.contentRewriteDescription || "",
// // dll
// },
// });
const form = useForm<z.infer<typeof imageSchema>>({
resolver: zodResolver(imageSchema),
defaultValues: {
contentTitle: detail?.contentTitle || "",
contentDescription: detail?.contentDescription || "",
contentCreator: detail?.contentCreator || "",
contentRewriteDescription: detail?.contentRewriteDescription || "",
// dll
},
});
const handleRemoveTag = (index: any) => {
setTags((prevTags) => prevTags.filter((_, i) => i !== index));
};
const handleImageChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
const files = Array.from(event.target.files);
setSelectedFiles((prevImages: any) => [...prevImages, ...files]);
console.log("DATAFILE::", selectedFiles);
}
};
const handleRemoveImage = (index: number) => {
setSelectedFiles((prevImages) => prevImages.filter((_, i) => i !== index));
};
const handleDirectSave = () => {
const values = form.getValues(); // ambil semua nilai tanpa validasi
onSubmit(values); // langsung submit
};
useEffect(() => {
async function initState() {
getCategories();
}
initState();
}, []);
useEffect(() => {
if (
userLevelId != undefined &&
roleId != undefined &&
userLevelId == "216" &&
roleId == "3"
) {
setIsUserMabesApprover(true);
}
}, [userLevelId, roleId]);
useEffect(() => {
if (
userLevelId != undefined &&
roleId != undefined &&
userLevelId == "216" &&
roleId == "3"
) {
setIsMabesApprover(true);
}
}, [userLevelId, roleId]);
const getCategories = async () => {
try {
const category = await listCategory(fileTypeId);
const resCategory: Category[] = category?.data?.data?.content;
setCategories(resCategory);
console.log("data category", resCategory);
if (scheduleId && scheduleType === "3") {
const findCategory = resCategory.find((o) =>
o.name.toLowerCase().includes("pers rilis")
);
if (findCategory) {
// setValue("categoryId", findCategory.id);
setSelectedCategoryId(findCategory.id); // Set the selected category
const response = await getTagsBySubCategoryId(findCategory.id);
setTags(response?.data?.data);
}
}
} catch (error) {
console.error("Failed to fetch categories:", error);
}
};
const setupPlacement = (
index: number,
placement: string,
checked: boolean
) => {
let temp = [...filePlacements];
if (checked) {
if (placement === "all") {
temp[index] = ["all", "mabes", "polda", "international"];
} else {
const now = temp[index];
now.push(placement);
if (now.length === 3 && !now.includes("all")) {
now.push("all");
}
temp[index] = now;
}
} else {
if (placement === "all") {
temp[index] = [];
} else {
const now = temp[index].filter((a) => a !== placement);
console.log("now", now);
temp[index] = now;
if (now.length === 3 && now.includes("all")) {
const newData = now.filter((b) => b !== "all");
temp[index] = newData;
}
}
}
setFilePlacements(temp);
};
const setupPlacementCheck = (length: number) => {
const temp = [];
for (let i = 0; i < length; i++) {
temp.push([]);
}
setFilePlacements(temp);
};
useEffect(() => {
async function initState() {
if (id) {
const response = await detailSPIT(id);
const details = response?.data?.data;
setDetail(details);
setFiles(details?.contentList);
setupPlacementCheck(details?.contentList?.length);
form.setValue("contentTitle", details?.contentTitle || "");
form.setValue("contentDescription", details?.contentDescription || "");
form.setValue("contentCreator", details?.contentCreator || "");
form.setValue(
"contentRewriteDescription",
details?.contentRewriteDescription || ""
);
const filesData = details.contentList || [];
const fileUrls = filesData.map((file: { contentFile: string }) =>
file.contentFile ? file.contentFile : "default-image.jpg"
);
setDetailThumb(fileUrls);
const matchingCategory = categories.find(
(category) => category.id === details.categoryId
);
if (matchingCategory) {
setSelectedTarget(matchingCategory.name);
}
// setSelectedTarget(details.categoryId); // Untuk dropdown
}
}
initState();
}, [refresh]);
const [tempFile, setTempFile] = useState(
detailThumb.map((data: any) => ({
contentId: data.id,
placement: [],
}))
);
const handleCheckboxChangeFile = (contentId: number, value: string) => {
setTempFile((prevTempFile: any) => {
return prevTempFile.map((file: any) => {
if (file.contentId === contentId) {
const isChecked = file.placement?.includes(value);
return {
...file,
placement: isChecked
? file.placement.filter((v: any) => v !== value) // Uncheck
: [...(file.placement || []), value], // Check
};
}
return file;
});
});
};
const handleCheckboxChange = (id: string): void => {
if (id === "all") {
if (publishedFor.includes("all")) {
setPublishedFor([]);
} else {
setPublishedFor(
options
.filter((opt: any) => opt.id !== "all")
.map((opt: any) => opt.id)
);
}
} else {
const updatedPublishedFor = publishedFor.includes(id)
? publishedFor.filter((item) => item !== id)
: [...publishedFor, id];
if (publishedFor.includes("all") && id !== "all") {
setPublishedFor(updatedPublishedFor.filter((item) => item !== "all"));
} else {
setPublishedFor(updatedPublishedFor);
}
}
};
const getPlacement = () => {
console.log("getPlaa", filePlacements);
const temp = [];
for (let i = 0; i < filePlacements?.length; i++) {
if (filePlacements[i].length !== 0) {
const now = filePlacements[i].filter((a) => a !== "all");
const data = {
mediaFileId: files[i].contentId,
placement: now.join(","),
};
temp.push(data);
}
}
return temp;
};
// const setupPlacement = (
// index: number,
// category: string,
// isChecked: boolean
// ) => {
// setFilePlacements((prev) =>
// prev.map((placement, i) =>
// i === index
// ? isChecked
// ? [...new Set([...placement, category])] // Tambahkan kategori jika belum ada
// : placement.filter((item) => item !== category) // Hapus kategori jika ada
// : placement
// )
// );
// };
const handleSelectAll = (category: string, isChecked: boolean) => {
setFilePlacements((prev: string[][]) =>
prev.map(
(placement: string[]) =>
isChecked
? Array.from(new Set([...placement, category])) // Konversi Set ke array dengan Array.from()
: placement.filter((item: string) => item !== category) // Hapus jika ada
)
);
};
const save = async (data: {
contentTitle: string;
contentDescription: string;
contentRewriteDescription?: string;
contentCreator: string;
}): Promise<void> => {
const temp = [];
for (const element of detail.contentList) {
temp.push([]);
}
const description =
selectedFileType === "original"
? data.contentDescription
: data.contentRewriteDescription;
const requestData = {
spitId: id,
title: data.contentTitle,
description,
htmlDescription: description,
tags: "siap",
categoryId: selectedCategoryId,
publishedFor: publishedFor.join(","),
creator: data.contentCreator,
files: isUserMabesApprover ? getPlacement() : [],
};
const response = await convertSPIT(requestData);
console.log("Form Data Submitted:", response);
setFilePlacements(temp);
setFiles(detail.files);
MySwal.fire({
title: "Sukses",
text: "Data berhasil disimpan.",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then(() => {
router.push("/en/contributor/content/spit");
});
};
const onSubmit = async (data: z.infer<typeof imageSchema>) => {
MySwal.fire({
title: "Simpan Data",
text: "Apakah Anda yakin ingin menyimpan data ini?",
icon: "warning",
showCancelButton: true,
cancelButtonColor: "#d33",
confirmButtonColor: "#3085d6",
confirmButtonText: "Simpan",
}).then((result) => {
if (result.isConfirmed) {
save(data);
}
});
};
const [showRewriteEditor, setShowRewriteEditor] = useState(false);
// const handleRewriteClick = () => {
// setShowRewriteEditor(true);
// };
const handleRewriteClick = async () => {
setIsContentRewriteClicked(true);
const request = {
style: selectedWritingStyle,
lang: "id",
contextType: "text",
urlContext: null,
context: detail?.contentDescription,
createdBy: roleId,
sentiment: "Humorous",
clientId: "7QTW8cMojyayt6qnhqTOeJaBI70W4EaQ",
};
const res = await generateDataRewrite(request);
close();
if (res?.error) {
console.error(res.message);
return false;
}
const newArticleId = res?.data?.data?.id;
setIsGeneratedArticle(true);
setArticleIds((prevIds: string[]) => {
if (prevIds.length < 3) {
return [...prevIds, newArticleId];
} else {
const updatedIds = [...prevIds];
updatedIds[2] = newArticleId;
return updatedIds;
}
});
Cookies.set("nulisAIArticleIdTemp", JSON.stringify(articleIds));
setShowRewriteEditor(true);
};
const handleArticleIdClick = async (id: string) => {
setIsLoadingData(true);
let retryCount = 0;
const maxRetries = 20;
try {
const waitForStatusUpdate = async () => {
while (retryCount < maxRetries) {
const res = await getDetailArticle(id);
const articleData = res?.data?.data;
if (articleData?.status === 2) {
return articleData;
}
retryCount++;
await new Promise((resolve) => setTimeout(resolve, 5000));
}
throw new Error("Timeout: Artikel belum selesai diproses.");
};
const articleData = await waitForStatusUpdate();
const cleanArticleBody = articleData?.articleBody?.replace(
/<img[^>]*>/g,
""
);
const articleImagesData = articleData?.imagesUrl?.split(",");
setArticleBody(cleanArticleBody || "");
setDetailData(articleData);
setSelectedArticleId(id);
// setArticleImages(articleImagesData || []);
} catch (error) {
console.error("Error fetching article details:", error);
} finally {
setIsLoadingData(false);
}
};
function deleteSpitContent() {
MySwal.fire({
title: "Apakah anda ingin menghapus konten?",
showCancelButton: true,
confirmButtonColor: "#dc3545",
confirmButtonText: "Iya",
cancelButtonText: "Tidak",
}).then((result) => {
if (result.isConfirmed) {
doDeleteSPIT();
}
});
}
async function doDeleteSPIT() {
const response = await deleteSPIT(id);
if (response?.error) {
error(response.message);
return false;
}
successBack();
}
function successBack() {
MySwal?.fire({
title: "Sukses",
icon: "success",
confirmButtonColor: "#3085d6",
confirmButtonText: "OK",
}).then((result) => {
if (result.isConfirmed) {
if (window.history.state && window.history.state.idx > 0) {
console.log("backkkkk");
console.log(window.history.state);
router.back();
} else {
router.push("/in/contributor/content/spit");
}
}
});
}
return (
<>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)}>
{detail !== undefined ? (
<div className="flex flex-col lg:flex-row gap-10">
<Card className="w-full lg:w-8/12">
<div className="px-6 py-6">
<p className="text-lg font-semibold mb-3">{t("form-spit")}</p>
<div className="gap-5 mb-5">
{/* Input Title */}
<div className="space-y-2 py-3">
<Label>{t("title")}</Label>
<Controller
control={form.control}
name="contentTitle"
render={({ field }) => (
<Input
size="md"
type="text"
value={field.value}
onChange={field.onChange}
placeholder="Enter contentTitle"
/>
)}
/>
</div>
<div className="flex items-center">
<div className="py-3 w-full space-y-2">
<Label>{t("category")}</Label>
<Select
defaultValue={detail?.content?.name}
onValueChange={(id) => {
console.log("Selected Category ID:", id);
setSelectedCategoryId(Number(id)); // Simpan ID kategori
}}
>
<SelectTrigger size="md">
<SelectValue placeholder="Pilih" />
</SelectTrigger>
<SelectContent>
{categories.map((category) => (
<SelectItem
key={category.id}
value={category.id.toString()} // ID kategori dikirim sebagai value
>
{category?.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="">
<RadioGroup
onValueChange={(value) => setSelectedFileType(value)}
value={selectedFileType}
className=" grid-cols-1"
>
<div className="">
<RadioGroupItem value="original" id="original-file" />
<Label htmlFor="original-file">
Select Original File
</Label>
</div>
<div className="py-3 space-y-2">
<Label>{t("description")}</Label>
<Controller
control={form.control}
name="contentDescription"
render={({ field: { onChange, value } }) => (
// <JoditEditor
// ref={editor}
// value={detail?.contentDescription}
// onChange={onChange}
// className="dark:text-black"
// />
<CustomEditor
onChange={onChange}
initialData={detail?.contentDescription}
/>
)}
/>
</div>
<p className="text-sm font-semibold">Content Rewrite</p>
<div className="space-y-2 pb-3 w-4/12">
<Label>{t("writing-style")}</Label>
<Select
value={selectedWritingStyle}
onValueChange={setSelectedWritingStyle}
>
<SelectTrigger size="md">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="friendly">Friendly</SelectItem>
<SelectItem value="professional">
Profesional
</SelectItem>
<SelectItem value="informational">
Informational
</SelectItem>
<SelectItem value="neutral">Neutral</SelectItem>
<SelectItem value="witty">Witty</SelectItem>
</SelectContent>
</Select>
</div>
<div className="my-2">
<Button
size="sm"
type="button"
onClick={handleRewriteClick}
className="bg-blue-500 text-white py-2 px-4 rounded"
>
Content Rewrite
</Button>
</div>
{showRewriteEditor && (
<div>
{isGeneratedArticle && (
<div className="mt-3 pb-0 flex flex-row ">
{articleIds.map((id: string, index: number) => (
<Button
type="button"
key={index}
className={`mr-3 px-3 py-2 rounded-md ${
selectedArticleId === id
? "bg-green-500 text-white"
: "border-2 border-green-500 bg-white text-green-500 hover:bg-green-500 hover:text-white hover:border-green-500"
}`}
onClick={() => handleArticleIdClick(id)}
>
{"Narasi " + (index + 1)}
</Button>
))}
</div>
)}
<div className="flex items-center space-x-2 mt-3">
<RadioGroupItem
value="rewrite"
id="rewrite-file"
/>
<Label htmlFor="rewrite-file">
Select File Rewrite
</Label>
</div>
<div className="py-3 space-y-2">
<Label>{t("file-rewrite")}</Label>
<Controller
control={form.control}
name="contentRewriteDescription"
render={({ field: { onChange, value } }) =>
isLoadingData ? (
<div className="flex justify-center items-center h-40">
<p className="text-gray-500">
Loading Proses Data...
</p>
</div>
) : (
<CustomEditor
onChange={onChange}
initialData={articleBody || value}
/>
)
}
/>
</div>
</div>
)}
</RadioGroup>
</div>
<div className="space-y-2">
<Label className="text-xl">{t("file-media")}</Label>
<div className="w-full ">
<Swiper
thumbs={{ swiper: thumbsSwiper }}
modules={[FreeMode, Navigation, Thumbs]}
navigation={false}
className="w-full"
>
{detailThumb?.map((data: any) => (
<SwiperSlide key={data.id}>
<img
className="object-fill h-full w-full rounded-md"
src={data}
alt={` ${data.id}`}
/>
</SwiperSlide>
))}
</Swiper>
<div className=" mt-2 ">
<Swiper
onSwiper={setThumbsSwiper}
slidesPerView={8}
spaceBetween={8}
pagination={{
clickable: true,
}}
modules={[Pagination, Thumbs]}
// className="mySwiper2"
>
{detailThumb?.map((data: any) => (
<SwiperSlide key={data.id}>
<img
className="object-cover h-[60px] w-[80px] rounded-md"
src={data}
alt={` ${data.id}`}
/>
</SwiperSlide>
))}
</Swiper>
</div>
</div>
</div>
<div className="mt-3">
<Label className="text-xl">{t("file-placement")}</Label>
</div>
{files?.length > 1 && (
<div className="flex flex-wrap gap-2 mt-2 justify-end mr-24 pr-2">
<div className="flex items-center space-x-2">
<Checkbox
id="all-content"
onCheckedChange={(e) =>
handleSelectAll("all", Boolean(e))
}
/>
<label
htmlFor="all-content"
className="text-xs font-medium"
>
{t("all")}
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="all-nasional"
onCheckedChange={(e) =>
handleSelectAll("mabes", Boolean(e))
}
/>
<label
htmlFor="all-nasional"
className="text-xs font-medium"
>
{t("all")} Nasional
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="all-wilayah"
onCheckedChange={(e) =>
handleSelectAll("polda", Boolean(e))
}
/>
<label
htmlFor="all-wilayah"
className="text-xs font-medium"
>
{t("all")} Wilayah
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="all-international"
onCheckedChange={(e) =>
handleSelectAll("international", Boolean(e))
}
/>
<label
htmlFor="all-international"
className="text-xs font-medium"
>
{t("all")} Internasional
</label>
</div>
</div>
)}
{files?.map((file, index) => (
<div
key={file.contentId}
className="flex flex-row gap-2 items-center my-3"
>
<img
src={file.contentFile}
className="w-[180px] rounded-md"
/>
<div className="flex flex-col gap-2 w-full pl-4">
<div className="flex justify-between text-sm">
{file.fileName}
</div>
<div className="flex flex-wrap gap-2">
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
value="all"
checked={filePlacements[index]?.includes("all")}
onCheckedChange={(e) =>
setupPlacement(index, "all", Boolean(e))
}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
{t("all")}
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={filePlacements[index]?.includes(
"mabes"
)}
onCheckedChange={(e) =>
setupPlacement(index, "mabes", Boolean(e))
}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Nasional
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={filePlacements[index]?.includes(
"polda"
)}
onCheckedChange={(e) =>
setupPlacement(index, "polda", Boolean(e))
}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Wilayah
</label>
</div>
<div className="flex items-center space-x-2">
<Checkbox
id="terms"
checked={filePlacements[index]?.includes(
"international"
)}
onCheckedChange={(e) =>
setupPlacement(
index,
"international",
Boolean(e)
)
}
/>
<label
htmlFor="terms"
className="text-xs font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
>
Internasional
</label>
</div>
</div>
</div>
</div>
))}
</div>
</div>
</Card>
<div className="w-full lg:w-4/12">
<Card className=" h-[800px]">
<div className="px-3 py-3">
<div className="space-y-2">
<Label>{t("creator")}</Label>
<Controller
control={form.control}
name="contentCreator"
render={({ field }) => (
<Input
size="md"
type="text"
value={detail?.contentCreator}
onChange={field.onChange}
placeholder="Enter Title"
/>
)}
/>
</div>
</div>
<div className="mt-3 px-3">
<Label>{t("preview")}</Label>
<Card className="mt-2">
<img
src={detail.contentThumbnail}
alt="Thumbnail Gambar Utama"
className="w-full h-auto rounded"
/>
</Card>
</div>
<div className="px-3 py-3">
<div className="space-y-2">
<Label>{t("tags")}</Label>
<div className="flex flex-wrap gap-2">
{detail?.contentTag
?.split(",")
.map((tag: any, index: any) => (
<Badge
key={index}
className="border rounded-md px-2 py-2"
>
{tag.trim()}
</Badge>
))}
</div>
</div>
</div>
<div className="px-3 py-3">
<div className="flex flex-col gap-3 space-y-2">
<Label>{t("publish-target")}</Label>
{options.map((option) => (
<div
key={option.id}
className="flex gap-2 items-center"
>
<Checkbox
id={option.id}
checked={
option.id === "all"
? publishedFor.length ===
options.filter((opt: any) => opt.id !== "all")
.length
: publishedFor.includes(option.id)
}
onCheckedChange={() =>
handleCheckboxChange(option.id)
}
/>
<Label htmlFor={option.id}>{option.label}</Label>
</div>
))}
</div>
</div>
</Card>
<div className="flex flex-row justify-end gap-3">
<div className="mt-4">
<Button type="submit" color="primary">
{t("submit")}
</Button>
</div>
<div className="mt-4">
<Button
type="submit"
className="bg-red-500 hover:bg-red-700"
onClick={() => deleteSpitContent()}
>
{t("cancel")}
</Button>
</div>
</div>
</div>
</div>
) : (
""
)}
</form>
</Form>
</>
);
}