import React from 'react';
import { useEffect } from 'react';
import {
  RadioButtonGroup,
  useApiHook,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import 'react-datepicker/dist/react-datepicker.css';
import { CustomOptions } from '../../../../fakeData';
import {
  initialPayload,
  useStaticData,
  useCreateTaskPayload,
  useNotiifcationLabel,
} from '../../store';
import { allTypes } from '../../types';
import { useCurrentAction } from '../../../store';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import styled from 'styled-components';
import { notification } from 'antd';
import { ContentContainer } from '../modalstyle';
import CreateTaskModal from './CreateTaskModal';

interface ApiResponse {
  message: string;
  code: number;
  error: string | null;
  error_traceback: string | null;
  data: allTypes[];
}
interface IProps {
  callReminderApi: any;
  callUnresolvedTaskApi: any;
}

function TaskModal(props: IProps) {
  const [, setCurrentAction] = useCurrentAction();
  const [taskPayload, setTaskPayload] = useCreateTaskPayload();
  const [, setLabel] = useNotiifcationLabel();
  const [, setStaticData] = useStaticData();

  const { fetchData: createFlagAPI } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/`,
    method: 'POST',
  });

  const { data: fetchedStaticData } = useApiHook<ApiResponse>({
    endpoint: `/v1/task/getStaticData/all/`,
    method: 'GET',
  });

  useEffect(() => {
    if (fetchedStaticData) {
      setStaticData(fetchedStaticData?.data);
    }
  }, [fetchedStaticData]);

  const handleRadioButtonChange = (event: any) => {
    const selectedValue = event.target.value;
    const isPrivateValue = selectedValue === 'private';
    setTaskPayload(prevState => ({
      ...prevState,
      is_private: isPrivateValue,
    }));
  };

  const closeModal = () => {
    setCurrentAction(undefined);
    setTaskPayload(initialPayload);
    setLabel('');
  };

  const handleTaskSubmit = async () => {
    let response = (await createFlagAPI({ payload: [taskPayload] })) as {
      code: number | null;
      error?: string | null | undefined;
      [key: string]: any;
    };
    if (response.code == 200 && response?.data) {
      closeModal();
      notification.success({
        message: 'Success',
        description: `${response.message}`,
      });
      await props?.callUnresolvedTaskApi();
    }
    if (response?.code == null && response?.error) {
      return notification.error({
        message: 'Failure',
        description: `${response.error}`,
      });
    }
  };

  const isSubmitDisabled = () => {
    const { description, due_datetime, flag_type, priority } = taskPayload;
    return !description || !due_datetime || !flag_type || !priority;
  };

  return (
    <>
      <OrderModal
        headerTitle={'CREATE TASK'}
        onCloseHeader={closeModal}
        onSubmit={handleTaskSubmit}
        submitBtnTitle={'Save Details'}
        isSubmitDisabled={isSubmitDisabled()}
        footerActions={
          <RadioButtonGroup
            selectedValue={
              taskPayload?.is_private == true ? 'private' : 'public'
            }
            options={CustomOptions}
            onChange={handleRadioButtonChange}
            heading={''}
            required={false}
          />
        }
      >
        <ContentContainer>{<CreateTaskModal />}</ContentContainer>
      </OrderModal>
    </>
  );
}

const OrderModal = styled(OrderActionModal)`
  width: 70%;
`;

export default TaskModal;
