"use client";

import { useEffect, useState } from "react";
import {
  Upload,
  Plus,
  Settings,
  CheckCheck,
  Clock,
  Check,
  X,
} from "lucide-react";
import Image from "next/image";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardContent, CardTitle } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { error, loading, success } from "@/config/swal";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useDropzone } from "react-dropzone";
import z from "zod";
import dynamic from "next/dynamic";
import { useParams, useRouter } from "next/navigation";
import Cookies from "js-cookie";
import {
  approveProduct,
  commentProduct,
  getProductDataById,
  rejectProduct,
  updateProduct,
} from "@/service/product";
import { convertDateFormat } from "@/utils/global";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";

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

interface FileWithPreview extends File {
  preview: string;
}

interface CategoryType {
  id: number;
  label: string;
  value: number;
}
const categorySchema = z.object({
  id: z.number(),
  label: z.string(),
  value: z.number(),
});

const createArticleSchema = z.object({
  title: z.string().min(2, {
    message: "Judul harus diisi",
  }),
  variant: z.string().min(2, {
    message: "variant diisi",
  }),
  price: z.string().min(2, {
    message: "Price harus diisi",
  }),
  category: z.array(categorySchema).nonempty({
    message: "Kategori harus memiliki setidaknya satu item",
  }),
  tags: z.array(z.string()).nonempty({
    message: "Minimal 1 tag",
  }), // Array berisi string
});

