"use client";
import React, { useEffect, useRef, useState } from "react";
import { useForm, Controller } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  deleteArticle,
  deleteArticleFile,
  getArticleDetail,
  listEnableCategory,
  updateArticle,
  uploadThumbnail,
} from "@/service/content/content";
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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { useParams, useRouter } from "next/navigation";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import dynamic from "next/dynamic";
import { error, loading, close, successAutoClose } from "@/lib/swal";
import { htmlToString } from "@/utils/globals";
import { listArticleCategories, uploadArticleFiles } from "@/service/content";
import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
import "swiper/css/thumbs";
import { FreeMode, Navigation, Pagination, Thumbs } from "swiper/modules";
import { useDropzone } from "react-dropzone";
import { CloudUpload } from "lucide-react";
import { TimeIcon, TimesIcon } from "@/components/icons";

const CustomEditor = dynamic(
  () => import("@/components/editor/custom-editor"),
  { ssr: false }
);

const videoSchema = z.object({
  title: z.string().min(1, "Judul diperlukan"),
  description: z.string().min(2, "Deskripsi diperlukan"),
  creatorName: z.string().min(1, "Creator diperlukan"),
  files: z
    .array(z.any())
    .optional()
    .refine(
      (files) =>
        !files ||
        files.every(
          (file: File) =>
            ["video/mp4", "video/mov", "video/avi"].includes(file.type) &&
            file.size <= 100 * 1024 * 1024
        ),
      {
        message:
          "Hanya file .mp4, .mov, .avi, maksimal 100MB yang diperbolehkan.",
      }
    ),
  publishedFor: z
    .array(z.string())
    .min(1, { message: "Minimal 1 target publish harus dipilih." }),
});

type VideoSchema = z.infer<typeof videoSchema>;

type Category = {
  id: number;
  title: string;
};

interface FileWithPreview extends File {
  preview: string;
}

type Option = {
  id: string;
  label: string;
};

interface DetailFile {
  id: number;
  fileUrl: string;
  fileName: string;
}

const options: Option[] = [
  { id: "all", label: "SEMUA" },
  { id: "4", label: "UMUM" },
  { id: "5", label: "JOURNALIS" },
];

