import { Button } from "@nextui-org/button";
import { Input, Textarea } from "@nextui-org/input";
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import { otpRequest, otpValidation } from "@/service/master-user";
import { error } from "@/config/swal";
import { UserProfileIcon } from "@/components/icons/globals";
import { convertDateFormat } from "@/utils/global";
import Cookies from "js-cookie";

const userId = Cookies.get("uie");

const commentSchema = z.object({
  name: z.string().min(1, {
    message: "Judul harus diisi",
  }),
  email: z
    .string()
    .email({
      message: "Email tidak valid",
    })
    .min(1, {
      message: "Harus diisi",
    }),
  comment: z.string().min(1, {
    message: "Deskripsi harus diisi",
  }),
});

const dummyData = [
  {
    id: 1,
    createdByName: "User 2",
    comment: "test comment",
    createdAt: "2025-01-30T00:09:39.352384Z",
    createdById: 32,
  },
  {
    id: 2,
    createdByName: "User 2",
    comment: "test comment 22",
    createdAt: "2025-01-31T00:10:50.352384Z",
    createdById: 23,
  },
];

export default function Comment() {
  const [needOtp, setNeedOtp] = useState(false);
  const [otpValue, setOtpValue] = useState("");
  const formOptions = {
    resolver: zodResolver(commentSchema),
  };
  type UserSettingSchema = z.infer<typeof commentSchema>;
  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
  } = useForm<UserSettingSchema>(formOptions);

  const onSubmit = async (values: z.infer<typeof commentSchema>) => {
    if (!needOtp) {
      const res = await otpRequest(values.email);
      if (res?.error) {
        error(res.message);
        return false;
      }
      setNeedOtp(true);
    } else {
      const validation = await otpValidation(values.email, otpValue);
      if (validation?.error) {
        error("OTP Tidak Sesuai");
        return false;
      }
      const req = {
        email: values.email,
        name: values.name,
        comment: values.comment,
      };
      console.log("req", req);
    }
  };
  return (
    <div className="py-5 px-8 flex flex-col gap-3">
      <div className="flex flex-col gap-2 text-black">
        {dummyData.map((list) => (
          <div
            key={list?.id}
            className="flex justify-between items-center border-b-2 py-3 shadow-md px-4 rounded-md"
          >
            <div className="flex flex-row gap-2 ">
              <UserProfileIcon size={44} />
              <div className="flex flex-col gap-1">
                <p className="text-sm font-semibold">{list.createdByName}</p>
                <p className="text-sm">{list.comment}</p>
              </div>
            </div>
            <div className="flex flex-col gap-1 text-right">
              <p className="text-xs">{convertDateFormat(list.createdAt)}</p>
              {(userId === String(list.createdById) || userId === "16") && (
                <a className="text-danger cursor-pointer text-xs">Hapus</a>
              )}
            </div>
          </div>
        ))}
      </div>
      <form
        className="py-3 px-4 flex flex-col gap-3 bg-gray-50 text-black dark:bg-stone-900 dark:text-white rounded-lg shadow-md"
        onSubmit={handleSubmit(onSubmit)}
      >
        <b>Tinggalkan balasan</b>
        <p className="text-xs">
          Alamat email Anda tidak akan dipublikasikan. Ruas yang wajib ditandai{" "}
          <span className="text-red-600">*</span>
        </p>
        <div className="flex flex-col gap-1">
          <p className="text-sm">Komentar</p>
          <Controller
            control={control}
            name="comment"
            render={({ field: { onChange, value } }) => (
              <Textarea
                type="text"
                id="comment"
                placeholder=""
                label=""
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full "
                classNames={{
                  inputWrapper: [
                    "border-1 rounded-lg",
                    "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                  ],
                }}
                variant="bordered"
              />
            )}
          />
          {errors?.comment && (
            <p className="text-red-400 text-sm mb-3">
              {errors.comment?.message}
            </p>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <p className="text-sm">
            Nama <span className="text-red-600">*</span>
          </p>

          <Controller
            control={control}
            name="name"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="name"
                placeholder=""
                label=""
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full "
                classNames={{
                  inputWrapper: [
                    "border-1 rounded-lg",
                    "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                  ],
                }}
                variant="bordered"
              />
            )}
          />
          {errors?.name && (
            <p className="text-red-400 text-sm mb-3">{errors.name?.message}</p>
          )}
        </div>
        <div className="flex flex-col gap-1">
          <p className="text-sm">
            Email <span className="text-red-600">*</span>
          </p>
          <Controller
            control={control}
            name="email"
            render={({ field: { onChange, value } }) => (
              <Input
                type="email"
                id="email"
                placeholder=""
                label=""
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full "
                classNames={{
                  inputWrapper: [
                    "border-1 rounded-lg",
                    "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                  ],
                }}
                variant="bordered"
              />
            )}
          />
          {errors?.email && (
            <p className="text-red-400 text-sm mb-3">{errors.email?.message}</p>
          )}
        </div>
        {needOtp && (
          <div className="flex flex-col gap-1">
            <p>OTP</p>
            <Input
              type="number"
              id="otp"
              placeholder=""
              label=""
              value={otpValue}
              onValueChange={setOtpValue}
              labelPlacement="outside"
              className="w-[100px] "
              classNames={{
                inputWrapper: [
                  "border-1 rounded-lg",
                  "dark:group-data-[focused=false]:bg-transparent !border-1 dark:!border-gray-400",
                ],
              }}
              variant="bordered"
            />
          </div>
        )}

        <Button className="bg-[#DD8306] text-white" radius="md" type="submit">
          Kirim
        </Button>
      </form>
    </div>
  );
}
