import React, { useEffect, useState } from 'react';
import { useApiHook, useAxios } from '@bjsdistribution/dms-component-library';
import 'react-datepicker/dist/react-datepicker.css';
import CreateReminder from './CreateReminderModal';
import {
  initialValue,
  useStaticData,
  useCreateReminderPayload,
  useNotiifcationLabel,
} from '../../store';
import { allTypes } from '../../types';
import { ContentContainer } from './SharedComponents';
import { useCurrentAction } from '../../../store';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import styled from 'styled-components';
import { notification } from 'antd';

interface ApiResponse {
  message: string;
  code: number;
  error: string | null;
  error_traceback: string | null;
  data: allTypes[];
}
interface IProps {
  callReminderApi: any;
  callUnresolvedTaskApi: any;
}
function ReminderModal(props: IProps) {
  const [, setCurrentAction] = useCurrentAction();
  const [createReminder, setReminderPayload] = useCreateReminderPayload();
  const [label] = useNotiifcationLabel();
  const [, setStaticData] = useStaticData();
  const [, setExtracted] = useState('');

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

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

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

  const closeModal = () => {
    setCurrentAction(undefined);
    setReminderPayload(initialValue);
  };
  console.log(createReminder, 'createReminder');
  const handleReminderSubmit = async () => {
    try {
      const response = (await createReminderAPI({
        payload: [createReminder],
      })) as {
        code: number | null;
        message?: string;
        error?: string | null;
        error_traceback?: string;
        data?: any;
      };

      if (response?.code === 200 && response?.data) {
        notification.success({
          message: 'Success',
          description: response?.message || 'Reminder created successfully',
        });
        closeModal();
        await props?.callReminderApi();
      } else {
        notification.error({
          message: 'Error',
          description:
            response?.error ||
            'Something went wrong while creating the reminder.',
        });
      }
    } catch (error) {
      const err = error as any;

      const errMsg =
        err?.response?.data?.error ||
        err?.response?.data?.message ||
        err?.message ||
        'An unexpected error occurred.';

      notification.error({
        message: 'Request Failed',
        description: errMsg,
      });
    }
  };
  const isSubmitDisabled = () => {
    const {
      department,
      assigned_to,
      priority,
      due_datetime,
      description,
    } = createReminder;
    return (
      !department ||
      !description ||
      !due_datetime ||
      !priority ||
      assigned_to?.length === 0 ||
      !assigned_to
    );
  };

  useEffect(() => {
    const match = label.match(/\(([^)]+)\)/);
    const extractedText = match ? match[1] : '';
    setExtracted(extractedText);
  }, [label]);

  return (
    <>
      {/* {loading && <Loader />} */}
      <OrderModal
        headerTitle={'CREATE REMINDER'}
        onCloseHeader={closeModal}
        onSubmit={handleReminderSubmit}
        submitBtnTitle={'Save Reminder'}
        isSubmitDisabled={isSubmitDisabled()}
        footerActions={''}
      >
        <ContentContainer>{<CreateReminder />}</ContentContainer>
      </OrderModal>
    </>
  );
}

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

export default ReminderModal;
