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

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

const groupTypes = [
    {key: "rural", value: "روستایی", disabled: false},
    {key: "industrial", value: "صنعتی", disabled: false},
    {key: "nomadic", value: "عشایری", disabled: false},
];

const planTypes = [
    {key: "ILQ", value: "افزایش سهمیه دام", disabled: false},
    {key: "SM", value: "آماری / پایشی", disabled: true},
];

const limitTimeTypes = [
    {label: "دارد", value: true},
    {
        label: "ندارد",
        value: false,
    },
];

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

    const [isTimeUnlimited, setIsTimeUnlimited] = useState(
        item ? item?.is_time_unlimited : false
    );

    const schema = z.object({
        name: zValidateString("نام طرح"),
        description: zValidateStringOptional("توضیحات"),
        plan_type: zValidateAutoComplete("نوع طرح"),
        group: zValidateAutoComplete("گروه"),
        // is_time_unlimited: zValidateNumber("شهر"),
        start_date_limit: isTimeUnlimited
            ? zValidateString("تاریخ شروع محدودیت")
            : zValidateStringOptional("تاریخ شروع محدودیت"),
        end_date_limit: isTimeUnlimited
            ? zValidateString("تاریخ اتمام محدودیت")
            : zValidateStringOptional("تاریخ اتمام محدودیت"),
    });

    type FormValues = z.infer<typeof schema>;

    const {
        control,
        handleSubmit,
        setValue,
        formState: {errors},
    } = useForm<FormValues>({
        resolver: zodResolver(schema),
        defaultValues: {
            name: item?.name || "",
            description: item?.description || "",
            group: item?.group ? [item?.group] : [],
            plan_type: item?.plan_type ? [item?.plan_type] : [],
            start_date_limit: item?.start_date_limit,
            end_date_limit: item?.end_date_limit,
        },
    });

    const mutation = useApiMutation({
        api: `/product/web/api/v1/incentive_plan/${item ? item?.id + "/" : ""}`,
        method: item ? "put" : "post",
    });

    const onSubmit = async (data: FormValues) => {
        try {
            await mutation.mutateAsync({
                name: data.name,
                description: data.description,
                plan_type: data.plan_type[0],
                group: data.group[0],
                is_time_unlimited: isTimeUnlimited,
                ...(isTimeUnlimited
                    ? {
                        start_date_limit: data?.start_date_limit,
                        end_date_limit: data?.end_date_limit,
                    }
                    : {}),

                ...(item
                    ? {registering_organization: item?.registering_organization}
                    : {}),
            });
            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)}>
            <Grid container column className="gap-2">
                <Controller
                    name="name"
                    control={control}
                    render={({field}) => (
                        <Textfield
                            fullWidth
                            placeholder="نام طرح "
                            value={field.value}
                            onChange={field.onChange}
                            error={!!errors.name}
                            helperText={errors.name?.message}
                        />
                    )}
                />

                <Controller
                    name="description"
                    control={control}
                    render={({field}) => (
                        <Textfield
                            fullWidth
                            placeholder="توضیحات (اختیاری)"
                            value={field.value}
                            onChange={field.onChange}
                            error={!!errors.description}
                            helperText={errors.description?.message}
                        />
                    )}
                />

                <Controller
                    name="plan_type"
                    control={control}
                    render={({field}) => (
                        <AutoComplete
                            data={planTypes}
                            selectedKeys={field.value}
                            onChange={(keys: (string | number)[]) => {
                                setValue("plan_type", keys);
                            }}
                            error={!!errors.plan_type}
                            helperText={errors.plan_type?.message}
                            title="نوع طرح"
                        />
                    )}
                />

                <Controller
                    name="group"
                    control={control}
                    render={({field}) => (
                        <AutoComplete
                            data={groupTypes}
                            selectedKeys={field.value}
                            onChange={(keys: (string | number)[]) => {
                                setValue("group", keys);
                            }}
                            error={!!errors.group}
                            helperText={errors.group?.message}
                            title="گروه"
                        />
                    )}
                />

                <RadioGroup
                    groupTitle="محدودیت زمانی"
                    className="mr-2 mt-2"
                    direction="row"
                    options={limitTimeTypes}
                    name="دریافت تعرفه"
                    value={isTimeUnlimited}
                    onChange={(e) =>
                        e.target.value === "true"
                            ? setIsTimeUnlimited(true)
                            : setIsTimeUnlimited(false)
                    }
                />

                {isTimeUnlimited && (
                    <>
                        <DatePicker
                            value={item?.start_date_limit || ""}
                            label="تاریخ شروع طرح"
                            size="medium"
                            onChange={(r) => {
                                setValue("start_date_limit", r);
                            }}
                        />

                        <DatePicker
                            value={item?.end_date_limit || ""}
                            label="تاریخ اتمام طرح"
                            size="medium"
                            onChange={(r) => {
                                setValue("end_date_limit", r);
                            }}
                        />
                    </>
                )}

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