"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, CardContent } 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 { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import Cookies from "js-cookie";
import { postBlog } from "@/service/blog/blog";
import { Textarea } from "@/components/ui/textarea";
import { DotSquare, InboxIcon, PaperclipIcon, SmileIcon } from "lucide-react";
import { detailMedia } from "@/service/curated-content/curated-content";
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 { Avatar, AvatarImage } from "@/components/ui/avatar";
import { Badge } from "@/components/ui/badge";

const detailSchema = z.object({
  title: z.string().min(1, { message: "Judul diperlukan" }),
  categoryName: z.string().min(1, { message: "Judul diperlukan" }),
  meta: z.string().min(1, { message: "Judul diperlukan" }),
  description: z
    .string()
    .min(2, { message: "Narasi Penugasan harus lebih dari 2 karakter." }),
  // tags: z.string().min(1, { message: "Judul diperlukan" }),
});

type Category = {
  id: string;
  categoryName: string;
};

export type curationDetail = {
  id: number;
  title: string;
  categoryName: string;
  description: string;
  uploadedBy: {
    id: number;
    fullname: string;
    username: string | null;
    email: string;
    isActive: boolean;
    isDefault: boolean;
    isInternational: boolean;
    userLevel: {
      id: number;
      name: string;
      aliasName: string;
      userGroupId: number;
    };
  };
  tags: string;
  provinceId: string;
  is_active: string;
};

const initialComments = [
  {
    id: 1,
    username: "Esther Howard",
    date: "07-04-2023 20:00 WIB",
    text: "Tolong untuk narasinya mengikuti 5W + 1H!",
    avatar: "/images/avatar/avatar-3.png", // URL avatar atau path gambar pengguna
    replies: [], // Komentar balasan
  },
  {
    id: 2,
    username: "Brooklyn Simmons",
    date: "07-04-2023 20:00 WIB",
    text: "Ok Baik, Saya segera melakukan perbaikan. Terima kasih atas masukannya. 🙏",
    avatar: "/images/avatar/avatar-5.png", // URL avatar atau path gambar pengguna
    replies: [], // Komentar balasan
  },
  {
    id: 3,
    username: "Leslie Alexander",
    date: "07-04-2023 20:00 WIB",
    text: "Sangat berguna. Terima Kasih!",
    avatar: "/images/avatar/avatar-7.png", // URL avatar atau path gambar pengguna
    replies: [], // Komentar balasan
  },
];

