"use client";
import SiteBreadcrumb from "@/components/site-breadcrumb";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import withReactContent from "sweetalert2-react-content";
import Swal from "sweetalert2";
import { Link, useRouter } from "@/i18n/routing";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useEffect, useState } from "react";
import {
  AdministrationLevelList,
  getListCompetencies,
  getListExperiences,
  saveUserInternal,
  saveUserRolePlacements,
} from "@/service/management-user/management-user";
import { loading } from "@/config/swal";
import { Label } from "@/components/ui/label";

const FormSchema = z.object({
  name: z.string({
    required_error: "Required",
  }),
  username: z.string({
    required_error: "Required",
  }),
  password: z.string({
    required_error: "Required",
  }),
  phoneNumber: z.string({
    required_error: "Required",
  }),
  email: z.string({
    required_error: "Required",
  }),
  skills: z.string({
    required_error: "Required",
  }),
  experiences: z.string({
    required_error: "Required",
  }),
  company: z.string({
    required_error: "Required",
  }),
});

export type Placements = {
  index: number;
  roleId?: string;
  userLevelId?: number;
};

export default function AddContactForm() {
  const MySwal = withReactContent(Swal);
  const router = useRouter();
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
  });
  const [incrementId, setIncrementId] = useState(1);
  const [placementRows, setPlacementRows] = useState<Placements[]>([
    { index: 0, roleId: "", userLevelId: 0 },
  ]);
  const [userCompetencies, setUserCompetencies] = useState<any>();
  const [userExperiences, setUserExperiences] = useState<any>();
  const [userLevels, setUserLevels] = useState<any>();

  const roleSelection = [
    {
      id: "11",
      name: "Polda",
    },
    {
      id: "12",
      name: "Satker Humas",
    },
    {
      id: "13",
      name: "Satker Mabes",
    },
  ];

  const onSubmit = async (data: z.infer<typeof FormSchema>) => {
    MySwal.fire({
      title: "Simpan Data",
      text: "Apakah Anda yakin ingin menyimpan data ini?",
      icon: "warning",
      showCancelButton: true,
      cancelButtonColor: "#d33",
      confirmButtonColor: "#3085d6",
      confirmButtonText: "Simpan",
    }).then((result) => {
      if (result.isConfirmed) {
        save(data);
      }
    });
  };

  const save = async (data: z.infer<typeof FormSchema>) => {
    console.log("data", data);

    const dataReq = {
      firstName: data.name,
      username: data.username,
      email: data.email,
      password: data.password,
      adress: "",
      roleId: "EXP-ID",
      phoneNumber: data.phoneNumber,
      userCompetencyId: data.skills,
      userExperienceId: data.experiences,
      companyName: data.company,
    };

    loading();
    const res = await saveUserInternal(dataReq);
    const resData = res?.data?.data;
    const userProfileId = resData?.id;

    var placementArr: any[] = [];
    placementRows.forEach((row: any) => {
      placementArr.push({
        roleId: Number(row.roleId),
        userLevelId: Number(row.userLevelId),
        userProfileId: userProfileId,
      });
    });

    const dataReq2 = {
      userId: userProfileId,
      placements: placementArr,
    };
    const res2 = await saveUserRolePlacements(dataReq2);
    const resData2 = res2?.data?.data;

    success("/admin/add-experts");
  };

  function success(redirect: string): void {
    MySwal.fire({
      title: '<p class="text-green-600 font-bold">Sukses</p>',
      icon: "success",
      confirmButtonColor: "#3085d6",
      confirmButtonText: '<span class="text-white">OK</span>',
      allowOutsideClick: false,
    }).then((result) => {
      if (result.isConfirmed) {
        router.push(redirect);
      }
    });
  }

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

  const handleSelectionChange = (
    index: number,
    type: "roleId" | "userLevelId",
    value: string
  ) => {
    setPlacementRows((prevRows) =>
      prevRows.map((row) =>
        row.index === index ? { ...row, [type]: value } : row
      )
    );
  };

  const handleRemoveRow = (index: number) => {
    console.log(index);
    console.log(placementRows);
    const newPlacements = placementRows.filter((row) => row.index != index);
    console.log(newPlacements);
    setPlacementRows(newPlacements);
  };

  const handleAddRow = () => {
    setPlacementRows((prevRows: any) => [
      ...prevRows,
      { index: incrementId, roleId: "", userLevelId: 0 },
    ]);
    setIncrementId((prevId) => prevId + 1);
  };

  return (
    <div>
      <SiteBreadcrumb />

      <Form {...form}>
        <form
          onSubmit={form.handleSubmit(onSubmit)}
          className="space-y-3 bg-white rounded-sm p-4"
        >
          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Email</FormLabel>
                <Input
                  type="email"
                  value={field.value}
                  placeholder="Masukkan Nama Lengkap"
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Nama Lengkap</FormLabel>
                <Input
                  value={field.value}
                  placeholder="Masukkan Nama Lengkap"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="phoneNumber"
            render={({ field }) => (
              <FormItem>
                <FormLabel>No. HP</FormLabel>
                <Input
                  type="number"
                  value={field.value}
                  placeholder="Masukkan Nama Lengkap"
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />
          <div className="mt-2 mb-0 pb-0">
            <FormLabel>
              Kategori Akun <span className="text-red-500">*</span>
            </FormLabel>
            <Select
            // onValueChange={(e) =>
            //   handleSelectionChange(row.index, "roleId", e)
            // }
            >
              <FormControl>
                <SelectTrigger>
                  <SelectValue placeholder="Pilih Role" />
                </SelectTrigger>
              </FormControl>
              <SelectContent>
                {roleSelection?.map((item: any) => (
                  <SelectItem key={item.id} value={String(item.id)}>
                    {item.name}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Username Admin</FormLabel>
                <Input
                  value={field.value}
                  placeholder="Masukkan Nama Lengkap"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Username Approver</FormLabel>
                <Input
                  value={field.value}
                  placeholder="Masukkan Nama Lengkap"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Username Kontributor</FormLabel>
                <Input
                  value={field.value}
                  placeholder="Masukkan Nama Lengkap"
                  onChange={field.onChange}
                />

                <FormMessage />
              </FormItem>
            )}
          />

          <div className="flex flex-row justify-end gap-2 mt-4 pt-4">
            <Link href="/supervisor/communications/contact">
              <Button
                size="md"
                type="button"
                variant="outline"
                color="destructive"
                className="text-xs"
              >
                Cancel
              </Button>
            </Link>
            <Button size="md" type="submit" color="primary" className="text-xs">
              Submit
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
}
