import PropTypes from 'prop-types';
import { Flex, Box, Text, Button, Heading, HStack } from '@chakra-ui/react';
import { useCallback } from 'react';
import { Formik, Form } from 'formik';
import * as Yup from 'yup';

import JobUpdationField from './JobUpdationField';
import {
  Recorder,
  EventFormatSelector,
  FormattedCodeViewer,
  LogViewer,
  AlertDialog,
  EditableInput,
  EditableDatePicker,
  EditableSelect,
  EditableTextarea,
} from '../common';
import { FREQUENCIES } from '../../constants/define';
import { convertDateToString } from '../../utilities/functions';

function JobUpdationForm({ job, logs, formRef, onUpdate, onRun, isRunning, isLoading }) {
  const { url, updatedAt, createdAt } = job || {},
    initialFormValues = {
      name: job?.name,
      url: job?.url,
      actionCode: job?.actionCode,
      frequency: job?.frequency,
      startDate: job?.startDate,
      endDate: job?.endDate,
    },
    isEditabled = true,
    isDisabled = isRunning;

  const getUrl = useCallback(() => {
    return url;
  }, [url]);

  const handleCancelChanges = () => {
    formRef.current.resetForm();
  };

  return (
    <AlertDialog onConfirm={onUpdate}>
      {(onOpenConfirmation) => (
        <Box width="full">
          <Formik
            initialValues={initialFormValues}
            innerRef={formRef}
            validationSchema={JobSchema}
            onSubmit={onOpenConfirmation}
          >
            {({ dirty, getFieldProps }) => {
              const recorderField = {
                key: 'actionCode',
                name: 'actionCode',
                as: Recorder,
                onGetTargetUrl: getUrl,
                isAllowRecord: isEditabled && !isDisabled,
              };

              const informationFields = [
                {
                  key: 'name',
                  name: 'name',
                  label: 'Name',
                  as: EditableInput,
                  isEditabled: isEditabled && !isDisabled,
                },
                {
                  key: 'url',
                  name: 'url',
                  label: 'Root URL',
                  as: EditableTextarea,
                  isEditabled: isEditabled && !isDisabled,
                },
                {
                  key: 'updatedAt',
                  name: 'updatedAt',
                  label: 'Updated',
                  as: (props) => <Text {...props}>{convertDateToString(updatedAt)}</Text>,
                  isEditabled: isEditabled && !isDisabled,
                },
                {
                  key: 'createdAt',
                  name: 'createdAt',
                  label: 'Created',
                  as: (props) => <Text {...props}>{convertDateToString(createdAt)}</Text>,
                  isEditabled: isEditabled && !isDisabled,
                },
                // {
                //   key: 'countyId',
                //   name: 'county',
                //   label: 'County',
                //   // as: (props) => {
                //   //   console.log({ props });
                //   //   return <Text {...props}>{props?.id}</Text>;
                //   // },
                //   as: (props) => {
                //     return (
                //       <EditableSelect
                //         {...props}
                //         options={props?.value?.map((county) => ({
                //           value: county.id,
                //           label: county.title,
                //         }))}
                //       />
                //     );
                //   },
                //   // options: Object.values(FREQUENCIES),
                //   // isEditabled: isEditabled && !isDisabled,
                // },
                {
                  key: 'amount',
                  name: 'amount',
                  label: 'Amount',
                  as: (props) => <Text {...props}>0</Text>,
                  isEditabled: false,
                },
              ];
              const automaticRunFields = [
                {
                  key: 'frequency',
                  name: 'frequency',
                  label: 'Cycle',
                  as: EditableSelect,
                  options: Object.values(FREQUENCIES),
                  isEditabled: isEditabled && !isDisabled,
                },
                {
                  key: 'startDate',
                  name: 'startDate',
                  label: 'Start',
                  as: EditableDatePicker,
                  isEditabled: isEditabled && !isDisabled,
                },
                getFieldProps('frequency').value === FREQUENCIES.CUSTOM && {
                  key: 'endDate',
                  name: 'endDate',
                  label: 'End',
                  as: EditableDatePicker,
                  isEditabled: isEditabled && !isDisabled,
                },
              ];
              return (
                <Form>
                  <Flex justifyContent="space-between" marginBottom="1rem">
                    <Flex mx={2} gap={2} float="right" alignSelf="self-end">
                      <JobUpdationField {...recorderField} />
                    </Flex>

                    <HStack>
                      {job.actionCode?.length > 0 && (
                        <Button colorScheme="primary" isLoading={isRunning} onClick={onRun}>
                          Run Now
                        </Button>
                      )}
                      {dirty && (
                        <>
                          <Button isLoading={isLoading} colorScheme="primary" type="submit">
                            Save
                          </Button>
                          <Button colorScheme="red" onClick={handleCancelChanges}>
                            Rollback
                          </Button>
                        </>
                      )}
                    </HStack>
                  </Flex>
                  <EventFormatSelector
                    code={getFieldProps('actionCode').value}
                    render={(formatOption, formatedCode) => (
                      <Flex justifyContent="flex-start" width="full">
                        <Box flex={2}>
                          <FormattedCodeViewer formatOption={formatOption} formatedCode={formatedCode} />
                        </Box>
                        <Box
                          top={1}
                          height="fit-content"
                          position="sticky"
                          border="0.5px solid rgba(128, 128, 128, 0.5)"
                          margin="1rem 1.3rem 0rem 1rem"
                          flex={1}
                        >
                          <Flex
                            flexDir="column"
                            padding="1rem"
                            gap="1rem"
                            border="0.5px solid rgba(128, 128, 128, 0.5)"
                          >
                            <Heading as="h6" size="md" color="primary.500">
                              Information:
                            </Heading>
                            <Flex flexDir="column" gap="1rem">
                              {informationFields.map((props) => (
                                <JobUpdationField key={props?.key} {...props} />
                              ))}
                            </Flex>
                          </Flex>
                          <Flex
                            flexDir="column"
                            padding="1rem"
                            gap="1rem"
                            border="0.5px solid rgba(128, 128, 128, 0.5)"
                          >
                            <Heading as="h6" size="md" color="primary.500">
                              Automatic Run:
                            </Heading>
                            <Flex flexDir="column" gap="1rem">
                              {automaticRunFields.map((props) => (
                                <JobUpdationField key={props?.key} {...props} />
                              ))}
                            </Flex>
                          </Flex>
                          <Flex
                            flexDir="column"
                            padding="1rem"
                            gap="1rem"
                            border="0.5px solid rgba(128, 128, 128, 0.5)"
                          >
                            <Heading as="h6" size="md" color="primary.500">
                              Status:
                            </Heading>
                            <LogViewer logs={logs} />
                          </Flex>
                        </Box>
                      </Flex>
                    )}
                  />
                </Form>
              );
            }}
          </Formik>
        </Box>
      )}
    </AlertDialog>
  );
}

const JobSchema = Yup.object().shape({
  name: Yup.string().required('Required'),
  countyId: Yup.string(),
  url: Yup.string().required('Required').url('Invalid Url'),
  actionCode: Yup.array().required('Required'),
  frequency: Yup.string().required('Required'),
  startDate: Yup.date().required('Required'),
  // endDate: Yup.date().min(Yup.ref('startDate'), "End date can't be before start date"),
  endDate: Yup.date().when('frequency', {
    is: (value) => value.includes(FREQUENCIES.CUSTOM),
    then: () =>
      Yup.date()
        .min(Yup.ref('startDate'), "End date can't be before start date")
        .required('End date is required when frequency is custom'), // validation when condition is true

    otherwise: () => Yup.date().nullable(),
  }),
});

JobUpdationForm.propTypes = {
  job: PropTypes.shape({
    id: PropTypes.string.isRequired,
    name: PropTypes.string.isRequired,
    countyId: PropTypes.string.isRequired,
    url: PropTypes.string.isRequired,
    actionCode: PropTypes.array.isRequired,
  }),
  logs: PropTypes.array.isRequired,
};

JobUpdationForm.defaultProps = {
  job: {},
  logs: [],
};

export default JobUpdationForm;
