import { Form, Formik } from 'formik';
import * as Yup from 'yup';
import { useQuery } from '@tanstack/react-query';
import { AiPromptsSettingsAPI, UpdateSettingsAPI } from '@/Utils/APIRequest/Endpoints';
import CustomFetch from '@/Utils/APIRequest/AxiosInstance';
import usePost from '@/Utils/Hooks/usePost';
import { CustomToast } from '@/Utils/CustomToast';
import FormikTextarea from '@/Component/Common/Forms/FormikTextarea';
import FormikSelect from '@/Component/Common/Forms/FormikSelect';
import FormikInput from '@/Component/Common/Forms/FormikInput';
import { ErrorInfoSVG, LoaderSVG } from '@/Component/Common/SVGs/CommonSVG';
import GradientButton from '@/Component/Common/Forms/GradientButton';
import FormLabel from '@/Component/Common/Forms/FormLabel';
import Loader from '@/Layout/Loader';

const AI_MODEL_OPTIONS = [
    { label: 'GPT-5.6', value: 'gpt-5.6' },
    { label: 'GPT-5.6 Sol', value: 'gpt-5.6-sol' },
    { label: 'GPT-5.6 Terra', value: 'gpt-5.6-terra' },
    { label: 'GPT-5.6 Luna', value: 'gpt-5.6-luna' },
    { label: 'GPT-5.1', value: 'gpt-5.1' },
    { label: 'GPT-5 Mini', value: 'gpt-5-mini' },
    { label: 'GPT-4.1', value: 'gpt-4.1' },
    { label: 'GPT-4.1 Mini', value: 'gpt-4.1-mini' },
];

const getModelOptions = (currentValue) => {
    if (currentValue && !AI_MODEL_OPTIONS.some((option) => option.value === currentValue)) {
        return [{ label: currentValue, value: currentValue }, ...AI_MODEL_OPTIONS];
    }
    return AI_MODEL_OPTIONS;
};

const AiPromptsSettings = () => {

    // Get API
    const { data: SettingsDetailData, isPending: DetailLoader, refetch } = useQuery({ queryKey: [AiPromptsSettingsAPI], queryFn: () => CustomFetch({ url: AiPromptsSettingsAPI }, null, false), refetchOnWindowFocus: false, select: (data) => data?.data?.data });

    // Put API
    const { isPending, mutate } = usePost(UpdateSettingsAPI, null, (response) => {
        if (response?.status == 200 || response?.status == 201) {
            CustomToast("success", "Settings updated successfully")
            refetch()
        }
    }, "Put");

    const initialValues = SettingsDetailData?.reduce((acc, item) => {
        acc[item.id] = item.value || '';
        return acc;
    }, {});

    const validationSchema = Yup.object().shape(
        SettingsDetailData?.reduce((acc, item) => {
            if (item.type === 'ai_agent_report_top_n') {
                acc[item.id] = Yup.string()
                    .required(`${item.name} is required`)
                    .matches(/^\d+$/, `${item.name} must be a number`)
                    .test('min-1', `${item.name} must be at least 1`, (value) => !value || Number(value) >= 1)
                    .test('max-250', `${item.name} cannot exceed 250`, (value) => !value || Number(value) <= 250);
            } else {
                acc[item.id] = Yup.string().required(`${item.name} is required`);
            }
            return acc;
        }, {})
    );

    const handleSubmit = async (values) => {
        const request_array = Object.keys(values).map(key => ({
            id: key,
            value: values[key]
        }));
        const payload: any = { request_array };
        mutate(payload);
    };

    return (
        <>
            {DetailLoader && <Loader />}
            <Formik
                enableReinitialize validationSchema={validationSchema}
                initialValues={initialValues} onSubmit={handleSubmit}
            >
                {({ errors, touched, setFieldValue }) => (
                    <Form>
                        <span className='text-sm mb-4 inline-block text-red-600'>Note: Please do not change the Variables in the prompt.</span>
                        <div className='grid grid-cols-1 gap-4'>
                            <div className='flex flex-wrap gap-4'>
                                {SettingsDetailData?.filter((item) => item.type === 'ai_model' || item.type === 'ai_agent_report_top_n').map((item) => (
                                    <div key={item.id} className='md:max-w-sm w-full'>
                                        <FormLabel title={item.name} />
                                        <div className={`relative`}>
                                            {item.type === 'ai_model' ? (
                                                <FormikSelect customClass="!border-neutral-200 !rounded-2xl !py-3 !font-medium !text-black !bg-[95%]" selectProps={{ name: `${item.id}` }}>
                                                    <option value="">Select {item.name}</option>
                                                    {getModelOptions(item.value).map((option) => (
                                                        <option key={option.value} value={option.value}>{option.label}</option>
                                                    ))}
                                                </FormikSelect>
                                            ) : (
                                                <FormikInput inputProps={{
                                                    type: 'text',
                                                    inputMode: 'numeric',
                                                    pattern: '[0-9]*',
                                                    name: `${item.id}`,
                                                    placeholder: `Enter ${item.name}`,
                                                    maxLength: 3,
                                                    onChange: (e) => {
                                                        const digits = e.target.value.replace(/\D/g, '');
                                                        if (!digits) {
                                                            setFieldValue(item.id, '');
                                                            return;
                                                        }
                                                        setFieldValue(item.id, String(Math.min(Number(digits), 250)));
                                                    }
                                                }} />
                                            )}
                                            {errors[item.id] && touched[item.id] && (
                                                <div className="flex items-center mt-2">
                                                    <ErrorInfoSVG customClass={'mr-1'} /><span className="text-error text-sm">
                                                        {`${errors[item.id]}`}
                                                    </span>
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                ))}
                            </div>
                            {SettingsDetailData?.filter((item) => item.type !== 'ai_model' && item.type !== 'ai_agent_report_top_n').map((item) => (
                                <div key={item.id}>
                                    <FormLabel title={item.name} />
                                    <div className={`relative`}>
                                        <FormikTextarea textareaProps={{ name: `${item.id}`, placeholder: `Enter ${item.name}`, rows: 20 }} />
                                        {errors[item.id] && touched[item.id] && (
                                            <div className="flex items-center mt-2">
                                                <ErrorInfoSVG customClass={'mr-1'} /><span className="text-error text-sm">
                                                    {`${errors[item.id]}`}
                                                </span>
                                            </div>
                                        )}
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className='flex items-center justify-start mt-5'>
                            <GradientButton buttonType={'submit'} customClass={'flex justify-center items-center w-full max-w-40'} disabled={isPending}>
                                Update
                                {isPending && <LoaderSVG customClass='ml-2.5' />}
                            </GradientButton>
                        </div>
                    </Form>
                )}
            </Formik>
        </>
    )
}

export default AiPromptsSettings
