import {
  Field,
  Input,
  Span,
  Stack,
} from "@chakra-ui/react";
import { Button } from "../../components/ui/button";
import {
  DialogBody,
  DialogCloseTrigger,
  DialogContent,
  DialogFooter,
  DialogHeader,
  DialogRoot,
  DialogTitle,
  DialogTrigger,
} from "../../components/ui/dialog";

// import { TbEdit } from "react-icons/tb";
import Edit from "../../components/ActionIcons/Edit";
import { JobStatusData, useGetCountryQuery, useGetDepartmentQuery, useGetIndustryQuery, useGetManageJobTypeQuery, useGetWorkspaceModesQuery, useUpdateJobsMutation, WorkSpace } from "../../Redux/Service/manage.jobs.service";
import { useReducer, useRef } from "react";
import { Toaster, toaster } from "../../components/ui/toaster";

const reducerFunction = (state: any, action: any) => {
  switch (action.type) {
    case "SET_JOB_TITLE":
      return { ...state, jobTitle: action.payload };
    case "SET_WORKSPACE_MODE":
      return { ...state, workspaceMode: action.payload };
    case "SET_CATEGORY":
      return { ...state, category: action.payload };
    case "SET_SUB_CATEGORY":
      return { ...state, subCategory: action.payload };
    case "SET_SALARY":
      return { ...state, salary: action.payload };
    case "SET_EXPERIENCE":
      return { ...state, experience: action.payload };
    case "SET_JOB_LOCATION":
      return { ...state, jobLocation: action.payload };
    case "SET_COUNTRY_SELECTION":
      return { ...state, countrySelection: action.payload };
    case "SET_JOB_TYPE":
      return { ...state, jobType: action.payload };
    case "SET_SKILLS_REQUIRED":
      return { ...state, skillsRequired: action.payload };
    case "SET_JOB_DESCRIPTION":
      return { ...state, jobDescription: action.payload };
    default:
      return state;
  }
};

