"use client";
import { FormEvent, Fragment, useEffect, useRef, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import * as z from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { Input, Textarea } from "@heroui/input";
import { Button } from "@heroui/button";
import { Radio, RadioGroup } from "@heroui/react";
import { updateProfile } from "@/services/master-user";
import { close, error, loading } from "@/config/swal";

const formSchema = z.object({
  fullname: z.string().min(1, {
    message: "Harus diisi",
  }),
  username: z.string().min(1, {
    message: "Harus diisi",
  }),
  email: z
    .string()
    .email({
      message: "Email tidak valid",
    })
    .min(2, {
      message: "Harus diisi",
    }),
  nrp: z.string().optional(),
  address: z.string().optional(),
  gender: z.string().optional(),
  phoneNumber: z.string().optional(),
});

export default function ProfileForm(props: {
  profile: any;
  doFetch: () => void;
}) {
  const MySwal = withReactContent(Swal);
  const { profile } = props;
  const formOptions = {
    resolver: zodResolver(formSchema),
  };
  type UserSettingSchema = z.infer<typeof formSchema>;
  const {
    control,
    handleSubmit,
    formState: { errors },
    setValue,
  } = useForm<UserSettingSchema>(formOptions);

  useEffect(() => {
    setValue("fullname", profile?.fullname);
    setValue("username", profile?.username);
    setValue("email", profile?.email);
    setValue("address", profile?.address);
    setValue("nrp", profile?.identityNumber);
    setValue("gender", profile?.genderType);
    setValue("phoneNumber", profile?.phoneNumber);
  }, [profile]);

  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    loading();
    const req = {
      address: values.address,
      fullname: values.fullname,
      username: values.username,
      email: values.email,
      identityNumber: values.nrp,
      phoneNumber: values.phoneNumber,
      genderType: values.gender,
      userLevelId: profile.userLevelId,
      userRoleId: profile.userRoleId,
    };
    const res = await updateProfile(req);
    close();
    if (res?.error) {
      error(res.message);
      return false;
    }
    props.doFetch();
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
      }
    });
  };

  return (
    <form className="flex flex-col gap-3 " onSubmit={handleSubmit(onSubmit)}>
      <div className="flex flex-col gap-1">
        <p className="text-sm">Username</p>
        <Controller
          control={control}
          name="username"
          render={({ field: { onChange, value } }) => (
            <Input
              type="text"
              id="username"
              placeholder=""
              label=""
              isReadOnly
              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?.username && (
          <p className="text-red-400 text-sm mb-3">
            {errors.username?.message}
          </p>
        )}
      </div>
      <div className="flex flex-col gap-1">
        <p className="text-sm">Nama Lengkap</p>
        <Controller
          control={control}
          name="fullname"
          render={({ field: { onChange, value } }) => (
            <Input
              type="text"
              id="fullname"
              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?.fullname && (
          <p className="text-red-400 text-sm mb-3">
            {errors.fullname?.message}
          </p>
        )}
      </div>

      <div className="flex flex-col gap-1">
        <p className="text-sm">Email</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>

      <div className="flex flex-col gap-1">
        <p className="text-sm">NRP</p>
        <Controller
          control={control}
          name="nrp"
          render={({ field: { onChange, value } }) => (
            <Input
              type="number"
              id="nrp"
              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?.nrp && (
          <p className="text-red-400 text-sm mb-3">{errors.nrp?.message}</p>
        )}
      </div>

      <div className="flex flex-col gap-1">
        <p className="text-sm">Alamat</p>
        <Controller
          control={control}
          name="address"
          render={({ field: { onChange, value } }) => (
            <Textarea
              type="text"
              id="address"
              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?.address && (
          <p className="text-red-400 text-sm mb-3">{errors.address?.message}</p>
        )}
      </div>
      <div className="flex flex-col gap-1">
        <p className="text-sm">Gender</p>
        <Controller
          control={control}
          name="gender"
          render={({ field: { onChange, value } }) => (
            <RadioGroup
              label=""
              value={value}
              onValueChange={onChange}
              orientation="horizontal"
            >
              <Radio value="male">Laki-laki</Radio>
              <Radio value="female">Perempuan</Radio>
            </RadioGroup>
          )}
        />
        {errors?.gender && (
          <p className="text-red-400 text-sm mb-3">{errors.gender?.message}</p>
        )}
      </div>
      <div className="flex flex-col gap-1">
        <p className="text-sm">No Handphone</p>
        <Controller
          control={control}
          name="phoneNumber"
          render={({ field: { onChange, value } }) => (
            <Input
              type="number"
              id="phoneNumber"
              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?.phoneNumber && (
          <p className="text-red-400 text-sm mb-3">
            {errors.phoneNumber?.message}
          </p>
        )}
      </div>
      <Button color="primary" type="submit" className="w-fit mt-4">
        Simpan
      </Button>
    </form>
  );
}
