import {
  SectionHeader,
  useAxios,
} from '@bjsdistribution/dms-component-library';
import React, { useEffect, useState } from 'react';
import Tabs from './Tabs';
import styled from 'styled-components';
import {
  useInfoType,
  useOrderAlertsData,
  useOrderDetails,
  useOrderId,
  useRouteId,
  useTabType,
} from '../store';
import NotifyFlag from '../../../assets/icons/NotifyFlag';
import {
  useTasksData,
  useOrderNotify,
  useReminderNotiData,
  useRouteDetails,
  useAllOrderStatus,
} from '../order-actions/store';
import { useParams, useSearchParams } from 'react-router-dom';

interface ApiResponse {
  message: string;
  code: number;
  error: string | null;
  error_traceback: string | null;
  data: [];
  setShouldPerformAction: boolean;
}

function Notification() {
  const [activeTab, setActiveTab] = useTabType();
  const [, setShowMoreInfo] = useInfoType();
  const [orderData] = useOrderDetails();
  const [taskData, setTasksData] = useTasksData();
  const [reminderNotifyData, setReminderNotifyData] = useReminderNotiData();
  const [, setRouteData] = useRouteDetails();
  const [, setCount] = useOrderNotify();
  const [activeReminders, setActiveReminders] = useState([]);
  const [closedReminders, setCloseReminders] = useState([]);
  const [activeTasks, setActiveTasks] = useState([]);
  const [closedTasks, setCloseTasks] = useState([]);
  const [idOfRoute, setRouteId] = useRouteId();
  const [, setStatusVal] = useAllOrderStatus();
  const [searchParams] = useSearchParams();
  const [orderAlertsData, setOrderAlertsData] = useOrderAlertsData();
  const orderIdParams = searchParams.get('order');
  const { id } = useParams();
  const [orderId, setOrderId] = useOrderId();
  const routeId = orderData?.order_routes?.route_id;

  useEffect(() => {
    if (orderIdParams) {
      setOrderId(id);
    } else {
      const paths = location.pathname.split('/');
      setOrderId(paths[paths?.length - 1]);
    }
  }, []);

  //Unresolved API
  const {
    data: fetchedUnresolvedData,
    loading: unresolvedLoading,
    fetchData: callUnresolvedTaskApi,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/`,
    method: 'GET',
    pagination: { is_pagination: false },
    filters: [{ field: 'order_id', op: '=', value: orderId }],
  });

  //reminder get
  const {
    data: fetchedReminderData,
    loading: reminderLoading,
    fetchData: callReminderApi,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/v1/task/reminder/get/`,
    method: 'GET',
    pagination: { is_pagination: false },
    filters: [{ field: 'order_id', op: '=', value: orderId }],
  });

  useEffect(() => {
    setStatusVal(orderData?.status_value);
  }, [orderData?.status_value]);

  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    //additionally set count
    setCount(1);
    setShowMoreInfo(false);
  };
  //flags data set
  useEffect(() => {
    if (fetchedUnresolvedData && fetchedUnresolvedData?.data) {
      setTasksData(fetchedUnresolvedData?.data);
    }
  }, [unresolvedLoading, fetchedUnresolvedData]);

  //reminder data set
  useEffect(() => {
    if (fetchedReminderData && fetchedReminderData?.data) {
      setReminderNotifyData(fetchedReminderData?.data);
    }
  }, [reminderLoading]);

  // Route API calling...
  const { data: fetchedData, fetchData: fetchRoute } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `route/${routeId}`,
    method: 'GET',
  });

  useEffect(() => {
    if (idOfRoute !== null && idOfRoute !== undefined) {
      fetchRoute();
    }
    return () => {
      setRouteId(null);
    };
  }, [idOfRoute]);

  const {
    data: alertsData,
    fetchData: callOrderAlertsApi,
    loading: alertsApiLoading,
  } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `v1/orders/alerts/?order_id=${orderId}`,
    method: 'GET',
  });

  useEffect(() => {
    if (alertsData && alertsData?.data) {
      setOrderAlertsData(alertsData?.data);
    }
  }, [alertsApiLoading]);

  useEffect(() => {
    const fetchData = async () => {
      if (orderId == null) return;

      try {
        await callReminderApi();
        await callUnresolvedTaskApi();
        await callOrderAlertsApi();
      } catch (error) {
        console.error('Error while fetching order-related data:', error);
      }
    };

    fetchData();
  }, [orderId]);

  useEffect(() => {
    if (fetchedData && fetchedData?.data) {
      const data = fetchedData?.data[0];
      setRouteData(data);
    }
  }, []);

  useEffect(() => {
    if (taskData?.length > 0) {
      setActiveTasks(taskData?.filter((item: any) => item.status !== 'SD'));
      setCloseTasks(taskData?.filter((item: any) => item?.status === 'SD'));
    }
  }, [taskData, fetchedUnresolvedData]);

  useEffect(() => {
    if (reminderNotifyData?.length > 0) {
      setActiveReminders(
        reminderNotifyData?.filter((item: any) => item.status === false)
      );
      setCloseReminders(
        reminderNotifyData?.filter((item: any) => item?.status === true)
      );
    }
  }, [reminderNotifyData]);

  //dismiss notifcations
  const dismissFlags = (id: any) => {
    setActiveTasks(prevFlags => {
      const updatedFlags = prevFlags?.filter((flags: any) => flags.id !== id);
      return updatedFlags;
    });

    setCloseTasks(prevFlags => {
      const updatedFlags = prevFlags?.filter((flags: any) => flags.id !== id);
      return updatedFlags;
    });
  };

  const dismissReminder = (id: any) => {
    setActiveReminders(prevReminders =>
      prevReminders?.filter((reminder: any) => reminder.id !== id)
    );
    setCloseReminders(prevReminders =>
      prevReminders?.filter((reminder: any) => reminder.id !== id)
    );
  };

  const totalActiveCount =
    activeTasks?.filter((item: any) => item.status !== 'SD')?.length +
    activeReminders?.length;
  // orderCount;

  const totalClosedCount =
    closedTasks?.filter((item: any) => item.status === 'SD')?.length +
    closedReminders?.length;

  return (
    <>
      <Section>
        <Container className="notification-header">
          <FlagContainer>
            <NotifyFlag />
          </FlagContainer>
          <Label label="NOTIFICATIONS" />
          <TabsData className="tab-buttons">
            <StyledTab
              active={activeTab === 'active'}
              onClick={() => handleTabChange('active')}
            >
              Active
              <ActiveCount>{totalActiveCount}</ActiveCount>
            </StyledTab>
            <StyledTab
              active={activeTab === 'closed'}
              onClick={() => handleTabChange('closed')}
            >
              Closed
              <ClosedCount>{totalClosedCount}</ClosedCount>
            </StyledTab>
          </TabsData>
        </Container>
        {unresolvedLoading || reminderLoading ? (
          <Loader>
            <Spinner />
            <Text>Fetching Notifications...</Text>
          </Loader>
        ) : taskData?.length > 0 ||
          reminderNotifyData?.length > 0 ||
          orderData ? (
          <TabsWrapper>
            <Tabs
              activeTasks={activeTasks}
              closedTasks={closedTasks}
              activeReminders={activeReminders}
              closedReminders={closedReminders}
              dismissReminder={dismissReminder}
              dismissFlags={dismissFlags}
              routeInfoData={orderAlertsData}
            />
          </TabsWrapper>
        ) : (
          'No Notifications Found'
        )}
      </Section>
    </>
  );
}