function ManageJobsAdd({ data, refetch }: { data: JobStatusData, refetch: () => void }) {
  const { data: workspaceModes } = useGetWorkspaceModesQuery({});
  const { data: industryData } = useGetIndustryQuery({});
  const { data: departmentData } = useGetDepartmentQuery({});
  const { data: countryData } = useGetCountryQuery({});
  const { data: jobTypeData } = useGetManageJobTypeQuery({});
  const [updateJobs, { isLoading}] = useUpdateJobsMutation();
  // console.log('Modes:', jobTypeData?.data.data);

  const initialState = {
    jobTitle: data?.job_title || "",
    workspaceMode: data?.workspace_mode_xid || "",
    category: data?.industry_xid || "",
    subCategory: data?.department_xid || "",
    salary: data?.ctc_amount || "",
    experience: data?.experience || "",
    jobLocation: data?.job_location || "",
    countrySelection: data?.country_xid || "",
    jobType: data?.job_type_xid || "",
    skillsDescription: data?.skill_description || "",
    jobDescription: data?.job_description || "",
  };

  const [state, dispatch] = useReducer(reducerFunction, initialState);
  const closeRef = useRef<HTMLButtonElement>(null);

  const getDisplayName = (name: string, maxLength = 30) =>
    name.length > maxLength ? name.slice(0, maxLength) + "..." : name;

    const handleSubmit = async () => {
      const {
        jobTitle,
        workspaceMode,
        category,
        subCategory,
        salary,
        experience,
        jobLocation,
        countrySelection,
        jobType,
        skillsDescription,
        jobDescription,
      } = state;

      if (
        !jobTitle ||
        !workspaceMode ||
        !category ||
        !subCategory ||
        !salary ||
        !experience ||
        !jobLocation ||
        !countrySelection ||
        !jobType ||
        !skillsDescription ||
        !jobDescription
      ) {
        toaster.create({
          title: "Missing Fields",
          description: "Please fill in all required fields before submitting.",
          type: "error",
        });
        return;
      }
  
      // Only en_name is editable, so we only need to send that in the payload.
      const payload = {
        id: data?.id,
        job_title: state.jobTitle,
        workspace_mode_xid: state.workspaceMode,
        industry_xid: state.category,
        department_xid: state.subCategory,
        ctc_amount: state.salary,
        experience: state.experience,
        job_location: state.jobLocation,
        country_xid: state.countrySelection,
        job_type_xid: state.jobType,
        skill_description: state.skillsDescription,
        job_description: state.jobDescription,
      };
  
      // console.log('payload', payload)
  
      try {
        const response = await updateJobs(payload).unwrap();
        if (response?.status === "success") {
          toaster.create({
            title: "Success",
            description: "Country updated successfully",
            type: "success",
          });
          closeRef.current?.click();
          refetch()
        } else {
          toaster.create({
            title: "Error",
            description: "Failed to update Country",
            type: "error",
          });
        }
      } catch (error) {
        console.error("Error updating template:", error);
        // alert("Failed to update template");
        toaster.create({
          title: "Error",
          description: "Something went wrong",
          type: "error",
        });
      }
    };

  return (
    <DialogRoot placement="center">
      <DialogTrigger asChild>
        <Span><Edit /></Span>
      </DialogTrigger>

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

        <DialogBody bg="white">
          <Stack py={3}>
            <Field.Root>
              <Field.Label color="black" pt={1} fontSize="12px">
                Job title
              </Field.Label>
              <Input
                placeholder="Enter the Job Title"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={state.jobTitle}
                onChange={(e) =>
                  dispatch({
                    type: "SET_JOB_TITLE",
                    payload: e.target.value,
                  })
                }
              />
            </Field.Root>
            <Field.Root>
              <Field.Label color="black" pt={1} fontSize="12px">
                Workspace mode
              </Field.Label>
              <select
                style={{
                  backgroundColor: "#EEEEEE",
                  color: "black",
                  border: "none",
                  height: "30px",
                  fontSize: "12px",
                  padding: "4px",
                  borderRadius: "4px",
                  width: "100%",
                }}
                value={state.workspace_mode_xid}
                onChange={(e) =>
                  dispatch({
                    type: "SET_WORKSPACE_MODE",
                    payload: Number(e.target.value),
                  })
                }
              >
                <option value="" disabled>
                  Select country
                </option>
                {workspaceModes && workspaceModes?.data.map((mode: WorkSpace) => (
                  <option key={mode.id} value={mode.id}>
                    {getDisplayName(mode.en_name)}
                  </option>
                ))}
              </select>
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Category
              </Field.Label>
              <select
                style={{
                  backgroundColor: "#EEEEEE",
                  color: "black",
                  border: "none",
                  height: "30px",
                  fontSize: "12px",
                  padding: "4px",
                  borderRadius: "4px",
                  width: "100%",
                }}
                value={state.industry_xid}
                onChange={(e) =>
                  dispatch({
                    type: "SET_INDUSTRY",
                    payload: Number(e.target.value),
                  })
                }
              >
                <option value="" disabled>
                  Select department
                </option>
                {industryData && industryData?.data.map((mode: WorkSpace) => (
                  <option key={mode.id} value={mode.id}>
                    {getDisplayName(mode.en_name)}
                  </option>
                ))}
              </select>
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Sub-Category
              </Field.Label>
              <select
                style={{
                  backgroundColor: "#EEEEEE",
                  color: "black",
                  border: "none",
                  height: "30px",
                  fontSize: "12px",
                  padding: "4px",
                  borderRadius: "4px",
                  width: "100%",
                }}
                value={state.department_xid}
                onChange={(e) =>
                  dispatch({
                    type: "SET_DEPARTMENT",
                    payload: Number(e.target.value),
                  })
                }
              >
                <option value="" disabled>
                  Select department
                </option>
                {departmentData && departmentData?.data.map((mode: WorkSpace) => (
                  <option key={mode.id} value={mode.id}>
                    {getDisplayName(mode.en_name)}
                  </option>
                ))}
              </select>
            </Field.Root>

            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Country
              </Field.Label>
              <select
                style={{
                  backgroundColor: "#EEEEEE",
                  color: "black",
                  border: "none",
                  height: "30px",
                  fontSize: "12px",
                  padding: "4px",
                  borderRadius: "4px",
                  width: "100%",
                }}
                value={state.country_xid}
                onChange={(e) =>
                  dispatch({
                    type: "SET_COUNTRY",
                    payload: Number(e.target.value),
                  })
                }
              >
                <option value="" disabled>
                  Select country
                </option>
                {countryData && countryData?.data.map((mode: WorkSpace) => (
                  <option key={mode.id} value={mode.id}>
                    {getDisplayName(mode.en_name)}
                  </option>
                ))}
              </select>
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Job type
              </Field.Label>
              <select
                style={{
                  backgroundColor: "#EEEEEE",
                  color: "black",
                  border: "none",
                  height: "30px",
                  fontSize: "12px",
                  padding: "4px",
                  borderRadius: "4px",
                  width: "100%",
                }}
                value={state.job_type_xid}
                onChange={(e) =>
                  dispatch({
                    type: "SET_JOB_TYPE",
                    payload: Number(e.target.value),
                  })
                }
              >
                <option value="" disabled>
                  Select Job Type
                </option>
                {jobTypeData && jobTypeData?.data.data.map((mode: WorkSpace) => (
                  <option key={mode.id} value={mode.id}>
                    {getDisplayName(mode.en_name)}
                  </option>
                ))}
              </select>
            </Field.Root>

            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Salary
              </Field.Label>
              <Input
                placeholder="Enter the Salary"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={state.salary}
                onChange={(e) =>
                  dispatch({
                    type: "SET_SALARY",
                    payload: e.target.value,
                  })
                }
              />
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Experience
              </Field.Label>
              <Input
                placeholder="Enter the Experience in years"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={state.experience}
                onChange={(e) =>
                  dispatch({
                    type: "SET_EXPERIENCE",
                    payload: e.target.value,
                  })
                }
              />
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Job Location
              </Field.Label>
              <Input
                placeholder="Enter the Job Location"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={state.jobLocation}
                onChange={(e) =>
                  dispatch({
                    type: "SET_JOB_LOCATION",
                    payload: e.target.value,
                  })
                }
              />
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Skills description
              </Field.Label>
              <Input
                placeholder="Enter the Skills description"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={state.skillsDescription}
                onChange={(e) =>
                  dispatch({
                    type: "SET_SKILLS_DESCRIPTION",
                    payload: e.target.value,
                  })
                }
              />
            </Field.Root>
            <Field.Root>
              <Field.Label pt={1} color="black" fontSize="12px">
                Job Description*
              </Field.Label>
              <Input
                placeholder="Enter the Job Description"
                bgColor="#EEEEEE"
                color="black"
                border="none"
                pl={1}
                fontSize="12px"
                height="30px"
                value={state.jobDescription}
                onChange={(e) =>
                  dispatch({
                    type: "SET_JOB_DESCRIPTION",
                    payload: e.target.value,
                  })
                }
              />
            </Field.Root>
          </Stack>
        </DialogBody>
        <DialogFooter display="flex" justifyContent="center" pt={"2"}>
          <Button
            w="100%"
            bg="#02A0A0"
            color={"#fff"}
            fontSize="12px"
            height="30px"
            onClick={handleSubmit}
            disabled={isLoading}
          >
            Save
          </Button>
        </DialogFooter>

        <DialogCloseTrigger color="black" ref={closeRef} />
      </DialogContent>
      <Toaster />
    </DialogRoot>
  );
}

export default ManageJobsAdd;