export default function DetailImage() {
  const MySwal = withReactContent(Swal);
  const { id } = useParams() as { id: string };
  console.log(id);
  const editor = useRef(null);
  type DetailSchema = z.infer<typeof detailSchema>;

  const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
  const taskId = Cookies.get("taskId");
  const scheduleId = Cookies.get("scheduleId");
  const scheduleType = Cookies.get("scheduleType");
  const [selectedTarget, setSelectedTarget] = useState("");
  // const [detail, setDetail] = useState({
  //   title: null,
  //   tags: null,
  //   files: [],
  //   fileType: null,
  // });
  const [detail, setDetail] = useState<curationDetail>();
  const [refresh] = useState(false);
  const [detailVideo, setDetailVideo] = useState<any>([]);
  const [detailThumb, setDetailThumb] = useState<any>([]);
  const [thumbsSwiper, setThumbsSwiper] = useState<any>(null);

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<DetailSchema>({
    resolver: zodResolver(detailSchema),
  });

  const [commentsData, setCommentsData] = useState(initialComments);
  const [replyText, setReplyText] = useState("");
  const [replyingTo, setReplyingTo] = useState<number | null>(null);

  const handleReply = (commentId: number) => {
    setReplyingTo(commentId);
  };

  const addReply = (commentId: number) => {
    if (replyText.trim()) {
      const newCommentData = commentsData.map((comment: any) => {
        if (comment.id === commentId) {
          return {
            ...comment,
            replies: [
              ...comment.replies,
              {
                text: replyText,
                username: "You",
                date: new Date().toLocaleString(),
              },
            ],
          };
        }
        return comment;
      });

      setCommentsData(newCommentData);
      setReplyText("");
      setReplyingTo(null);
    }
  };

  useEffect(() => {
    async function initState() {
      if (id) {
        const response = await detailMedia(id);
        const details = response?.data?.data;

        setDetail(details);
        const filesData = details.files || [];
        const fileUrls = filesData.map((file: { url: string }) =>
          file.url ? file.url : "default-image.jpg"
        );
        setDetailVideo(fileUrls);
        const filesDataThumbnail = details.files || [];
        const fileUrlsThumbnail = filesDataThumbnail.map(
          (file: { thumbnailFileUrl: string }) =>
            file.thumbnailFileUrl ? file.thumbnailFileUrl : "default-image.jpg"
        );
        setDetailThumb(fileUrlsThumbnail);
      }
    }
    initState();
  }, [id, refresh]);

  return (
    <div className="flex gap-10">
      {detail !== undefined ? (
        <Card className="w-full ">
          <div className="px-6 py-6">
            <p className="text-lg font-semibold mb-3">Kurasi Detail</p>
            <CardContent className="border rounded-md">
              <div className="flex flex-row gap-10">
                <div className="w-6/12">
                  <div className="gap-5 mb-5">
                    <div className="space-y-2 py-3">
                      <Label>Judul</Label>
                      <Controller
                        control={control}
                        name="title"
                        render={({ field }) => (
                          <Input
                            size="md"
                            type="text"
                            value={field.value}
                            onChange={field.onChange}
                            placeholder="Enter Title"
                            defaultValue={detail.title}
                          />
                        )}
                      />
                      {errors.title?.message && (
                        <p className="text-red-400 text-sm">
                          {errors.title.message}
                        </p>
                      )}
                    </div>
                    <div className="flex items-center">
                      <div className="py-3 w-full">
                        <Label>Kategori</Label>
                        <Controller
                          control={control}
                          name="categoryName"
                          render={({ field }) => (
                            <Input
                              size="md"
                              type="text"
                              value={field.value}
                              onChange={field.onChange}
                              placeholder="Enter Title"
                              defaultValue={detail.categoryName}
                            />
                          )}
                        />
                      </div>
                    </div>
                    <div className=" py-3">
                      <div className="space-y-2">
                        <Label>Description</Label>
                        <Controller
                          control={control}
                          name="description"
                          render={({ field }) => (
                            <Textarea
                              value={detail.description}
                              onChange={field.onChange}
                              placeholder="Enter Meta"
                              cols={5}
                            />
                          )}
                        />
                        {errors.description?.message && (
                          <p className="text-red-400 text-sm">
                            {errors.description.message}
                          </p>
                        )}
                      </div>
                    </div>
                  </div>
                </div>
                <div className="w-6/12">
                  <div className="gap-5 mb-5">
                    <div className="mt-5">
                      <Label>Jenis Penugasan</Label>
                      <RadioGroup
                        // value={type} // State yang dipetakan ke value RadioGroup
                        // onValueChange={(value) => setType(value)} // Mengubah nilai state ketika pilihan berubah
                        className="flex flex-wrap gap-3"
                      >
                        <div className="flex items-center gap-2">
                          <RadioGroupItem value="1" id="publication" />
                          <Label htmlFor="umum">Umum</Label>
                        </div>
                        <div className="flex items-center gap-2">
                          <RadioGroupItem value="2" id="amplification" />
                          <Label htmlFor="ksp">Ksp</Label>
                        </div>
                        <div className="flex items-center gap-2">
                          <RadioGroupItem value="3" id="contra" />
                          <Label htmlFor="journalist">Journalist</Label>
                        </div>
                        <div className="flex items-center gap-2">
                          <RadioGroupItem value="4" id="contra" />
                          <Label htmlFor="polri">Polri</Label>
                        </div>
                      </RadioGroup>
                    </div>
                    <div className="py-3">
                      <div className="space-y-2">
                        <Label>Tag</Label>
                        <div className="flex flex-wrap gap-2">
                          {detail?.tags?.split(",").map((tag, index) => (
                            <Badge
                              key={index}
                              className="border rounded-md  px-2 py-2"
                            >
                              {tag.trim()}
                            </Badge>
                          ))}
                        </div>
                      </div>
                    </div>
                    <div className=" py-3">
                      <div className="space-y-2">
                        <Label>
                          {" "}
                          {detail?.uploadedBy?.fullname ||
                            "Data tidak tersedia"}
                        </Label>
                      </div>
                    </div>
                    <div className=" py-3">
                      <div className="flex flex-row items-center gap-2 text-blue-500">
                        <InboxIcon />
                        <p className="text-blue-500">Kotak Saran (0)</p>
                      </div>
                    </div>

                    <Button>Content Rewrite</Button>
                  </div>
                </div>
              </div>
            </CardContent>
            <CardContent className="border rounded-md mt-5">
              <div className="flex flex-row gap-5">
                <div className="w-6/12 border px-3 mt-3 rounded-md">
                  <div className="gap-5 mb-5">
                    <div className="space-y-2 py-3">
                      <Label className="text-xl text-black">File Media</Label>
                      <div className="w-full">
                        <Swiper
                          thumbs={{ swiper: thumbsSwiper }}
                          modules={[FreeMode, Navigation, Thumbs]}
                          navigation={false}
                          className="w-full"
                        >
                          {detailVideo?.map((data: any) => (
                            <SwiperSlide key={data.id}>
                              <video
                                className="object-fill h-full w-full"
                                src={data}
                                controls
                                title={`Video ${data.id}`} // Mengganti alt dengan title
                              />
                            </SwiperSlide>
                          ))}
                        </Swiper>
                        <div className="mt-2">
                          <Swiper
                            onSwiper={setThumbsSwiper}
                            slidesPerView={6}
                            spaceBetween={8}
                            pagination={{
                              clickable: true,
                            }}
                            modules={[Pagination, Thumbs]}
                          >
                            {detailVideo?.map((data: any) => (
                              <SwiperSlide key={data.id}>
                                <video
                                  className="object-cover h-[60px] w-[80px]"
                                  src={data}
                                  muted
                                  title={`Video ${data.id}`} // Mengganti alt dengan title
                                />
                              </SwiperSlide>
                            ))}
                          </Swiper>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="w-6/12 border px-3 rounded-md mt-3">
                  <div className="gap-5 mb-5">
                    <div className="mt-5">
                      <Label className="text-xl text-black">
                        Penempatan File
                      </Label>
                      <div className="flex flex-row justify-between items-center">
                        <p>file</p>
                        <p>Penempatan</p>
                      </div>
                      <p className="bg-black h-1 w-full rounded-lg"></p>
                      {detailThumb?.map((data: any) => (
                        <div
                          key={data.id}
                          className="flex items-center gap-3 mt-2"
                        >
                          {/* <img
                            className="object-cover w-20 h-20"
                            src={data.thumbnailUrl} // Assuming `thumbnailUrl` is the property that contains the URL for the thumbnail image
                            alt={`Thumbnail ${index}`}
                          /> */}
                          <img
                            className="object-cover w-36 h-32"
                            src={data}
                            alt={` ${data.id}`}
                          />
                          <div className="flex flex-row gap-3 items-center">
                            <label className="text-blue-500 cursor-pointer">
                              <input
                                type="checkbox"
                                name="placement"
                                value="Nasional"
                              />
                              Nasional
                            </label>
                            <label className="text-blue-500 cursor-pointer">
                              <input
                                type="checkbox"
                                name="placement"
                                value="Wilayah"
                              />
                              Wilayah
                            </label>
                            <label className="text-blue-500 cursor-pointer">
                              <input
                                type="checkbox"
                                name="placement"
                                value="International"
                              />
                              International
                            </label>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </CardContent>
            <CardContent>
              <div className="gap-5 mb-5">
                <div className="mt-5">
                  <Label className="text-xl text-black">Berikan Komentar</Label>
                  <div className="flex items-start gap-3">
                    <Avatar>
                      <AvatarImage
                        src="/images/avatar/avatar-1.png"
                        alt="@shadcn"
                      />
                    </Avatar>

                    <textarea
                      className="flex-grow p-2 border rounded-lg focus:outline-none focus:border-yellow-400"
                      placeholder="Tuliskan komentar Anda di sini.."
                    ></textarea>
                  </div>
                  <div className="flex items-center mt-2 gap-3">
                    <button className="flex items-center text-gray-600 hover:text-gray-800">
                      <PaperclipIcon className="w-5 h-5" />
                      Lampirkan
                    </button>
                    <button className="flex items-center text-gray-600 hover:text-gray-800">
                      <SmileIcon className="w-5 h-5" />
                      Emoticon
                    </button>
                    <button className="ml-auto px-4 py-1 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600">
                      Kirim
                    </button>
                  </div>
                </div>

                <div className="mt-5">
                  <Label className="text-xl text-black">Komentar</Label>
                  {commentsData.map((comment) => (
                    <div
                      key={comment.id}
                      className="flex items-start gap-3 mt-2"
                    >
                      <Avatar>
                        <AvatarImage
                          src={comment.avatar}
                          alt={`@${comment.username}`}
                        />
                      </Avatar>
                      <div className="flex flex-col">
                        <span className="text-gray-700 font-semibold">
                          {comment.username}
                        </span>
                        <span className="text-gray-500 text-sm">
                          {comment.date}
                        </span>
                        <p className="text-gray-800 mt-1">{comment.text}</p>
                        <div
                          className="flex items-center mt-1 text-blue-500 cursor-pointer"
                          onClick={() => handleReply(comment.id)}
                        >
                          <DotSquare className="w-4 h-4" />
                          <span className="ml-1">Balas</span>
                        </div>
                        {comment.replies.length > 0 && (
                          <div className="ml-8 mt-2">
                            {comment.replies.map((reply: any, index: any) => (
                              <div
                                key={index}
                                className="flex items-start gap-3 mt-1"
                              >
                                <Avatar>
                                  <AvatarImage
                                    src="https://github.com/shadcn.png"
                                    alt={`@${reply.username}`}
                                  />
                                </Avatar>
                                <div className="flex flex-col">
                                  <span className="text-gray-700 font-semibold">
                                    {reply.username}
                                  </span>
                                  <span className="text-gray-500 text-sm">
                                    {reply.date}
                                  </span>
                                  <p className="text-gray-800 mt-1">
                                    {reply.text}
                                  </p>
                                </div>
                              </div>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                  {replyingTo !== null && (
                    <div className="mt-4">
                      <textarea
                        className="w-full p-2 border rounded-md"
                        rows={3}
                        placeholder="Tulis balasan..."
                        value={replyText}
                        onChange={(e) => setReplyText(e.target.value)}
                      ></textarea>
                      <button
                        className="mt-2 bg-yellow-500 text-white px-4 py-2 rounded-md"
                        onClick={() => addReply(replyingTo)}
                      >
                        Kirim
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </div>
        </Card>
      ) : (
        ""
      )}
    </div>
  );
}
