import { atom, useAtom } from 'jotai';
import { atomWithReducer } from 'jotai/utils';
import {
  CancelOrderProductsType,
  CreateProduct,
  OrderActionsType,
  OrdersType,
  UnRecieveOrderProduct,
  UpdateOrderProduct,
} from './types';
import {
  ClientData,
  ClientType,
} from '../order-daily-overview/common/interface';
// OrderActionsType
const activeTabAtom = atom<string>('active');
const infoAtom = atom<boolean | undefined>(false);
const orderResources = atom<[]>([]);
const currentActionAtom = atom<OrderActionsType | undefined>(undefined);
const isOnHold = atom<Boolean>(false);
const date = atom(new Date());

const orderStaticDataAtom = atom<any>({});

interface OrderRecipient {
  recipient_name: string | null;
  postcode: string | null;
}

const customerInfoAtom = atom<OrderRecipient>({
  recipient_name: '',
  postcode: '',
});

export const ordersInitialValue: OrdersType = {
  depot_id: null,
  gsit_order_id: null,
  customer_id: null,
  trading_name: null,
  recipient_reference: null,
  order_locked: true,
  lock_notes: null,
  order_type_id: null,
  allow_live_tracking: null,
  weight: null,
  cube: null,
  rescheduled: null,
  zone_code: null,
  status: null,
  status_value: null,
  order_status_note: null,
  print_pod: null,
  order_number: null,
  consignment: null,
  action_date: null,
  other_instructions: null,
  schedule_after: null,
  vehicle_type: null,
  order_locked_by: null,
  delivery_instructions: null,
  drop_time: null,
  created_by: null,
  created_at: null,
  recipient_name: '',
  postcode: '',
  order_recipient: {
    id: null,
    order_id: null,
    recipient_name: null,
    address: null,
    postcode: null,
    postcode_district: null,
    postcode_short: null,
    latitude: null,
    longitude: null,
    what_3words_address: null,
    contact_home: null,
    contact_work: null,
    contact_mobile: null,
    contact_email: null,
    is_comms_enabled: null,
  },
  order_services_detail: {
    order_id: null,
    timed_service_id: null,
    order_delivery_point_id: null,
    order_service_level_id: null,
    heavy_order: null,
    heavy_item: null,
    bulky_order: null,
    bulky_item: null,
    id: null,
  },
  order_services: [
    {
      order_id: null,
      order_service_list_id: null,
      service_time: null,
      is_refused: null,
      service_note: null,
      id: null,
      service_category_id: 0,
    },
  ],
  order_routes: null,
  order_eta_updates: [],
  order_delivery_declined_dates: [],
  order_communications: [],
  id: null,
  name: '',
  carrier_id: null,
};

export const orderProductInitialvalue: CreateProduct = {
  code: '',
  description: '',
  sku: '',
  weight: 0,
  cube: 0,
  order_id: 0,
  order_product_type_id: 0,
  return_reason_id: 0,
  collection_reason_id: 0,
  product_return_action_id: 0,
  return_location: '',
};

export const unrecieveOrderProducts: UnRecieveOrderProduct = {
  unrecieve_reason_id: 0,
  unrecieve_note: '',
  // id: 0
};

export const updateOrderProducts: UpdateOrderProduct = {
  id: 0,
  order_id: 0,
  product_type_id: 0,
  product_return_action_id: 0,
  return_location: '',
  return_reason_id: 0,
};

export const usedate = () => {
  return useAtom(date);
};
function useTabType() {
  return useAtom(activeTabAtom);
}
function useInfoType() {
  return useAtom(infoAtom);
}
function useOrderResources() {
  return useAtom(orderResources);
}
function useCurrentAction() {
  return useAtom(currentActionAtom);
}

function useOrderStaticData() {
  return useAtom(orderStaticDataAtom);
}

export function useCustomerInfo() {
  return useAtom(customerInfoAtom);
}

// Define initial modal state
export const initialModalState = {
  openModalType: null,
};
function useIsOnHoldOrder() {
  return useAtom(isOnHold);
}
//value
const orderId = atom<any>(undefined);
export const useOrderId = () => {
  //dddddddddddd
  return useAtom(orderId);
};

const escalationIds = atom<number[]>([]);

function useEscalationIDs() {
  return useAtom(escalationIds);
}

const bulkUpdateSelectedRow = atom<any[]>([]);
export const useBulkUpdateSelectedRow = () => {
  return useAtom(bulkUpdateSelectedRow);
};

export const initialConfirmOrderErrValues = {
  homeContactError: '',
  workContactError: '',
  mobileError: '',
  emailError: '',
};

const errorConfirmOrderAtom = atom(initialConfirmOrderErrValues);

function useErrorConfirmOrder() {
  return useAtom(errorConfirmOrderAtom);
}

const OrderDetailsConfirmOrder = atom<OrdersType>(ordersInitialValue);
function useOrderDetailsConfirmOrder() {
  return useAtom(OrderDetailsConfirmOrder);
}

