"use client";
import { error } from "@/config/swal";
import { createMasterUser } from "@/service/master-user";
import { MasterUser } from "@/types/globals";
import { zodResolver } from "@hookform/resolvers/zod";
import {
  Button,
  Card,
  Input,
  Radio,
  RadioGroup,
  Select,
  SelectItem,
  Selection,
  Textarea,
} from "@nextui-org/react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import React, { useState } from "react";
import { Controller, useForm } from "react-hook-form";
import Datepicker from "react-tailwindcss-datepicker";
import Swal from "sweetalert2";
import withReactContent from "sweetalert2-react-content";
import { z } from "zod";
import { EyeFilledIcon, EyeSlashFilledIcon } from "../icons";

const masterUserSchema = z.object({
  fullname: z.string().min(1, { message: "Required" }),
  username: z.string().min(1, { message: "Required" }),
  password: z
    .string()
    .min(8, "Password harus memiliki minimal 8 karakter.")
    .refine((password) => /[A-Z]/.test(password), {
      message: "Password harus memiliki minimal satu huruf kapital.",
    })
    .refine((password) => /[0-9]/.test(password), {
      message: "Password harus memiliki minimal satu angka.",
    })
    .refine((password) => /[!@#$%^&*(),.?":{}|<>]/.test(password), {
      message: "Password harus memiliki minimal satu simbol.",
    }),
  passwordValidate: z.string().min(1, { message: "Required" }),

  email: z.string().min(1, { message: "Required" }),
  identityType: z.string().min(1, { message: "Required" }),
  identityNumber: z.string().min(1, { message: "Required" }),
  lastEducation: z.string().min(1, { message: "Required" }),
  genderType: z.string().min(1, { message: "Required" }),
  phoneNumber: z.string().min(1, { message: "Required" }),
  workType: z.string().min(1, { message: "Required" }),
  address: z.string().min(1, { message: "Required" }),
  birthDate: z.object({
    startDate: z.string().min(1, { message: "Required" }),
    endDate: z.string().min(1, { message: "Required" }),
  }),
});

const typeIdentity = [
  {
    id: 1,
    value: "KTP",
  },
  {
    id: 2,
    value: "SIM",
  },
  {
    id: 3,
    value: "Passport",
  },
];

const workingBackground = [
  {
    id: 1,
    value: "Pegawai Negri Sipil",
  },
  {
    id: 2,
    value: "Wiraswasta",
  },
  {
    id: 3,
    value: "Guru",
  },
  {
    id: 4,
    value: "Dokter",
  },
];

const educationGrade = [
  {
    id: 1,
    value: "SMA / Sederajat",
  },
  {
    id: 2,
    value: "Diploma 1",
  },
  {
    id: 3,
    value: "Diploma 2",
  },
  {
    id: 4,
    value: "Diploma 3",
  },
  {
    id: 5,
    value: "Diploma 4",
  },
  {
    id: 6,
    value: "S1",
  },
  {
    id: 7,
    value: "S2",
  },
  {
    id: 8,
    value: "S3",
  },
];