export default function DetailProductForm(props: { isDetail: boolean }) {
  const { isDetail } = props;
  const params = useParams();
  const id = params?.id;
  const username = Cookies.get("username");
  const userId = Cookies.get("uie");
  const [files, setFiles] = useState<FileWithPreview[]>([]);
  const [useAi, setUseAI] = useState(false);
  const [listCategory, setListCategory] = useState<CategoryType[]>([]);
  const [tag, setTag] = useState("");
  const [detailfiles, setDetailFiles] = useState<any>([]);
  const [mainImage, setMainImage] = useState(0);
  const [thumbnail, setThumbnail] = useState("");
  const [diseId, setDiseId] = useState(0);
  const [thumbnailImg, setThumbnailImg] = useState<File[]>([]);
  const [selectedMainImage, setSelectedMainImage] = useState<number | null>(
    null,
  );
  const [thumbnailValidation, setThumbnailValidation] = useState("");
  // const { isOpen, onOpen, onOpenChange } = useDisclosure();
  const [isOpen, setIsOpen] = useState(false);
  const onOpen = () => setIsOpen(true);
  const onOpenChange = () => setIsOpen((prev) => !prev);
  const [approvalStatus, setApprovalStatus] = useState<number>(2);
  const [approvalMessage, setApprovalMessage] = useState("");
  const [detailData, setDetailData] = useState<any>();
  const [startDateValue, setStartDateValue] = useState<any>(null);
  const [timeValue, setTimeValue] = useState("00:00");
  const [openApproverHistory, setOpenApproverHistory] = useState(false);
  const [userLevelId, setUserLevelId] = useState<string | null>(null);

  const router = useRouter();

  // 🔹 Ambil userlevelId dari cookies
  const [userRoleId, setUserRoleId] = useState<string | null>(null);
  const MySwal = withReactContent(Swal);

  // 🔹 Ambil userlevelId dari cookies
  useEffect(() => {
    const urie = Cookies.get("urie"); // contoh: "3"
    setUserRoleId(urie ?? null);
  }, []);

  const { getRootProps, getInputProps } = useDropzone({
    onDrop: (acceptedFiles) => {
      setFiles((prevFiles) => [
        ...prevFiles,
        ...acceptedFiles.map((file) => Object.assign(file)),
      ]);
    },
    multiple: true,
    accept: {
      "image/*": [],
    },
  });

  const formOptions = {
    resolver: zodResolver(createArticleSchema),
    defaultValues: { title: "", description: "", category: [], tags: [] },
  };
  type UserSettingSchema = z.infer<typeof createArticleSchema>;
  const {
    register,
    control,
    handleSubmit,
    formState: { errors },
    setValue,
    getValues,
    watch,
    setError,
    clearErrors,
  } = useForm<UserSettingSchema>(formOptions);
  const [specs, setSpecs] = useState([
    {
      id: 1,
      title: "Jaecoo 7 SHS Teknologi dan Exterior",
      images: ["/spec1.jpg", "/spec2.jpg", "/spec3.jpg", "/spec4.jpg"],
    },
  ]);

  type ColorType = {
    id: number;
    name: string;
    preview: string;
    colorSelected: string | null;
  };

  const [colors, setColors] = useState<ColorType[]>([
    {
      id: 1,
      name: "",
      preview: "/car-1.png",
      colorSelected: null,
    },
    {
      id: 2,
      name: "",
      preview: "/car-2.png",
      colorSelected: null,
    },
  ]);

  const palette = [
    "#1E4E52",
    "#597E8D",
    "#6B6B6B",
    "#BEBEBE",
    "#E2E2E2",
    "#F4F4F4",
    "#FFFFFF",
    "#F9360A",
    "#9A2A00",
    "#7A1400",
    "#4B0200",
    "#B48B84",
    "#FFA598",
  ];

  const handleAddSpec = () => {
    setSpecs((prev) => [
      ...prev,
      {
        id: prev.length + 1,
        title: "",
        images: [],
      },
    ]);
  };

  const handleAddColor = () => {
    setColors((p) => [
      ...p,
      {
        id: p.length + 1,
        name: "",
        preview: "/car-default.png",
        colorSelected: null,
      },
    ]);
  };

  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false);
  const [openCommentModal, setOpenCommentModal] = useState(false);
  const [commentValue, setCommentValue] = useState("");
  const handleSubmitComment = async () => {
    // await api.post("/banner/comment", {
    //   bannerId: viewBanner.id,
    //   comment: commentValue,
    // });

    setOpenCommentModal(false);
  };

  const [uploadTarget, setUploadTarget] = useState<{
    type: "spec" | "color";
    index: number;
  } | null>(null);

  const fileInputId = "file-upload-input";

  const handleFileSelected = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (!file || !uploadTarget) return;

    const reader = new FileReader();
    reader.onload = () => {
      const fileUrl = reader.result as string;

      if (uploadTarget.type === "spec") {
        setSpecs((prev) => {
          const updated = [...prev];
          updated[uploadTarget.index].images.push(fileUrl);
          return updated;
        });
      }

      if (uploadTarget.type === "color") {
        setColors((prev) => {
          const updated = [...prev];
          updated[uploadTarget.index].preview = fileUrl;
          return updated;
        });
      }
    };

    reader.readAsDataURL(file);
    setIsUploadDialogOpen(false);
  };

  useEffect(() => {
    initState();
  }, [listCategory]);

  async function initState() {
    const res = await getProductDataById(id);
    const data = res?.data?.data;

    if (!data) return;

    setDetailData(data);

    // form
    setValue("title", data.title);
    setValue("variant", data.variant);
    setValue("price", formatRupiah(data.price));

    // thumbnail
    setThumbnail(data.thumbnail_url);

    // colors
    if (data.colors?.length) {
      setColors(
        data.colors.map((color: any, index: number) => ({
          id: index + 1,
          name: color.name || "",
          preview: color.image_url || data.thumbnail_url || "",
          colorSelected: color.name || null,
        })),
      );
    }

    // specifications
    if (data.specifications?.length) {
      setSpecs(
        data.specifications.map((spec: any, index: number) => ({
          id: index + 1,
          title: spec.title || "",
          images: spec.image_urls || [],
        })),
      );
    }
  }

  const handleCommentProduct = async (id: number) => {
    const { value: message } = await MySwal.fire({
      title: "Komen Produk",
      input: "textarea",
      inputLabel: "Komentar (opsional)",
      inputPlaceholder: "Masukkan komentar...",
      inputAttributes: {
        "aria-label": "Masukkan komentar",
      },
      showCancelButton: true,
      confirmButtonText: "Komentar",
      cancelButtonText: "Batal",
      confirmButtonColor: "#dc2626",
    });

    if (message === undefined) {
      return; // User cancelled
    }

    loading();
    const res = await commentProduct(id, message || undefined);

    if (res?.error) {
      error(res.message || "Gagal komentar produk");
      close();
      return;
    }

    close();
    success("Produk berhasil dikomentar");
    initState(); // refresh table
  };

  const handleRejectProduct = async (id: number) => {
    const MySwal = withReactContent(Swal);
    const { value: message } = await MySwal.fire({
      title: "Tolak Product",
      input: "textarea",
      inputLabel: "Alasan penolakan (opsional)",
      inputPlaceholder: "Masukkan alasan penolakan...",
      inputAttributes: {
        "aria-label": "Masukkan alasan penolakan",
      },
      showCancelButton: true,
      confirmButtonText: "Tolak",
      cancelButtonText: "Batal",
      confirmButtonColor: "#dc2626",
    });

    if (message === undefined) {
      return; // User cancelled
    }

    loading();
    const res = await rejectProduct(id, message || undefined);

    if (res?.error) {
      error(res.message || "Gagal menolak product");
      close();
      return;
    }

    close();
    success("Product berhasil ditolak");
    initState(); // refresh table
  };

  const handleApproveProduct = async (id: number) => {
    loading();
    const res = await approveProduct(id);

    if (res?.error) {
      error(res.message || "Gagal menyetujui product");
      close();
      return;
    }

    close();
    success("Product berhasil disetujui");
    initState(); // refresh table
  };

  const handleOpenApproverHistory = () => {
    setOpenApproverHistory(true);
  };

  const formatRupiah = (value: string) =>
    "Rp " + Number(value).toLocaleString("id-ID");

  return (
    <>
      <Card className="w-full border-none shadow-md">
        <CardHeader>
          <CardTitle className="text-xl font-bold text-teal-900">
            Detail Produk
          </CardTitle>
        </CardHeader>

        <CardContent className="space-y-8">
          <div className="grid md:grid-cols-3 gap-4">
            <div>
              <Controller
                control={control}
                name="title"
                render={({ field: { onChange, value } }) => (
                  <div className="w-full">
                    <label
                      htmlFor="title"
                      className="block text-sm font-medium mb-1"
                    >
                      Nama Produk <span className="text-red-500">*</span>
                    </label>
                    <Input
                      type="text"
                      id="title"
                      placeholder="Masukkan judul"
                      value={value ?? ""}
                      readOnly={isDetail}
                      onChange={onChange}
                      className="w-full border rounded-lg"
                    />
                  </div>
                )}
              />
            </div>

            <div>
              <Controller
                control={control}
                name="variant"
                render={({ field: { onChange, value } }) => (
                  <div className="w-full">
                    <label
                      htmlFor="variant"
                      className="block text-sm font-medium mb-1"
                    >
                      Variant <span className="text-red-500">*</span>
                    </label>
                    <Input
                      type="text"
                      id="title"
                      placeholder="Masukkan judul"
                      value={value ?? ""}
                      readOnly={isDetail}
                      onChange={onChange}
                      className="w-full border rounded-lg"
                    />
                  </div>
                )}
              />
            </div>

            <div>
              <Controller
                control={control}
                name="price"
                render={({ field: { onChange, value } }) => (
                  <div className="w-full">
                    <label
                      htmlFor="price"
                      className="block text-sm font-medium mb-1"
                    >
                      Variant <span className="text-red-500">*</span>
                    </label>
                    <Input
                      type="text"
                      id="price"
                      placeholder="Masukkan judul"
                      value={value ?? ""}
                      readOnly={isDetail}
                      onChange={onChange}
                      className="w-full border rounded-lg"
                    />
                  </div>
                )}
              />
            </div>
          </div>
          <div>
            <Label className="font-semibold">Banner</Label>
            <div className="mt-2 w-[120px] h-[80px] rounded-lg overflow-hidden border bg-gray-100">
              {thumbnail ? (
                <Image
                  src={thumbnail}
                  alt="Banner"
                  width={120}
                  height={80}
                  className="object-cover"
                />
              ) : (
                <div className="flex items-center justify-center text-xs text-gray-400 h-full">
                  No Image
                </div>
              )}
            </div>
          </div>

          <div>
            <Label className="font-semibold text-gray-700">Warna Produk</Label>

            <div className="mt-4 grid grid-cols-1 md:grid-cols-4 gap-6  border-2 rounded-lg border-black p-3 ">
              {colors.map((item, index) => (
                <div key={item.id} className="space-y-3">
                  <Label className="text-sm text-gray-500">
                    Warna {index + 1}
                  </Label>

                  {/* Preview warna */}
                  <div
                    className="w-12 h-12 rounded-full border"
                    style={{ backgroundColor: item.colorSelected ?? "#e5e7eb" }}
                  />

                  {/* Foto mobil */}
                  <div className="w-full h-[90px] border rounded-lg overflow-hidden">
                    <Image
                      src={item.preview}
                      alt="warna"
                      width={200}
                      height={120}
                      className="object-cover w-full h-full"
                    />
                  </div>

                  <p className="text-xs text-gray-500 text-center">
                    Foto Produk Warna {index + 1}
                  </p>
                </div>
              ))}
            </div>
          </div>

          <div>
            <Label className="text-lg font-semibold text-gray-800">
              Spesifikasi Produk
            </Label>

            {specs.map((spec) => (
              <div
                key={spec.id}
                className="mt-4 space-y-3 border-2 rounded-lg border-black p-3"
              >
                <Input value={spec.title} readOnly className="font-medium" />

                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  {spec.images.map((img, i) => (
                    <div key={i} className="border rounded-lg overflow-hidden">
                      <Image
                        src={img}
                        alt="spec"
                        width={200}
                        height={200}
                        className="object-cover w-full h-[120px]"
                      />
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
          <div>
            <h4 className="text-sm font-semibold text-gray-700 mb-3">
              Status Timeline
            </h4>

            <div className="space-y-4">
              <div className="flex gap-3">
                <div className="w-6 h-6 rounded-full bg-green-100 flex items-center justify-center">
                  <Check className="w-4 h-4 text-green-600" />
                </div>
                <div>
                  <p className="font-medium text-gray-800">
                    Diupload oleh Operator
                  </p>
                  <p className="text-sm text-gray-500">
                    {convertDateFormat(detailData?.created_at)} WIB
                  </p>
                </div>
              </div>
            </div>
            <div className="flex gap-3">
              <div
                className={`w-6 h-6 rounded-full flex items-center justify-center ${
                  detailData?.status_id === 1
                    ? "bg-yellow-100"
                    : detailData?.status_id === 2
                      ? "bg-green-100"
                      : "bg-red-100"
                }`}
              >
                {detailData?.status_id === 1 ? (
                  <Clock className="w-4 h-4 text-yellow-700" />
                ) : detailData?.status_id === 2 ? (
                  <Check className="w-4 h-4 text-green-600" />
                ) : (
                  <X className="w-4 h-4 text-red-700" />
                )}
              </div>

              <div>
                <p className="font-medium text-gray-800">
                  {detailData?.status_id === 1
                    ? "Menunggu disetujui oleh Approver"
                    : detailData?.status_id === 2
                      ? "Disetujui oleh Approver"
                      : "Ditolak oleh Approver"}
                </p>

                <p className="text-sm text-gray-500">
                  {convertDateFormat(detailData?.updated_at)} WIB
                </p>
              </div>
            </div>
          </div>
          <div className="border rounded-lg px-3 py-3">
            <p>Comment : </p>
            <div className="flex flex-row justify-between">
              <button
                onClick={handleOpenApproverHistory}
                className="text-sm text-blue-600 hover:underline mt-2"
              >
                View Approver History
              </button>
              <p>Jaecoo - Approver | 10/11/2026</p>
            </div>
          </div>
          {userRoleId !== "2" && detailData && (
            <div className="flex justify-between items-center gap-3 px-6 py-4 border-t bg-[#F2F7FA] mt-10">
              {detailData.status_id === 1 ? (
                <>
                  <Button
                    variant="secondary"
                    className="bg-blue-200 hover:bg-blue-400"
                    onClick={() => handleCommentProduct(detailData.id)}
                  >
                    Beri Tanggapan
                  </Button>

                  <Button
                    variant="destructive"
                    className="w-[180px]"
                    onClick={() => handleRejectProduct(detailData.id)}
                  >
                    Reject
                  </Button>

                  {userRoleId === "1" && (
                    <Button
                      className="bg-green-600 hover:bg-green-700 text-white w-[180px]"
                      onClick={() => handleApproveProduct(detailData.id)}
                    >
                      <CheckCheck className="w-4 h-4 mr-1" />
                      Approve
                    </Button>
                  )}
                </>
              ) : (
                <Button
                  variant="secondary"
                  className="mx-auto"
                  onClick={() => router.back()}
                >
                  Tutup
                </Button>
              )}
            </div>
          )}

          {/* <Button className=" bg-teal-800 hover:bg-teal-900 text-white py-3">
            Submit
          </Button> */}
        </CardContent>
      </Card>
      {openApproverHistory && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4"
          onClick={() => setOpenApproverHistory(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-3xl w-full overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            {/* HEADER */}
            <div className="bg-gradient-to-br from-[#1F6779] to-[#0F6C75] text-white px-6 py-5 relative">
              <button
                onClick={() => setOpenApproverHistory(false)}
                className="absolute top-4 right-4 text-white/80 hover:text-white text-xl"
              >
                ✕
              </button>

              <h2 className="text-lg font-semibold">Approver History</h2>

              <div className="flex items-center gap-2 mt-3">
                <span className="bg-yellow-100 text-yellow-800 text-xs font-medium px-3 py-1 rounded-full">
                  Menunggu
                </span>
                <span className="bg-white text-[#0F6C75] text-xs font-medium px-3 py-1 rounded-full">
                  Banner
                </span>
                <span className="bg-white/20 text-white text-xs px-2 py-[2px] rounded-full">
                  1
                </span>
              </div>
            </div>

            {/* BODY */}
            <div className="p-6 grid grid-cols-[1fr_auto_1fr] gap-6 items-start">
              {/* LEFT TIMELINE */}
              <div className="relative space-y-6">
                {/* Upload */}
                <div className="flex flex-col items-center">
                  <span className="bg-[#C7DDE4] text-[#0F6C75] text-xs px-4 py-1 rounded-full">
                    Upload
                  </span>
                  <div className="w-px h-6 bg-gray-300" />
                </div>

                {/* Diterima */}
                <div className="relative bg-[#1F6779] text-white rounded-xl p-4">
                  <h4 className="font-semibold text-sm mb-2">Diterima</h4>
                  <span className="inline-block bg-[#E3EFF4] text-[#0F6C75] text-xs px-3 py-1 rounded-full">
                    Direview oleh: approver-jaecoo1
                  </span>
                </div>

                <div className="w-px h-6 bg-gray-300 mx-auto" />

                {/* Pending */}
                <div className="relative bg-[#B36A00] text-white rounded-xl p-4">
                  <h4 className="font-semibold text-sm mb-2">Pending</h4>
                  <span className="inline-block bg-[#FFF6CC] text-[#7A4A00] text-xs px-3 py-1 rounded-full">
                    Direview oleh: approver-jaecoo1
                  </span>
                </div>
              </div>

              {/* ARROW */}
              <div className="flex flex-col gap-20 text-gray-500 font-bold">
                <span>&gt;</span>
                <span>&gt;</span>
              </div>

              {/* RIGHT NOTES */}
              <div className="space-y-14">
                <div>
                  <div className="bg-[#C7DDE4] text-sm px-4 py-2 rounded-lg">
                    Catatan:
                  </div>
                </div>

                <div>
                  <div className="bg-[#FFF9C4] text-sm px-4 py-2 rounded-lg">
                    Catatan:
                  </div>
                </div>
              </div>
            </div>

            {/* FOOTER */}
            <div className="border-t bg-[#F2F7FA] text-center py-3">
              <button
                onClick={() => setOpenApproverHistory(false)}
                className="text-[#0F6C75] font-medium hover:underline"
              >
                Tutup
              </button>
            </div>
          </div>
        </div>
      )}
      <Dialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle className="text-teal-900 font-semibold">
              Upload File
            </DialogTitle>
          </DialogHeader>

          <div
            className="border-2 border-dashed rounded-xl p-8 text-center cursor-pointer"
            onClick={() => document.getElementById(fileInputId)?.click()}
          >
            <Upload className="w-10 h-10 text-gray-400 mx-auto mb-3" />
            <p className="text-sm text-gray-500">
              Klik untuk upload atau drag & drop
            </p>
            <p className="text-xs text-gray-400">PNG, JPG (max 2 MB)</p>

            <input
              id={fileInputId}
              type="file"
              accept="image/*"
              className="hidden"
              onChange={handleFileSelected}
            />
          </div>

          <DialogFooter className="flex gap-3 pt-4">
            <Button
              variant="secondary"
              className="bg-slate-200"
              onClick={() => setIsUploadDialogOpen(false)}
            >
              Batal
            </Button>

            <Button
              onClick={() => document.getElementById(fileInputId)?.click()}
              className="bg-teal-800 hover:bg-teal-900 text-white"
            >
              Pilih File
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
      {openCommentModal && detailData && (
        <div
          className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4"
          onClick={() => setOpenCommentModal(false)}
        >
          <div
            className="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            {/* HEADER */}
            <div className="bg-gradient-to-br from-[#1F6779] to-[#0F6C75] text-white px-6 py-5 relative">
              <button
                onClick={() => setOpenCommentModal(false)}
                className="absolute top-4 right-4 text-white/80 hover:text-white text-xl"
              >
                ✕
              </button>

              <h2 className="text-lg font-semibold">Beri Tanggapan</h2>

              {/* Badge */}
              <div className="flex items-center gap-2 mt-3">
                <span className="bg-yellow-100 text-yellow-800 text-xs font-medium px-3 py-1 rounded-full">
                  Menunggu
                </span>

                <span className="bg-white text-[#0F6C75] text-xs font-medium px-3 py-1 rounded-full">
                  Banner
                </span>

                <span className="bg-white/20 text-white text-xs px-2 py-[2px] rounded-full">
                  {detailData.position}
                </span>
              </div>
            </div>

            {/* BODY */}
            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-500 mb-2">
                  Comment
                </label>
                <textarea
                  value={commentValue}
                  onChange={(e) => setCommentValue(e.target.value)}
                  placeholder="Masukkan komentar"
                  className="w-full min-h-[100px] border rounded-lg p-3 focus:outline-none focus:ring-2 focus:ring-[#0F6C75]"
                />
              </div>
            </div>

            {/* FOOTER */}
            <div className="flex justify-between gap-3 px-6 py-4 border-t bg-[#F2F7FA]">
              <button
                onClick={() => setOpenCommentModal(false)}
                className="flex-1 py-2 rounded-xl bg-blue-100 hover:bg-blue-200 text-gray-700 font-medium"
              >
                Batal
              </button>

              <button
                onClick={handleSubmitComment}
                className="flex-1 py-2 rounded-xl bg-[#1F6779] hover:bg-[#0F6C75] text-white font-medium"
              >
                Submit
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