export default function FormVideoUpdate() {
  const MySwal = withReactContent(Swal);
  const { id } = useParams() as { id: string };
  const router = useRouter();

  const [detail, setDetail] = useState<any>(null);
  const [categories, setCategories] = useState<Category[]>([]);
  const [tags, setTags] = useState<string[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [publishedFor, setPublishedFor] = useState<string[]>([]);
  const inputRef = useRef<HTMLInputElement>(null);
  const [files, setFiles] = useState<FileWithPreview[]>([]);
  const [thumbsSwiper, setThumbsSwiper] = useState<any>(null);
  const [detailFiles, setDetailFiles] = useState<DetailFile[]>([]);

  const { getRootProps, getInputProps } = useDropzone({
    accept: {
      "video/mp4": [".mp4"],
      "video/quicktime": [".mov"],
    },
    maxSize: 500 * 1024 * 1024,
    multiple: true,
    onDrop: (acceptedFiles, fileRejections) => {
      if (fileRejections.length > 0) {
        const messages = fileRejections
          .map((rej) => rej.errors.map((e) => e.message).join(", "))
          .join(", ");
        return;
      }

      const filesWithPreview = acceptedFiles.map((file) =>
        Object.assign(file, { preview: URL.createObjectURL(file) })
      );

      setFiles((prev) => {
        const updatedFiles = [...prev, ...filesWithPreview];
        setValue("files", updatedFiles, { shouldValidate: true });
        return updatedFiles;
      });
    },
  });

  const {
    control,
    handleSubmit,
    setValue,
    formState: { errors },
  } = useForm<VideoSchema>({
    resolver: zodResolver(videoSchema),
    defaultValues: { publishedFor: [] },
  });

  // 🧩 Fetch data detail + category
  useEffect(() => {
    loadData();
  }, [id, setValue]);

  async function loadData() {
    try {
      loading();
      const [detailRes, categoryRes] = await Promise.all([
        getArticleDetail(Number(id)),
        listArticleCategories(1, 100),
      ]);
      close();

      const detailData = detailRes?.data?.data;
      setDetail(detailData);
      const catData = categoryRes?.data?.data || [];
      setCategories(catData);

      // Prefill form
      setDetailFiles(detailData.files);
      setValue("title", detailData.title);
      setValue("description", detailData.htmlDescription);
      setValue("creatorName", detailData.createdByName ?? "");
      setSelectedCategory(String(detailData.categories[0].id));

      setTags(detailData.tags?.split(",").map((t: string) => t.trim()) || []);
      setPublishedFor(detailData.publishedFor?.split(",") || []);
    } catch (err) {
      close();
      console.error("❌ Error loading detail:", err);
    }
  }

  const handleAddTag = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Enter" && e.currentTarget.value.trim()) {
      e.preventDefault();
      const newTag = e.currentTarget.value.trim();
      if (!tags.includes(newTag)) {
        setTags([...tags, newTag]);
      }
      e.currentTarget.value = "";
    }
  };

  const handleRemoveTag = (index: number) => {
    setTags(tags.filter((_, i) => i !== index));
  };

  const handleCheckboxChange = (value: string) => {
    setPublishedFor((prev) =>
      prev.includes(value) ? prev.filter((v) => v !== value) : [...prev, value]
    );
  };

  const onSubmit = async (data: VideoSchema) => {
    try {
      loading();

      const payload = {
        aiArticleId: detail?.aiArticleId ?? "",
        categoryIds: selectedCategory ?? "",
        createdById: detail?.createdById ?? "",
        description: htmlToString(data.description),
        htmlDescription: data.description,
        isDraft: false,
        isPublish: true,
        slug: detail?.slug ?? data.title.toLowerCase().replace(/\s+/g, "-"),
        statusId: detail?.statusId ?? 1,
        tags: tags.join(","),
        title: data.title,
        typeId: detail?.typeId ?? 2,
      };

      console.log("📤 Payload Update:", payload);

      const res = await updateArticle(Number(id), payload);

      if (res?.error) {
        error(res.message || "Gagal memperbarui data");
        return;
      }

      // if (selectedFile) {
      //   const form = new FormData();
      //   form.append("file", selectedFile);
      //   await uploadThumbnail(id, form);
      // }
      if (files.length > 0) {
        const formData = new FormData();

        // Add all files to FormData
        files.forEach((file, index) => {
          formData.append("files", file);
        });
        const uploadResponse = await uploadArticleFiles(id, formData);
      }

      close();
      successAutoClose("Video berhasil diperbarui!");
      router.push("/admin/content/video");
    } catch (err) {
      close();
      console.error("❌ Update error:", err);
      error("Terjadi kesalahan saat menyimpan data.");
    }
  };

  const handleRemoveFile = (file: FileWithPreview) => {
    const uploadedFiles = files;
    const filtered = uploadedFiles.filter((i) => i.name !== file.name);
    setFiles([...filtered]);
  };

  const handleDeleteFile = async (id: number) => {
    const res = await deleteArticleFile(id);
    loadData();
  };

  if (!detail) return <p className="p-5 text-center">Memuat data...</p>;

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="flex flex-col lg:flex-row gap-10">
        {/* Left Side */}
        <Card className="w-full lg:w-8/12 p-6">
          <h2 className="text-lg font-semibold mb-4">Update Video</h2>

          {/* Title */}
          <div className="mb-4">
            <Label>Judul</Label>
            <Controller
              control={control}
              name="title"
              render={({ field }) => (
                <Input {...field} placeholder="Masukkan judul video" />
              )}
            />
            {errors.title && (
              <p className="text-red-500 text-sm">{errors.title.message}</p>
            )}
          </div>

          {/* Category */}
          <div className="mb-4">
            <Label>Kategori</Label>
            <Select
              value={selectedCategory}
              onValueChange={setSelectedCategory}
            >
              <SelectTrigger>
                <SelectValue placeholder="Pilih kategori" />
              </SelectTrigger>
              <SelectContent>
                {categories?.map((cat) => (
                  <SelectItem key={cat.id} value={String(cat.id)}>
                    {cat.title}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          {/* Description */}
          <div className="mb-4">
            <Label>Deskripsi</Label>
            <Controller
              control={control}
              name="description"
              render={({ field }) => (
                <CustomEditor
                  onChange={field.onChange}
                  initialData={field.value}
                />
              )}
            />
            {errors.description && (
              <p className="text-red-500 text-sm">
                {errors.description.message}
              </p>
            )}
          </div>

          <div className="space-y-2">
            <Label className="text-xl">File Media</Label>
            <div {...getRootProps({ className: "dropzone" })}>
              <input {...getInputProps()} />
              <div className=" w-full text-center border-dashed border border-default-200 dark:border-default-300  rounded-md py-[52px] flex  items-center flex-col">
                <CloudUpload className="text-default-300 w-10 h-10" />
                <h4 className=" text-2xl font-medium mb-1 mt-3 text-card-foreground/80">
                  {/* Drop files here or click to upload. */}
                  Drag File
                </h4>
                <div className=" text-xs text-muted-foreground">
                  Upload File Video Max
                </div>
              </div>
            </div>
            <div className="flex flex-col gap-2">
              {detailFiles.map((file) => (
                <div key={file.id} className="flex flex-row items-center gap-4">
                  <video
                    className="object-contain w-[300px] h-[200px]"
                    src={file.fileUrl}
                    controls
                    title={file.fileName}
                  />

                  <p>{file.fileName}</p>
                  <a
                    className="text-destructive"
                    onClick={() => handleDeleteFile(file.id)}
                  >
                    <TimesIcon />
                  </a>
                </div>
              ))}
              {files?.map((file) => (
                <div
                  key={file.name}
                  className="flex flex-row items-center gap-4"
                >
                  <video
                    className="object-contain w-[300px] h-[200px]"
                    src={file.preview}
                    controls
                    title={file.name}
                  />

                  <p>{file.name}</p>
                  <a
                    className="text-destructive"
                    onClick={() => handleRemoveFile(file)}
                  >
                    <TimesIcon />
                  </a>
                </div>
              ))}
            </div>
          </div>
        </Card>

        {/* Right Side */}
        <div className="w-full lg:w-4/12 space-y-4">
          <Card className="p-4">
            <Label>Creator</Label>
            <Controller
              control={control}
              name="creatorName"
              render={({ field }) => <Input {...field}  />}
            />

            <div className="mt-3 space-y-2">
              <Label>Thumbnail</Label>
              <Input
                type="file"
                accept="image/*"
                onChange={(e) =>
                  e.target.files && setSelectedFile(e.target.files[0])
                }
              />
              <div className="mt-2">
                {selectedFile ? (
                  <img
                    src={URL.createObjectURL(selectedFile)}
                    alt="Preview"
                    className="rounded"
                  />
                ) : (
                  <img
                    src={detail.thumbnailUrl}
                    alt="Current Thumbnail"
                    className="rounded"
                  />
                )}
              </div>
            </div>

            <div className="mt-4">
              <Label>Tags</Label>
              <Input
                type="text"
                placeholder="Tambahkan tag dan tekan Enter"
                onKeyDown={handleAddTag}
                ref={inputRef}
              />
              <div className="flex flex-wrap gap-2 mt-2">
                {tags.map((tag, index) => (
                  <Badge key={index} className="bg-black text-white px-2 py-1">
                    {tag}
                    <button
                      type="button"
                      onClick={() => handleRemoveTag(index)}
                      className="ml-2 text-xs"
                    >
                      ✕
                    </button>
                  </Badge>
                ))}
              </div>
            </div>

            <div className="mt-4 space-y-2">
              <Label>Publish Target</Label>
              <Controller
                control={control}
                name="publishedFor"
                render={({ field }) => (
                  <div className="py-3">
                    <div className="flex flex-col gap-3 space-y-2">
                      {options.map((option) => {
                        const isAllChecked =
                          field.value.length ===
                          options.filter((opt: any) => opt.id !== "all").length;

                        const isChecked =
                          option.id === "all"
                            ? isAllChecked
                            : field.value.includes(option.id);

                        const handleChange = () => {
                          let updated: string[] = [];

                          if (option.id === "all") {
                            updated = isAllChecked
                              ? []
                              : options
                                  .filter((opt: any) => opt.id !== "all")
                                  .map((opt: any) => opt.id);
                          } else {
                            updated = isChecked
                              ? field.value.filter((val) => val !== option.id)
                              : [...field.value, option.id];

                            if (isAllChecked && option.id !== "all") {
                              updated = updated.filter((val) => val !== "all");
                            }
                          }

                          field.onChange(updated);
                          setPublishedFor(updated);
                        };

                        return (
                          <div
                            key={option.id}
                            className="flex gap-2 items-center"
                          >
                            <Checkbox
                              id={option.id}
                              checked={isChecked}
                              onCheckedChange={handleChange}
                              className="border"
                            />
                            <Label htmlFor={option.id}>{option.label}</Label>
                          </div>
                        );
                      })}

                      {errors.publishedFor && (
                        <p className="text-red-500 text-sm">
                          {errors.publishedFor.message}
                        </p>
                      )}
                    </div>
                  </div>
                )}
              />
            </div>

            <div className="flex justify-end gap-3 mt-5">
              <Button type="submit">Update</Button>
              <Button
                type="button"
                variant="outline"
                onClick={() => router.back()}
              >
                Cancel
              </Button>
            </div>
          </Card>
        </div>
      </div>
    </form>
  );
}