const selectedAction = atom<string>('');

export function useSelectionAction() {
  return useAtom(selectedAction);
}

// REFUSED SERVICES STATE STARTS

const confirmedDate = atom<{
  previousDate: string | null;
  currentDate: string | null;
}>({
  previousDate: null,
  currentDate: null,
});

export function useNotificationConfirmedDate() {
  return useAtom(confirmedDate);
}

const cancelOrderProducts = atom<CancelOrderProductsType[]>([]);
export function useCancelOrderProducts() {
  return useAtom(cancelOrderProducts);
}

// changes customer Account state
const customerData = atom<any[]>([]);
export const useCustomerData = () => {
  return useAtom(customerData);
};

const orderAlertsData = atom<any>({});
export function useOrderAlertsData() {
  return useAtom(orderAlertsData);
}

export {
  useTabType,
  useInfoType,
  useOrderResources,
  useCurrentAction,
  useIsOnHoldOrder,
  useOrderStaticData,
  useEscalationIDs,
  useErrorConfirmOrder,
  useOrderDetailsConfirmOrder,
};

// Remainder count
const OrderDetails = atom<OrdersType>(ordersInitialValue);
function useOrderDetails() {
  return useAtom(OrderDetails);
}

const prevOrderDetails = atom<OrdersType>(ordersInitialValue);
function usePrevOrderDetails() {
  return useAtom(prevOrderDetails);
}

const customerDetails = atom<any>({});
function useCustomerDetails() {
  return useAtom(customerDetails);
}

const DepotDeatils = atom<any>(0);
function useDepotDetails() {
  return useAtom(DepotDeatils);
}
const productDetails = atom<any>([]);
function useProductDetails() {
  return useAtom(productDetails);
}

const fetchAgain = atom<boolean>(false);
export function usefetchAgain() {
  return useAtom(fetchAgain);
}

const productDetailsCopy = atom<any>([]);
export function useProductDetailsCopy() {
  return useAtom(productDetailsCopy);
}

const StatusDeatils = atom<any>(0);
function useStatusDetails() {
  return useAtom(StatusDeatils);
}

const depotOptions = atom<any>([]);
function useDepotOptions() {
  return useAtom(depotOptions);
}

const depotEscData = atom<any>([]);
function useEscData() {
  return useAtom(depotEscData);
}
const deleteProdId = atom<any[]>([]);
function useDeleteProdsID() {
  return useAtom(deleteProdId);
}

const createOrderProduct = atom<any[]>([]);
function useCreateOrderProducts() {
  return useAtom(createOrderProduct);
}

const unrevieveOrderProduct = atom<UnRecieveOrderProduct>(
  unrecieveOrderProducts
);
function useRecieveOrderProducts() {
  return useAtom(unrevieveOrderProduct);
}

const updateOrderProduct = atom<UpdateOrderProduct>(updateOrderProducts);
function useUpdateOrderProducts() {
  return useAtom(updateOrderProduct);
}
const CallAPi = atom(false);

export function useCallAPi() {
  return useAtom(CallAPi);
}
// export const selectedProductIdAtom = atom<number | null>(null);

export const selectedProductActionTabKeyAtom = atom<string>(
  'update_product_type_tab'
);
function useSelectedProductActionTabKey() {
  return useAtom(selectedProductActionTabKeyAtom);
}

export const errorAtom = atom({
  homeContactError: '',
  workCOntanctError: '',
  mobileError: '',
  emailError: '',
  w3wError: '',
  postCodeError: '',
});

const orderProductResources = atom<any>([]);
function useOrderProductsResources() {
  return useAtom(orderProductResources);
}

const orderProductToolbox = atom<any>([]);
function useOrderProductsToolbox() {
  return useAtom(orderProductToolbox);
}

export const initialBulkReasonValues = {
  collection_reason_id: 0,
  return_reason_id: 0,
  product_return_action_id: 0,
  return_location: '',
};

const bulkReasonsAtom = atom<any>(initialBulkReasonValues);
export function useBulkReasons() {
  return useAtom(bulkReasonsAtom);
}

const bulkUpdatePayloadAtom = atom<any>([]);
export function useBulkUpdatePayload() {
  return useAtom(bulkUpdatePayloadAtom);
}

const singleProductTypeUpdateAtom = atom<any>({
  order_product_type_id: 0,
  order_product_type: '',
});
export function useSingleProductTypeUpdate() {
  return useAtom(singleProductTypeUpdateAtom);
}

const locationOptions = atom<any>([]);
export function useLocationOptions() {
  return useAtom(locationOptions);
}
const orderProductSystemLogs = atom<any>([]);
function useOrderProductSystemLogs() {
  return useAtom(orderProductSystemLogs);
}

const eventNotesData = atom<any>([]);
function useEventNotesData() {
  return useAtom(eventNotesData);
}

