import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useFlagById, useUpdateTask } from '../order-actions/store';
import { useCurrentAction } from '../store';
import Tippy from '@tippyjs/react';
import {
  Button,
  RadioButtonGroup,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../types';
import { notification } from 'antd';

export const FlagsFilter = [
  {
    label: 'Private',
    value: 'private',
  },
  {
    label: 'Public',
    value: 'public',
  },
];

function SaveDetails({ callUnresolvedTaskApi, setTasksData }: any) {
  const [, setCurrentAction] = useCurrentAction();
  const [taskPayload] = useUpdateTask();

  const [flagById] = useFlagById();

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

  const onSubmit = async () => {
    const response = (await callFlagUpdateAPI({
      payload: [taskPayload],
    })) 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}`,
      });

      setCurrentAction(undefined);

      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 isDisabled = flagById?.status === 'SD';

  return (
    <Wrapper>
      <Tippy
        content={
          <TooltipContent>
            {
              'This task cannot be edited because it has been marked as resolved.'
            }
          </TooltipContent>
        }
        placement="bottom"
        arrow={true}
        disabled={!isDisabled}
      >
        <ButtonWrapper>
          <SaveButton onClick={onSubmit} disabled={isDisabled}>
            SAVE DETAILS
          </SaveButton>
          <CancelButton onClick={onCancel}>CANCEL</CancelButton>
        </ButtonWrapper>
      </Tippy>
    </Wrapper>
  );
}

function RadioButtonsSection() {
  const [flagById] = useFlagById();
  const [taskPayload, setPayload] = useUpdateTask();
  const [, setNewValue] = useState<boolean | string>(false);

  useEffect(() => {
    const defaultSelectedValue = flagById?.is_private ? false : true;
    setPayload({
      ...taskPayload,
      is_private: defaultSelectedValue,
    });
  }, [flagById?.is_private]);

  const handleRadioButtonChange = (event: any) => {
    const value = event.target.value;

    let booleanValue: boolean;
    if (value === 'private') {
      booleanValue = true;
    } else {
      booleanValue = false;
    }

    setNewValue(value);
    setPayload({
      ...taskPayload,
      is_private: booleanValue,
    });
  };

  return (
    <DropDowns>
      <RadioButtonGroup
        selectedValue={taskPayload?.is_private == false ? 'public' : 'private'}
        options={FlagsFilter}
        onChange={handleRadioButtonChange}
        heading={''}
        required={false}
      />
    </DropDowns>
  );
}

const ButtonWrapper = styled.div`
  display: flex;
  gap: 15px;
  margin-right: 15px;
`;

const SaveButton = styled(Button)``;

const CancelButton = styled(Button)`
  background-color: white;
  color: #3a3630;
`;

const DropDowns = styled.div`
  display: flex;
  gap: 25px;
`;

const TooltipContent = styled.div`
  background-color: #333;
  color: #fff;
  padding: 5px 10px;
  border-radius: 5px;
`;

const Wrapper = styled.div``;

export { SaveDetails, RadioButtonsSection };