const Container = styled.div`
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px;
  border-bottom: 1px solid #ccc;
`;

const Loader = styled.div`
  align-items: center;
  justify-content: center;
  display: flex;
  flex-direction: column;
  gap: 10px;
`;

const Spinner = styled.div`
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-left-color: #3a3630;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
`;

const FlagContainer = styled.div`
  padding: 8px;
  background-color: #3a3630;
  border-radius: 10px;
`;

const TabsData = styled.div`
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 10px;
`;

const ActiveCount = styled.div`
  color: #ffffff;
  padding: 1px 5px;
  background-color: #6396e5;
  border-radius: 6px;
`;

const ClosedCount = styled.div`
  color: #ffffff;
  padding: 1px 5px;
  background-color: #e95252;
  border-radius: 6px;
`;

const StyledTab = styled.div<{ active: boolean }>`
  display: flex;
  gap: 5px;
  cursor: pointer;
  color: ${props => (props.active ? '#3a3630' : '#AEA9A1')};
  border-bottom: ${props =>
    props.active ? '2px solid #feba30' : '2px solid #eeeeee'};
  transition: border-bottom 0.3s ease;
  font-family: 'Roboto', sans-serif;
  padding-bottom: 5px;
  align-items: center;
`;

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

const Label = styled(SectionHeader)`
  border-bottom: 1px solid #ccc;
  font-family: 'Roboto', sans-serif;
  font-size: 16px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px; /* 150% */
  text-transform: uppercase;
`;

const TabsWrapper = styled.div`
  /* min-height: 200px; */
  max-height: 350px;
  overflow-y: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &:hover {
    scrollbar-width: thin;
  }

  &::-webkit-scrollbar {
    width: 0;
  }

  &:hover::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(0, 0, 0, 0.5);
  }
`;

const Text = styled.div`
  color: var(--tonal-brown-651, #6a7378);
  font-family: Lato;
  font-size: 13px;
  font-style: normal;
  font-weight: 600;
`;
export default Notification;
