import {
  Button,
  Label,
  useAxios,
  // SelectDropdown,
} from '@bjsdistribution/dms-component-library';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useLocation } from 'react-router-dom';
import { useGlobalStateHitAuditLog, usemoduleIds, useOrderId } from '../store';
import { notification } from 'antd';
import NoteType from './NoteType';
import { useSelectedData } from '../../store';
import { ApiResponse } from '../types';

function AddNote() {
  const [noteText, setNoteText] = useState('');
  const [orderId] = useOrderId();
  const location = useLocation();
  const pathname = location.pathname;
  const orderIdLocaation = pathname.split('/')[1];
  const [moduleIds] = usemoduleIds();
  const [, setRecallAuditLog] = useGlobalStateHitAuditLog();
  const [selected] = useSelectedData();

  // Save New Note
  const { fetchData: callAuditLogs } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/audit_logs/orders/`,
    method: 'POST',
  });

  const [notificationData, setNotificationData] = useState<{
    type: 'success' | 'error';
    message: string;
    description: string;
  } | null>(null);

  const saveNote = async () => {
    setRecallAuditLog(false);
    if (!noteText) return;
    const payload = {
      audit_logs: [
        {
          parent_object_id: orderId || orderIdLocaation,
          parent_module_id: moduleIds?.parentId,
          module_id: moduleIds?.id,
          module_object_id: orderId || orderIdLocaation,
          action: 'create',
          description: noteText,
          data_dump: '{}',
          manual: 1,
          is_private: selected,
        },
      ],
    };
    try {
      let response = (await callAuditLogs({
        payload: payload,
      })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };
      if (response.code == 200 && response?.data) {
        notification.success({
          message: 'Success',
          description: `${response?.message}`,
        });
        setNoteText('');
        setRecallAuditLog(true);
      } else {
        notification.error({
          message: 'Error',
          description: `${response?.error}`,
        });
      }
    } catch (error) {
      notification.error({
        message: 'Error',
        description: 'Failed to save note due to an error.',
      });
    }
  };

  useEffect(() => {
    if (notificationData) {
      const { type, message, description } = notificationData;
      notification[type]({
        message,
        description,
        duration: 5,
      });
      setNotificationData(null); // Clear notification data after showing
    }

    // Set top position for notifications
    notification.config({
      top: 80,
    });
  }, [notificationData]);

  return (
    <Container>
      <Label label="Add New Note" />
      <StyledTextArea
        name="description"
        placeholder="Enter your note here..."
        value={noteText}
        onChange={(e: any) => setNoteText(e.target.value)}
      />
      <SaveNoteContainer>
        <Button disabled={!noteText} onClick={saveNote}>
          SAVE NOTE
        </Button>
        <NoteType />
      </SaveNoteContainer>
    </Container>
  );
}

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
`;

const SaveNoteContainer = styled.div`
  display: inline-flex;
  gap: 10px;
  .disabled button {
    opacity: 0.5;
    cursor: default;
  }
`;

const StyledTextArea = styled.textarea`
  height: 57px;
  border-radius: 12px;
  background: #fff;
  resize: none;
  border-radius: 8px;
  border: 1px solid var(--Neutral-Gray-Gray-100, #e0e2e7);
  background: var(--Flowkit-White, #fff);
  padding: 8px 12px;
`;

// const StyledSelectDropdown = styled(SelectDropdown)`
//   border-color: #e0e2e7 !important;
//   width: 8vw;
//   margin-bottom: 5px;
// `;

export default AddNote;
