import { Controller, useForm } from "react-hook-form";
import { Grid } from "../../components/Grid/Grid";
import Button from "../../components/Button/Button";
import { z } from "zod";
import {
  zValidateAutoComplete,
  zValidateString,
  zValidateStringOptional,
} from "../../data/getFormTypeErrors";
import { useToast } from "../../hooks/useToast";
import { useModalStore } from "../../context/zustand-store/appStore";
import { zodResolver } from "@hookform/resolvers/zod";
import { useApiMutation } from "../../utils/useApiRequest";
import { getToastResponse } from "../../data/getToastResponse";
import { FormApiBasedAutoComplete } from "../../components/FormItems/FormApiBasedAutoComplete";
import { RadioGroup } from "../../components/RadioButton/RadioGroup";
import { useState } from "react";
import Textfield from "../../components/Textfeild/Textfeild";
import Divider from "../../components/Divider/Divider";

type AddPosProps = {
  getData: () => void;
  item?: any;
};

const allocateTypes = [
  { label: "سازمان", value: "org" },
  { label: "صنف", value: "guild", disabled: true },
  { label: "صنف آزاد", value: "free", disabled: true },
];

export const AllocatePos = ({ getData, item }: AddPosProps) => {
  const showToast = useToast();
  const { closeModal } = useModalStore();

  const [activityType, setAllocateType] = useState("org");

  const schema = z.object({
    name: zValidateString("نام"),
    organization: zValidateAutoComplete("سازمان"),
    acceptor: item?.acceptor
      ? zValidateStringOptional("پذیرنده")
      : zValidateString("پذیرنده"),
    terminal: item?.terminal
      ? zValidateStringOptional("ترمینال")
      : zValidateString("ترمینال"),
  });

  type FormValues = z.infer<typeof schema>;

  const {
    control,
    handleSubmit,
    setValue,
    trigger,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
    defaultValues: {
      terminal: item?.terminal || "",
      acceptor: item?.acceptor || "",
      organization: [],
    },
  });

  const mutation = useApiMutation({
    api: `/pos_device/web/v1/pos/device_assignment/${
      item?.assignment?.client ? item?.assignment?.id + "/" : ""
    }`,

    method: item?.assignment?.client ? "put" : "post",
  });

  const onSubmit = async (data: FormValues) => {
    try {
      await mutation.mutateAsync({
        client_data: {
          ...(item?.assignment?.client
            ? { id: item?.assignment?.client?.id }
            : {}),
          client_type: "organization",
          is_organization: true,
          organization: data?.organization[0],
        },
        device: item?.id,
        ...(!item?.acceptor && {
          acceptor: data?.acceptor,
          terminal: data?.terminal,
        }),
      });

      showToast(getToastResponse(item, ""), "success");
      getData();
      closeModal();
    } catch (error: any) {
      if (error?.status === 403) {
        showToast(
          error?.response?.data?.message || "این مورد تکراری است!",
          "error"
        );
      } else {
        showToast(
          error?.response?.data?.message || "خطا در ثبت اطلاعات!",
          "error"
        );
      }
    }
  };

  return (
    <form
      onSubmit={handleSubmit(onSubmit, (formErrors) => {
        console.log("Validation errors:", formErrors);
      })}
    >
      <Grid container column className="gap-2">
        <RadioGroup
          direction="row"
          groupTitle="نوع تخصیص"
          options={allocateTypes}
          name="نوع تخصیص"
          value={activityType}
          onChange={(e) => setAllocateType(e.target.value)}
        />

        <Controller
          name="organization"
          control={control}
          render={() => (
            <>
              <FormApiBasedAutoComplete
                defaultKey={item?.assignment?.client?.organization?.id}
                title="انتخاب سازمان"
                api={`auth/api/v1/organization/organizations_by_province?exclude=PSP&province=${item?.organization?.province}`}
                keyField="id"
                valueField="name"
                error={!!errors.organization}
                errorMessage={errors.organization?.message}
                onChange={(r) => {
                  setValue("organization", [r]);
                  trigger("organization");
                }}
              />
            </>
          )}
        />

        {(!item?.acceptor || !item?.terminal) && (
          <Divider className="text-sm">تکمیل اطلاعات دستگاه</Divider>
        )}

        {!item?.acceptor && (
          <Controller
            name="acceptor"
            control={control}
            render={({ field }) => (
              <Textfield
                fullWidth
                placeholder="شماره پذیرنده"
                value={field.value}
                onChange={field.onChange}
                error={!!errors.acceptor}
                helperText={errors.acceptor?.message}
              />
            )}
          />
        )}

        {!item?.terminal && (
          <Controller
            name="terminal"
            control={control}
            render={({ field }) => (
              <Textfield
                fullWidth
                placeholder="شماره ترمنینال"
                value={field.value}
                onChange={field.onChange}
                error={!!errors.terminal}
                helperText={errors.terminal?.message}
              />
            )}
          />
        )}

        <Button type="submit">ثبت</Button>
      </Grid>
    </form>
  );
};
