import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import {
  CancelAndCompleteAction,
  CancelationModal,
  CrossIcon,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import { useResolvedPayload, useFlagById } from '../order-actions/store';
import { useCurrentAction } from '../store';
import { ApiResponse } from '../types';
import { notification } from 'antd';

function HeaderSection({ callUnresolvedTaskApi, setTasksData }: any) {
  const [flagById] = useFlagById();
  const [forResolvedPayload, setPayload] = useResolvedPayload();
  const [, setCurrentAction] = useCurrentAction();
  const [isModalOpen, setIsModalOpen] = useState(false);

  //flag PUT API
  const { fetchData: callFlagUpdateAPI } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/resolve/`,
    method: 'PUT',
  });

  useEffect(() => {
    if (flagById) {
      setPayload({
        task_ids: [flagById?.id],
      });
    }
  }, [flagById]);

  const openModal = () => {
    setIsModalOpen(true);
  };

  const closeModal = () => {
    setIsModalOpen(false);
  };

  const saveButton = async () => {
    const response = (await callFlagUpdateAPI({
      payload: forResolvedPayload,
    })) as {
      code: number | null;
      error?: string | null;
      message?: string;
      data?: any;
      [key: string]: any;
    };

    if (response.code === 200 && response?.data) {
      notification.success({
        message: 'Success',
        description: `${response?.message}`,
      });

      setIsModalOpen(false);
      setCurrentAction(undefined);

      // fetch tasks and update state
      const unresolvedResponse = await callUnresolvedTaskApi();
      if (unresolvedResponse && unresolvedResponse?.data) {
        setTasksData(unresolvedResponse?.data);
      }
    }

    if (response?.code == null && response?.error) {
      return notification.error({
        message: 'Failure',
        description: `${response?.error}`,
      });
    }
  };

  const onCancel = () => {
    setCurrentAction(undefined);
  };

  const isShow = flagById?.status !== 'AD';
  return (
    <Header>
      <Title>VIEW TASK</Title>
      {!isShow ? (
        <ResolveButton onClick={openModal}>MARK AS RESOLVED</ResolveButton>
      ) : (
        <CrossWrapper>
          <CrossIcon onClick={onCancel} />
        </CrossWrapper>
      )}
      {isModalOpen && (
        <StyledOverlay>
          <CancelationModal
            title="Mark as Resolved"
            description="Are you sure you want to mark this Flag as resolved?"
            actions={
              <CustomCancelAndCompleteAction
                cancelLabel="Cancel"
                onCancel={closeModal}
                completeLabel="Confirm"
                onComplete={saveButton}
              />
            }
          />
        </StyledOverlay>
      )}
    </Header>
  );
}

const Header = styled.div`
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
`;

const CustomCancelAndCompleteAction = styled(CancelAndCompleteAction)`
  justify-content: center;
`;

const ResolveButton = styled.button`
  color: #3a3630;
  background: #feba30;
  padding: 6px;
  border-radius: 6px;
  font-weight: 600;
  font-size: 13px;
  border: 1px solid #feba30;
`;

const Title = styled.span`
  font-family: 'Roboto', sans-serif;
  font-size: 20px;
  font-weight: 900;
  line-height: 32px;
  text-transform: uppercase;
  color: #3a3630;
`;

const StyledOverlay = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(2px);
  z-index: 1000;
`;

const CrossWrapper = styled.div`
  cursor: pointer;
`;

export default HeaderSection;