export default function FormMasterUser() {
  const router = useRouter();
  const MySwal = withReactContent(Swal);
  const [isVisible, setIsVisible] = useState([false, false]);
  const toggleVisibility = (type: number) => {
    setIsVisible(
      type === 0 ? [!isVisible[0], isVisible[1]] : [isVisible[0], !isVisible[1]]
    );
  };

  const formOptions = {
    resolver: zodResolver(masterUserSchema),
    defaultValues: {
      identityType: "KTP",
      birthDate: { stardDate: "", endDate: "" },
    },
  };
  type MicroIssueSchema = z.infer<typeof masterUserSchema>;
  const {
    control,
    handleSubmit,
    formState: { errors },
    setError,
  } = useForm<MicroIssueSchema>(formOptions);

  async function save(data: z.infer<typeof masterUserSchema>) {
    const formData = {
      address: data.address,
      dateOfBirt: data.birthDate,
      password: data.password,
      email: data.email,
      fullname: data.fullname,
      genderType: data.genderType,
      identityNumber: data.identityNumber,
      identityType: data.identityType,
      lastEducation: data.lastEducation,
      phoneNumber: data.phoneNumber,
      userLevelId: 2,
      userRoleId: 2,
      username: data.username,
      workType: data.workType,
    };

    const response = await createMasterUser(formData);

    if (response?.error) {
      error(response.message);
      return false;
    }

    successSubmit("/admin/article");
  }

  function successSubmit(redirect: any) {
    MySwal.fire({
      title: "Sukses",
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "OK",
    }).then((result) => {
      if (result.isConfirmed) {
        router.push(redirect);
      }
    });
  }

  async function onSubmit(data: z.infer<typeof masterUserSchema>) {
    if (data.password === data.passwordValidate) {
      MySwal.fire({
        title: "Simpan Data",
        text: "",
        icon: "warning",
        showCancelButton: true,
        cancelButtonColor: "#d33",
        confirmButtonColor: "#3085d6",
        confirmButtonText: "Simpan",
      }).then((result) => {
        if (result.isConfirmed) {
          save(data);
        }
      });
    } else {
      setError("passwordValidate", {
        type: "manual",
        message: "Password harus sama.",
      });
    }
  }

  return (
    <div className="mx-5 my-5 overflow-y-auto">
      <form method="POST" onSubmit={handleSubmit(onSubmit)}>
        <Card className="rounded-md p-5 flex flex-col gap-3">
          <Controller
            control={control}
            name="fullname"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="title"
                placeholder="Fullname..."
                label="Fullname"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.fullname?.message && (
            <p className="text-red-400 text-sm">{errors.fullname?.message}</p>
          )}
          <Controller
            control={control}
            name="username"
            render={({ field: { onChange, value } }) => (
              <Input
                type="text"
                id="username"
                placeholder="Username..."
                label="Username"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.username?.message && (
            <p className="text-red-400 text-sm">{errors.username?.message}</p>
          )}
          <Controller
            control={control}
            name="password"
            render={({ field: { onChange, value } }) => (
              <Input
                type={isVisible[0] ? "text" : "password"}
                id="password"
                placeholder="Password..."
                label="Password"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
                endContent={
                  <button
                    className="focus:outline-none"
                    type="button"
                    onClick={() => toggleVisibility(0)}
                  >
                    {isVisible[0] ? (
                      <EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none" />
                    ) : (
                      <EyeFilledIcon className="text-2xl text-default-400 pointer-events-none" />
                    )}
                  </button>
                }
              />
            )}
          />
          {errors.password?.message && (
            <p className="text-red-400 text-sm">{errors.password?.message}</p>
          )}
          <Controller
            control={control}
            name="passwordValidate"
            render={({ field: { onChange, value } }) => (
              <Input
                type={isVisible[1] ? "text" : "password"}
                id="passwordValidate"
                placeholder="Confirm Password..."
                label="Confirm Password"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
                endContent={
                  <button
                    className="focus:outline-none"
                    type="button"
                    onClick={() => toggleVisibility(1)}
                  >
                    {isVisible[1] ? (
                      <EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none" />
                    ) : (
                      <EyeFilledIcon className="text-2xl text-default-400 pointer-events-none" />
                    )}
                  </button>
                }
              />
            )}
          />
          {errors.passwordValidate?.message && (
            <p className="text-red-400 text-sm">
              {errors.passwordValidate?.message}
            </p>
          )}

          <Controller
            control={control}
            name="email"
            render={({ field: { onChange, value } }) => (
              <Input
                type="email"
                id="email"
                placeholder="Email..."
                label="Email"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.email?.message && (
            <p className="text-red-400 text-sm">{errors.email?.message}</p>
          )}

          <Controller
            control={control}
            name="identityType"
            render={({ field: { onChange, value } }) => (
              <Select
                variant="bordered"
                labelPlacement="outside"
                label="Identity Type"
                placeholder="Select"
                className="max-w-xs"
                selectedKeys={[value]}
                onChange={onChange}
              >
                {typeIdentity.map((type) => (
                  <SelectItem key={type.value}>{type.value}</SelectItem>
                ))}
              </Select>
            )}
          />
          {errors.identityType?.message && (
            <p className="text-red-400 text-sm">
              {errors.identityType?.message}
            </p>
          )}
          <Controller
            control={control}
            name="identityNumber"
            render={({ field: { onChange, value } }) => (
              <Input
                type="number"
                id="identityNumber"
                placeholder="Identity Number..."
                label="Identity Number"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.identityNumber?.message && (
            <p className="text-red-400 text-sm">
              {errors.identityNumber?.message}
            </p>
          )}

          <Controller
            control={control}
            name="genderType"
            render={({ field: { onChange, value } }) => (
              <RadioGroup
                orientation="horizontal"
                label="Gender"
                value={value}
                onValueChange={onChange}
              >
                <Radio value="Male">Laki-laki</Radio>
                <Radio value="Female">Perempuan</Radio>
              </RadioGroup>
            )}
          />
          {errors.genderType?.message && (
            <p className="text-red-400 text-sm">{errors.genderType?.message}</p>
          )}
          <Controller
            control={control}
            name="birthDate"
            render={({ field: { onChange, value } }) => (
              <Datepicker
                useRange={false}
                asSingle={true}
                value={value}
                displayFormat="DD/MM/YYYY"
                onChange={onChange}
                popoverDirection="down"
                inputClassName="w-full bg-transparent border-1 border-gray-200 px-2 py-[6px] rounded-xl "
              />
            )}
          />
          {errors.birthDate?.startDate?.message && (
            <p className="text-red-400 text-sm">
              {errors.birthDate?.startDate?.message}
            </p>
          )}
          <Controller
            control={control}
            name="lastEducation"
            render={({ field: { onChange, value } }) => (
              <Select
                variant="bordered"
                labelPlacement="outside"
                label="Last Education"
                selectedKeys={[value]}
                onChange={onChange}
                placeholder="Select"
                className="max-w-xs"
              >
                {educationGrade.map((grade) => (
                  <SelectItem key={grade.value}>{grade.value}</SelectItem>
                ))}
              </Select>
            )}
          />
          {errors.lastEducation?.message && (
            <p className="text-red-400 text-sm">
              {errors.lastEducation?.message}
            </p>
          )}
          <Controller
            control={control}
            name="phoneNumber"
            render={({ field: { onChange, value } }) => (
              <Input
                type="number"
                id="identityNumber"
                placeholder="08*********"
                label="No. Handphone"
                value={value}
                onChange={onChange}
                labelPlacement="outside"
                className="w-full"
                variant="bordered"
              />
            )}
          />
          {errors.phoneNumber?.message && (
            <p className="text-red-400 text-sm">
              {errors.phoneNumber?.message}
            </p>
          )}
          <Controller
            control={control}
            name="workType"
            render={({ field: { onChange, value } }) => (
              <Select
                variant="bordered"
                labelPlacement="outside"
                label="Working Type"
                placeholder="Select"
                className="max-w-xs"
                selectedKeys={[value]}
                onChange={onChange}
              >
                {workingBackground.map((type) => (
                  <SelectItem key={type.id} value={type.id}>
                    {type.value}
                  </SelectItem>
                ))}
              </Select>
            )}
          />
          {errors.workType?.message && (
            <p className="text-red-400 text-sm">{errors.workType?.message}</p>
          )}
          <Controller
            control={control}
            name="address"
            render={({ field: { onChange, value } }) => (
              <Textarea
                label="Address"
                labelPlacement="outside"
                placeholder="Enter Text"
                value={value}
                onValueChange={onChange}
              />
            )}
          />
          {errors.address?.message && (
            <p className="text-red-400 text-sm">{errors.address?.message}</p>
          )}
          <div className="flex justify-end gap-3">
            <Link href={`/admin/master-user`}>
              <Button color="danger" variant="ghost">
                Cancel
              </Button>
            </Link>
            <Button type="submit" color="primary" variant="solid">
              Save
            </Button>
          </div>
        </Card>
      </form>
    </div>
  );
}
