"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 { useRouter } from "@/i18n/routing";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useEffect, useState } from "react";
import {
  AdministrationLevelList,
  checkRolePlacementsAvailability,
  getListCompetencies,
  getListExperiences,
  saveUserInternal,
  saveUserRolePlacements,
} from "@/service/management-user/management-user";
import { error, loading } from "@/config/swal";
import { Eye, EyeOff } from "lucide-react";

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 AddExpertForm() {
  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 [passwordType, setPasswordType] = useState("password");
  const [showPassword, setShowPassword] = useState(false);

  const togglePasswordType = () => {
    setPasswordType((prevType) =>
      prevType === "password" ? "text" : "password"
    );
  };

  const roleSelection = [
    {
      id: "11",
      name: "Koor Kurator",
    },
    {
      id: "12",
      name: "Kurator",
    },
  ];

  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,
      address: "",
      roleId: "EXP-ID",
      phoneNumber: data.phoneNumber,
      userCompetencyId: data.skills,
      userExperienceId: data.experiences,
      companyName: data.company,
      isAdmin: true,
    };

    loading();
    
    // check availability first
    var placementArr: any[] = [];
    placementRows.forEach((row: any) => {
      placementArr.push({
        roleId: Number(row.roleId),
        userLevelId: Number(row.userLevelId),
      });
    });

    const dataReqAvail = {
      placements: placementArr,
    };
    const resAvail = await checkRolePlacementsAvailability(dataReqAvail);
    if (resAvail?.error) {
      close();
      error(resAvail.message);
      return false;
    }

    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);
      }
    });
  }

  useEffect(() => {
    getDataAdditional();
  }, []);

  async function getDataAdditional() {
    const resCompetencies = await getListCompetencies();
    setUserCompetencies(resCompetencies?.data?.data);

    const resExperiences = await getListExperiences();
    setUserExperiences(resExperiences?.data?.data);

    const resUserLevels = await AdministrationLevelList();
    const data = resUserLevels?.data?.data;
    var levelsArr: any[] = [];
    data.forEach((levels: any) => {
      levelsArr.push({
        id: levels.id,
        label: levels.name,
        name: levels.name,
        value: String(levels.id),
        levelNumber: levels.levelNumber,
      });
    });
    setUserLevels(levelsArr);
  }

  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 = () => {
    if (placementRows.length < 2) {
      setPlacementRows((prevRows) => [
        ...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 dark:bg-black rounded-sm p-4"
        >
          <p className="fonnt-semibold">Campaign</p>
          <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="username"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Username</FormLabel>
                <Input
                  type="text"
                  value={field.value}
                  placeholder="Masukkan"
                  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 No.Hp"
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />
          <input
            type="text"
            name="usernamefake"
            autoComplete="username"
            hidden
          />
          <input
            type="password"
            name="passwordfake"
            autoComplete="new-password"
            hidden
          />
          <FormField
            control={form.control}
            name="email"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Email</FormLabel>
                <Input
                  type="email"
                  value={field.value}
                  placeholder="Masukkan email"
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="password"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Password</FormLabel>
                <div className="relative">
                  <Input
                    value={field.value}
                    type={showPassword ? "text" : "password"}
                    placeholder="Masukkan Password"
                    onChange={field.onChange}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-default-500 hover:text-default-700"
                    tabIndex={-1}
                  >
                    {showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="skills"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Bidang Keahlian</FormLabel>
                <Select onValueChange={field.onChange} value={field.value}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih Bidang Keahlian" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {userCompetencies?.map((item: any) => (
                      <SelectItem key={item.id} value={String(item.id)}>
                        {item.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="experiences"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Pengalaman</FormLabel>
                <Select onValueChange={field.onChange} value={field.value}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih Pengalaman" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {userExperiences?.map((item: any) => (
                      <SelectItem key={item.id} value={String(item.id)}>
                        {item.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="company"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Nama Institusi/Perusahaan</FormLabel>
                <Input
                  type="text"
                  value={field.value}
                  placeholder="Nama Institusi/Perusahaan"
                  onChange={field.onChange}
                />
                <FormMessage />
              </FormItem>
            )}
          />

          <div className="mt-4">
            <FormLabel>Posisi</FormLabel>
            {placementRows?.map((row: any) => (
              <div key={row.index} className="flex items-center gap-2 my-2">
                <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>
                {/* <Select
                  onValueChange={(e) =>
                    handleSelectionChange(row.index, "userLevelId", e)
                  }
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih User Level" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    {userLevels?.map((item: any) => (
                      <SelectItem key={item.id} value={String(item.id)}>
                        {item.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select> */}
                <Select
                  onValueChange={(e) =>
                    handleSelectionChange(row.index, "userLevelId", e)
                  }
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih User Level" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="216">MABES POLRI</SelectItem>
                  </SelectContent>
                </Select>
                {placementRows.length > 1 && (
                  <Button
                    type="button"
                    size="md"
                    color="destructive"
                    onClick={() => handleRemoveRow(row.index)}
                  >
                    Hapus
                  </Button>
                )}
              </div>
            ))}
            {/* <Button
              type="button"
              size="md"
              onClick={handleAddRow}
              disabled={placementRows.length >= 2} // optional: disable button if already 1 row added
            >
              Tambah
            </Button> */}
          </div>

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