import React, { useEffect } from 'react';
import styled from 'styled-components';
import AddNote from './AddNote';
import AuditLogs from './logs';
import { useApiHook } from '@bjsdistribution/dms-component-library';
import {
  useAuditLogLoadingState,
  // useCallAPi,
  usegetNotes,
  useGlobalStateHitAuditLog,
  usemoduleIds,
  useOrderId,
} from '../store';
// import { useLocation } from 'react-router-dom';
function Notes() {
  const [moduleIds, setModuleIds] = usemoduleIds();
  const [orderId] = useOrderId();
  const [, setNotes] = usegetNotes();
  const [, setAuditLogLoading] = useAuditLogLoadingState();
  const [recallAuditLog, setAuditLogs] = useGlobalStateHitAuditLog();

  // Fetch module IDs
  const { data: fetchedData, loading: apiLoading } = useApiHook<{ data: any }>({
    endpoint: 'audit_logs/modules/',
    method: 'GET',
  });

  useEffect(() => {
    if (!apiLoading && fetchedData?.data) {
      const modules =
        fetchedData?.data
          .filter((item: any) => item?.name === 'ORDER')
          .flatMap((item: any) =>
            item?.static_child_mappings
              ?.filter(
                (child: any) => child?.child_module?.name === 'ORDER-NOTE'
              )
              .map((child: any) => ({
                id: child?.child_module?.id,
                parentId: child?.parent_module?.id,
              }))
          ) || [];

      setModuleIds(modules[0] || null);
    }
  }, [apiLoading, fetchedData]);

  // Fetch Notes Data
  const {
    data: NotesData,
    loading: NotesLoading,
    setShouldPerformAction,
  } = useApiHook<{ data: any }>({
    endpoint: `audit_logs/?module_id=${moduleIds?.parentId}&module_object_id=${orderId}`,
    method: 'GET',
    performAction: false,
  });

  useEffect(() => {
    if (moduleIds && orderId) {
      setShouldPerformAction(true);
    }
    if (!NotesLoading && NotesData?.data) {
      const updatedData = NotesData?.data
        .filter(
          (item: any) =>
            item['ORDER-NOTE'] || item['ORDER'] || item['ORDER-RETURN']
        )
        .map((item: any) => [
          item['ORDER-NOTE'],
          item['ORDER'],
          item['ORDER-RETURN'],
        ])
        .flat()
        .filter(Boolean);

      const combinedArray = updatedData?.flat();
      combinedArray.sort(
        (a: any, b: any) =>
          new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
      );
      setNotes(combinedArray);
      recallAuditLog
        ? setShouldPerformAction(true)
        : setShouldPerformAction(false);
    }
    setAuditLogLoading(NotesLoading);
  }, [moduleIds, orderId, NotesLoading, recallAuditLog]);

  const handleGetLogs = () => {
    setAuditLogs(true);
    setTimeout(() => {
      setAuditLogs(false);
    }, 1000);
  };

  return (
    <Container>
      <CardHeader>
        NOTES
        <SmallButton onClick={handleGetLogs}>UPDATE LOGS</SmallButton>
      </CardHeader>
      <CustomizedFormSection>
        <AddNote />
        <AuditLogs />
      </CustomizedFormSection>
    </Container>
  );
}

const Container = styled.div`
  border-radius: 5px;
`;

const CardHeader = styled.div`
  border: 1px solid #f0f2f2;
  background-color: #f8fafc;
  color: #3a3630;
  font-size: 16px;
  padding: 10px;
  border-bottom: 1px solid #ddd;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  text-transform: uppercase;
  font-family: 'Roboto', sans-serif;
  font-weight: 600;
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const CustomizedFormSection = styled.div`
  display: flex;
  background: #ffffff;
  padding: 10px;
  flex-direction: column;
  gap: 14px;
  border: 1px solid #f0f2f2;
  border-bottom-right-radius: 8px;
  border-bottom-left-radius: 8px;
  box-shadow: 0px 4px 30px 0px rgba(46, 45, 116, 0.05);
`;

const SmallButton = styled.button`
  background-color: #363a30;
  color: #ffffff;
  font-size: 12px;
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;

  &:hover {
    background-color: #feba30;
  }
`;
export default Notes;