const selectedProductIdAtom = atom<number | undefined>(undefined);
function useSelectedProductId() {
  return useAtom(selectedProductIdAtom);
}
const returnAfterOrderAtom = atom<any[]>([]);

export function useReturnAfterOrderData() {
  return useAtom(returnAfterOrderAtom);
}

const clientDataAtom = atom<ClientData[]>([]);
function useClientData() {
  return useAtom(clientDataAtom);
}

const clientData = atom<ClientType[]>([]);

export function usegetClientData() {
  return useAtom(clientData);
}

const internalSearch = atom<string>('');

function useInternalSearchText() {
  return useAtom(internalSearch);
}

export {
  useAtom,
  useOrderDetails,
  useCustomerDetails,
  useProductDetails,
  useDepotDetails,
  useStatusDetails,
  useDepotOptions,
  usePrevOrderDetails,
  useEscData,
  useDeleteProdsID,
  useCreateOrderProducts,
  useRecieveOrderProducts,
  useUpdateOrderProducts,
  useOrderProductsResources,
  useOrderProductsToolbox,
  useOrderProductSystemLogs,
  useEventNotesData,
  useSelectedProductId,
  useSelectedProductActionTabKey,
  useClientData,
  useInternalSearchText,
};

const notes = atom<any>([]);

export function usegetNotes() {
  return useAtom(notes);
}

const moduleIds = atom<{
  id?: string;
  parentId?: string;
} | null>(null);

export function usemoduleIds() {
  return useAtom(moduleIds);
}

const callAPi = atom(false);

export function useLogsCallAPi() {
  return useAtom(callAPi);
}

const callOrderProductsApi = atom<boolean>(false);

export function usecallOrderProductsApi() {
  return useAtom(callOrderProductsApi);
}

const selectedProductId = atom<any>([]);

export function useSelectUpdateOP() {
  return useAtom(selectedProductId);
}

const gsitCUstomerId = atom<any>({});

export function useGsitCUstomerId() {
  return useAtom(gsitCUstomerId);
}

const CUstomerId = atom<number | undefined>(undefined);

export function useCUstomerId() {
  return useAtom(CUstomerId);
}

const RouteId = atom<any | null>(null);

export function useRouteId() {
  return useAtom(RouteId);
}

const gsitOrderId = atom<number | undefined>(undefined);

export function useGsitOrderId() {
  return useAtom(gsitOrderId);
}

const orderProductId = atom<number | undefined>(undefined);

export function useOrderProductId() {
  return useAtom(orderProductId);
}
const returnDataAtom = atom<any[]>([]);
export function useReturnData() {
  return useAtom(returnDataAtom);
}
const apiUpdateCalling = atom<boolean>(false);

export function useUpdateApiCall() {
  return useAtom(apiUpdateCalling);
}

const liveRecalling = atom<boolean>(false);

//re api call of live status
export function useLiveRecalling() {
  return useAtom(liveRecalling);
}

//delete products
const onDeleteProduct = atom<boolean>(false);

export function useDeleteRecall() {
  return useAtom(onDeleteProduct);
}

export const selectedTabKeyAtom = atom<string>('1');
export const letselectedProductIdAtom = atom<number | null>(null);

// const BulkUPdateDisabledState = atom<boolean>(false);
// export const useBulkUPdateDisabledState = () => {
//   return useAtom(BulkUPdateDisabledState);
// };

const auditLogLoadingState = atom<boolean>(true);
export function useAuditLogLoadingState() {
  return useAtom(auditLogLoadingState);
}

const globalStateHitAuditLog = atom<boolean>(false);
export function useGlobalStateHitAuditLog() {
  return useAtom(globalStateHitAuditLog);
}

const globalOrderGetApi = atom<boolean>(true);

export function useGlobalStateHitOrder() {
  return useAtom(globalOrderGetApi);
}

// Popup state Manage
const initialState = null;

const popupReducer = (state: any, action: any) => {
  if (action.type === 'create-return') {
    state = 'create-return';
    return { state };
  }
  if (action.type === 'bulkUpdate') {
    state = 'bulkUpdate';
    return { state };
  } else if (action.type === 'addProduct') {
    state = 'addProduct';
    return { state };
  } else if (action.type === 'split-order') {
    state = 'split-order';
    return { state };
  } else if (action.type === 'deleteProduct') {
    state = 'deleteProduct';
    return { state };
  } else if (action.type === 'defectsModal') {
    state = 'defectsModal';
    return { state };
  } else if (action.type === 'repackModal') {
    state = 'repackModal';
    return { state };
  } else if (action.type === 'qclog') {
    state = 'qclog';
    return { state };
  } else if (action.type === 'qclogtable') {
    state = 'qclogtable';
    return { state };
  } else if (action.type === 'repack') {
    state = 'repack';
    return { state };
  } else if (action.type === 'close') {
    state = null;
    return { state };
  } else {
    throw new Error('unknown action type');
  }
};
export const countReducerAtom = atomWithReducer(initialState, popupReducer);
