import {
  formatUtcToLocal,
  useApiHook,
} from '@bjsdistribution/dms-component-library';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useOrderId } from '../../../../store';
import {
  EmptyDataContainer,
  StyledTable,
  StyledTableWrapper,
} from './ReminderStyles';
import CustomScrollBar from '../../../../../../common/scrollbar';
import { Empty, Skeleton } from 'antd';

function NotesTable() {
  const [moduleIds, setModuleIds] = useState<{
    id?: string;
    child_id?: string;
  } | null>(null);
  const [orderId] = useOrderId();
  const [notes, setNotes] = useState<any>();
  const [loading, setNoteLoadingStore] = useState(false);

  // Fetch module IDs
  const { data: fetchedData, loading: apiLoading } = useApiHook<{ data: any }>({
    endpoint: 'audit_logs/modules/',
    method: 'GET',
    pagination: { page: 1, per_page: 100 },
  });
  useEffect(() => {
    if (!apiLoading && fetchedData?.data) {
      const modules = fetchedData?.data
        ?.filter((item: any) => item?.name === 'ORDER')
        ?.map((item: any) => {
          const orderProductId = item?.static_child_mappings.find(
            (i: any) => i?.child_module?.name === 'ORDER-PRODUCT'
          )?.child_module?.id;

          return {
            id: item?.id,
            child_id: orderProductId || null,
          };
        });
      setModuleIds(modules[0] || null);
    }
  }, [apiLoading, fetchedData]);

  // Fetch Notes Data
  const {
    data: NotesData,
    loading: NotesLoading,
    setShouldPerformAction,
  } = useApiHook<{ data: any }>({
    endpoint: `audit_logs/?module_id=${moduleIds?.id}&module_object_id=${orderId}`,
    method: 'GET',
    performAction: false,
  });
  useEffect(() => {
    setNoteLoadingStore(true);
    if (moduleIds) {
      setShouldPerformAction(true);
    }
    if (!NotesLoading && NotesData?.data) {
      const OrdersData = NotesData?.data[0]?.ORDER || [];
      const OrderNotesData = NotesData?.data[1]?.['ORDER-PRODUCT'] || [];
      const allNotes = [...OrdersData, ...OrderNotesData];
      setNotes(allNotes);
      setNoteLoadingStore(NotesLoading);
    }
  }, [moduleIds, NotesLoading]);

  if (notes?.length === 0) {
    return null;
  }

  return (
    <Container>
      <Title>Notes ({notes?.length})</Title>
      <StyledTableWrapper>
        <CustomScrollBar>
          <StyledTable className="scrollClass">
            <thead>
              <tr>
                <th>Created</th>
                <th>Notes</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr>
                  <td colSpan={6}>
                    <Skeleton active />
                  </td>
                  <td colSpan={6}></td>
                </tr>
              ) : notes?.length === 0 ? (
                <tr>
                  <td className="emptyTd" colSpan={7}>
                    <EmptyDataContainer>
                      <Empty />
                    </EmptyDataContainer>
                  </td>
                </tr>
              ) : (
                notes?.map((order: any) => (
                  <tr key={order.id}>
                    <td>
                      <div
                        style={{
                          fontWeight: 'bold',
                          textTransform: 'capitalize',
                        }}
                      >
                        {order?.created_by}
                      </div>
                      <div>
                        {/* {format(
                          new Date(order?.created_at),
                          "dd/MM/yyyy '@' HH:mm"
                        )} */}
                        {`${formatUtcToLocal(order?.created_at).date} @ ${
                          formatUtcToLocal(order?.created_at).time
                        }`}
                      </div>
                    </td>
                    <td
                      dangerouslySetInnerHTML={{ __html: order?.description }}
                    ></td>
                  </tr>
                ))
              )}
            </tbody>
          </StyledTable>
        </CustomScrollBar>
      </StyledTableWrapper>
    </Container>
  );
}

const Title = styled.h2`
  color: #3a3630;
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  font-style: normal;
  font-weight: 500;
  text-transform: uppercase;
  padding: 0;
  margin: 0;
`;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 8px;
  > div {
    min-height: 350px;
  }
`;

export default NotesTable;
