import {
  Button,
  Input,
  InputRightAddon,
  Stack,
  FormErrorMessage,
  FormControl,
  FormLabel,
  InputGroup,
} from '@chakra-ui/react';
import { Formik, Form, Field } from 'formik';

import * as Yup from 'yup';
import Recorder from '../common/Recorder';
import EventFormatSelector from '../common/EventFormatSelector';
import FormattedCodeViewer from '../common/FormattedCodeViewer';
import AlertDialog from '../common/AlertDialog';
import ScheduleSelector from '../common/ScheduleSelector';
import { EVENT_NAMES } from '../../constants/define';
import InfiniteSelect from '../common/InfiniteSelect';
const JobSchema = Yup.object().shape({
  name: Yup.string().required('Required'),
  countyId: Yup.string().required('Required'),
  url: Yup.string().required('Required').url('Invalid Url'),
  actionCode: Yup.array().required('Required'),
  frequency: Yup.string().required('Required'),
  startDate: Yup.date(),
  endDate: Yup.date(),
});

const initialFormValues = {
  name: '',
  countyId: '',
  url: 'https://vmatrix1.brevardclerk.us/beca/Beca_Splash.cfm',
  actionCode: [],
  frequency: 'daily',
  startDate: new Date(),
  endDate: new Date(),
};

const JobCreationForm = ({ formRef, isLoading, onCreate }) => {
  const handleCreate = async () => {
    await onCreate();
  };
  // const handleUpdateEventsLog = (newValue) => {
  //   formRef.current.setFieldValue('action_code', isEmpty(newValue) ? [] : newValue);
  // };

  const handleScheduleChange = (newValue) => {
    // Lấy giá trị hiện tại của form
    const currentValues = formRef.current.values;

    // Khởi tạo một đối tượng mới với các giá trị hiện tại
    let newValues = {
      ...currentValues,
      frequency: newValue.frequency || currentValues.frequency,
      startDate: newValue.startDate || currentValues.startDate,
      endDate: newValue.endDate || currentValues.endDate,
    };

    // Xử lý dựa trên loại tần suất
    switch (newValue.frequency) {
      case 'weekly':
        // Đối với weekly, chỉ đặt dayOfWeek và loại bỏ dayOfMonth
        newValues.dayOfWeek = newValue.dayOfWeek;
        delete newValues.dayOfMonth;
        // delete newValues.endDate;
        break;
      case 'monthly':
        // Đối với monthly, chỉ đặt dayOfMonth và loại bỏ dayOfWeek
        newValues.dayOfMonth = newValue.dayOfMonth;
        delete newValues.dayOfWeek;
        // delete newValues.endDate;
        break;
      case 'daily':
      case 'custome':
      default:
        // Đối với daily và các loại khác, loại bỏ cả dayOfWeek và dayOfMonth
        delete newValues.dayOfWeek;
        delete newValues.dayOfMonth;
        break;
    }

    // Cập nhật toàn bộ trạng thái của form
    formRef.current.setValues(newValues);
  };

  return (
    <AlertDialog onConfirm={handleCreate}>
      {(onOpenConfirmation) => (
        <Formik
          initialValues={initialFormValues}
          innerRef={formRef}
          validationSchema={JobSchema}
          onSubmit={onOpenConfirmation}
        >
          {({ errors, touched, getFieldProps }) => (
            <Form>
              <Stack spacing={4}>
                <Button
                  colorScheme="primary"
                  width="fit-content"
                  disabled={isLoading}
                  isLoading={isLoading}
                  type="submit"
                >
                  Create Job
                </Button>
                <FormControl isInvalid={!!errors.name && touched.name}>
                  <FormLabel htmlFor="name">Job Title</FormLabel>
                  <Field as={Input} id="name" name="name" type="text" variant="filled" />
                  <FormErrorMessage>{errors.name}</FormErrorMessage>
                </FormControl>

                <FormControl isInvalid={!!errors.countyId && touched.countyId}>
                  <FormLabel>County</FormLabel>
                  <Field name="countyId">
                    {({ field }) => <InfiniteSelect eventName={EVENT_NAMES.COUNTIES.LIST} {...field} />}
                  </Field>
                  <FormErrorMessage>{errors.countyId}</FormErrorMessage>
                </FormControl>
                <ScheduleSelector
                  scheduleValues={getFieldProps('schedule').value}
                  onScheduleChange={handleScheduleChange}
                />
                <FormControl isInvalid={!!errors.url && touched.url}>
                  <FormLabel htmlFor="url">Target Scraping</FormLabel>
                  <InputGroup borderRadius={5}>
                    <Field
                      as={Input}
                      id="url"
                      name="url"
                      placeholder="https://github.com"
                      type="text"
                      border="1px solid #949494"
                    />
                    <InputRightAddon p={0} b={0}>
                      <Field
                        name="actionCode"
                        as={Recorder}
                        // onChange={handleUpdateEventsLog}
                        onGetTargetUrl={() => getFieldProps('url').value}
                      />
                    </InputRightAddon>
                  </InputGroup>
                  <FormErrorMessage>{errors.url}</FormErrorMessage>
                </FormControl>
                <FormControl>
                  <Stack>
                    <EventFormatSelector
                      code={getFieldProps('actionCode').value}
                      render={(formatOption, formatedCode) => (
                        <FormattedCodeViewer formatOption={formatOption} formatedCode={formatedCode} />
                      )}
                    />
                  </Stack>
                </FormControl>
              </Stack>
            </Form>
          )}
        </Formik>
      )}
    </AlertDialog>
  );
};

export default JobCreationForm;
