// import { MdOutlineRemoveRedEye } from "react-icons/md";
import { Box, Field, HStack, Input, Stack } from "@chakra-ui/react";
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
  DialogTitle,
  DialogTrigger,
} from "../../../components/ui/dialog";
// import { BiEdit } from "react-icons/bi";
import { Button } from "../../../components/ui/button";
// import { TbEdit } from "react-icons/tb";
import Edit from "../../../components/ActionIcons/Edit";
import { UserData, useUpdateUserMutation } from "../../../Redux/Service/manage.user";
import { useState } from "react";
import { Toaster, toaster } from "../../../components/ui/toaster";

interface UserPayload {
  id: number;
  principal_type_xid: number;
  principal_source_xid: number;
  first_name: string;
  last_name: string;
  gender: string;
  date_of_birth: string | null;
  language_xid: number; // ✅ Always an array
}

export interface UserFormData {
  id: number;
  principal_type_xid: number;
  first_name: string;
  last_name: string;
  phone_number: string;
  gender: string;
  date_of_birth: string;
  is_active: boolean;
  principal_type: {
    id: number;
    principal_type_title: string;
  };
  principle_language_linkss: {
    id?: number;
    iam_principal_xid?: number;
    language_xid: number;
  };
}

function EditRegisterUsers({ data, refetch }: { data: UserData, refetch: () => void }) {
  const [isOpen, setIsOpen] = useState(false);
  const transformToFormData = (data: UserData): UserFormData => ({
    ...data,
    principle_language_linkss: {
      ...data.principle_language_linkss,
      language_xid: data.principle_language_linkss.language_xid, // wrap in array
    },
  });
  const [formData, setFormData] = useState<UserFormData>(transformToFormData(data));
  // const [formData, setFormData] = useState<UserData>({
  //   id: data?.id,
  //   first_name: data?.first_name || '',
  //   last_name: data?.last_name || '',
  //   principal_type_xid: data?.principal_type_xid,
  //   phone_number: data?.phone_number || '',
  //   gender: data?.gender || '',
  //   date_of_birth: data?.date_of_birth || '',
  //   principal_type: data?.principal_type,
  //   is_active: data?.is_active ?? true,
  //   principle_language_linkss: {
  //     ...data?.principle_language_linkss,
  //     language_xid: Array.isArray(data?.principle_language_linkss?.language_xid)
  //       ? data.principle_language_linkss.language_xid
  //       : [data?.principle_language_linkss?.language_xid].filter(Boolean),
  //   },
  //   // principle_language_linkss: data?.principle_language_linkss ?? [],
  // });
  const [updateUser, { isLoading }] = useUpdateUserMutation();

  const handleOpenModal = () => {
    setIsOpen(true);
  };

  const handleSubmit = async (event: React.FormEvent) => {
    event.preventDefault();
    if (formData.first_name === '' || formData.last_name === '' || formData.phone_number === '' || formData.gender === '' || formData.date_of_birth === '') {
      toaster.create({
        title: "Error",
        description: "Input fields cannot be empty",
        type: "error",
      });
      return;
    }

    // const languageData = formData?.principle_language_linkss?.language_xid;

    const payload: UserPayload = {
      id: formData?.id,
      principal_type_xid: formData?.principal_type_xid,
      principal_source_xid: formData?.id,
      first_name: formData?.first_name,
      last_name: formData?.last_name,
      gender: formData?.gender,
      date_of_birth: formData?.date_of_birth,
      // language_xid: languageData,
      language_xid: formData.principle_language_linkss?.language_xid
        ? formData.principle_language_linkss.language_xid
        : formData.principle_language_linkss?.language_xid,

    };

    // console.log('payload', payload)

    try {
      const response = await updateUser(payload).unwrap();
      if (response?.status === "success") {
        toaster.create({
          title: "Success",
          description: "Country updated successfully",
          type: "success",
        });
        setIsOpen(false);
        refetch()
      } else {
        toaster.create({
          title: "Error",
          description: "Failed to update Country",
          type: "error",
        });
      }
    } catch (error: any) {
      console.error("Error updating template:", error);
      // alert("Failed to update template");
      toaster.create({
        title: "Error",
        description: error ? `${error?.data.message}` : "Something went wrong",
        type: "error",
      });
    }
  };

  return (
    <>
      <DialogRoot placement="center" key={formData.id} open={isOpen} onOpenChange={({ open }) => setIsOpen(open)}>
        <DialogTrigger asChild>
          {/* <Span>
          <Edit />
        </Span> */}
          <Button bg="transparent" color={"black"} h={"18px"} onClick={handleOpenModal}><Edit /></Button>
        </DialogTrigger>

        <DialogContent
          bg={"#fff"}
          w={{ base: "90%", md: "400px" }}
          height={"80vh"}
          overflow={"scroll"}
          overflowX="hidden"
          p={3} // Reduced padding
          bgSize={"md"}
        >
          <DialogHeader bg="white" p={0}>
            <DialogTitle alignSelf="center" color="black" fontSize="14px">
              Edit user Accounts
            </DialogTitle>
          </DialogHeader>

          <DialogBody bg="white">
            <Stack py={3}>
              <Field.Root>
                <Field.Label color="black" pt={1} fontSize="12px">
                  First Name
                </Field.Label>
                <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData.first_name}
                  onChange={(e) => setFormData({ ...formData, first_name: e.target.value })}
                />

                <Field.Label color="black" pt={1} fontSize="12px">
                  Last Name
                </Field.Label>
                <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData.last_name}
                  onChange={(e) => setFormData({ ...formData, last_name: e.target.value })}
                />

                <Field.Label color="black" pt={1} fontSize="12px">
                  Gender
                </Field.Label>
                <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData.gender}
                  onChange={(e) => setFormData({ ...formData, gender: e.target.value })}
                />

                <Field.Label color="black" pt={1} fontSize="12px">
                  DOB
                </Field.Label>
                <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData.date_of_birth ? new Date(formData.date_of_birth).toLocaleDateString('en-GB').replace(/\//g, '-') : 'N/A'}
                  onChange={(e) => setFormData({ ...formData, date_of_birth: e.target.value })}
                  disabled={formData.principal_type_xid === 2 ? true : false}
                />

                <Field.Label color="black" pt={1} fontSize="12px">
                  Mobile Number
                </Field.Label>
                <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData.phone_number || ''}
                  onChange={(e) => setFormData({ ...formData, phone_number: e.target.value })}
                />

                <Field.Label color="black" pt={1} fontSize="12px">
                  Type Of User
                </Field.Label>
                {/* <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData.principal_type?.principal_type_title || 'N/A'}
                  onChange={(e) => setFormData({ ...formData, principal_type: { ...formData.principal_type, principal_type_title: e.target.value } })}
                /> */}

                <Box>
                  <select
                    style={{
                      width: "100%",
                      background: "transparent",
                      color: "black",
                      border: "none",
                      fontSize: "12px",
                      height: "30px",
                      outline: "none",
                    }}
                    value={formData.principal_type_xid?.toString() || 'N/A'}
                    onChange={(e) => setFormData({ ...formData, principal_type_xid: Number(e.target.value) })}
                  >
                    {/* <option value="">Select User Type</option> */}
                    <option value="2">Recruiter</option>
                    <option value="3">Jobseeker</option>
                  </select>
                </Box>

                <Field.Label color="black" pt={1} fontSize="12px">
                  Default Language
                </Field.Label>
                {/* <Input
                  bgColor="#EEEEEE"
                  color="black"
                  border="none"
                  pl={1}
                  fontSize="12px"
                  height="30px"
                  value={formData?.principle_language_linkss?.language_xid || 'N/A'}
                  onChange={(e) => setFormData({
                    ...formData, principle_language_linkss: {
                      ...formData?.principle_language_linkss, language_xid: e.target.value
                        .split(",")
                        .map(lang => lang.trim())
                        .filter(Boolean)
                    }
                  })}
                /> */}

                <HStack>
                  <select
                    style={{
                      width: "100%",
                      background: "transparent",
                      color: "black",
                      border: "none",
                      fontSize: "12px",
                      height: "30px",
                      outline: "none",
                    }}
                    value={formData?.principle_language_linkss?.language_xid || ""}
                    onChange={(e) => {
                      const value = Number(e.target.value);
                      setFormData({
                        ...formData,
                        principle_language_linkss: {
                          ...formData?.principle_language_linkss,
                          language_xid: value,
                        },
                      });
                    }}
                  >
                    <option value="1">English</option>
                    <option value="2">Hindi</option>
                    <option value="3">Marathi</option>
                    <option value="4">Telgu</option>
                    <option value="5">Tamil</option>
                    <option value="6">Bengali</option>
                    <option value="7">Odia</option>
                  </select>
                </HStack>
              </Field.Root>
            </Stack>
          </DialogBody>
          <DialogFooter mt={5}>
            <Button rounded={"md"} w={"100%"} size={"sm"} bg={"#02A0A0"} onClick={handleSubmit} disabled={isLoading}>
              Save
            </Button>
          </DialogFooter>
          <DialogCloseTrigger color="black" />
        </DialogContent>
      </DialogRoot >
      <Toaster />
    </>
  );
}

export default EditRegisterUsers;
