import { Label, SelectDropdown } from '@bjsdistribution/dms-component-library';
import React from 'react';
import styled from 'styled-components';
import {
  usegetClientData,
  useOrderDetails,
  useStatusDetails,
} from '../../../store';
import { useClientPortal, useSubContracterData } from '../../../../store';

function Carrier() {
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [subContracterData] = useSubContracterData();
  const [orderStatus] = useStatusDetails();
  const [isClientPortal] = useClientPortal();
  const [clientData] = usegetClientData();

  const localClientData = JSON.parse(
    localStorage?.getItem('Client_iD') || '{}'
  );
  const clientId = Number(localClientData?.client_id);

  // Build options from subContracterData
  const carrierOptions =
    subContracterData?.map((carrier: any) => ({
      label: carrier?.name,
      value: carrier?.id,
    })) || [];

  // find the value which is selected
  const selectedCarrierOption = carrierOptions?.find(
    (option: any) => option?.value === orderDetails?.carrier_id
  );

  // get client name when no carrierid found
  const fallbackClientName = clientData?.find(
    (client: any) => Number(client?.client_id) === clientId
  )?.name;

  // fall if no carrierid
  const fallbackOption = fallbackClientName
    ? { label: fallbackClientName, value: '' }
    : null;

  const onChange = (selectedOption: any) => {
    setOrderDetails(prev => ({
      ...prev,
      carrier_id: selectedOption?.value,
    }));
  };

  return (
    <FormContainer>
      <Label label="Carrier" htmlFor="CarrierDropdown" />
      <SelectDropdown
        placeholder="Select Carrier"
        inputId="CarrierDropdown"
        openMenuOnFocus={false}
        value={selectedCarrierOption || fallbackOption || null}
        options={carrierOptions}
        onChange={onChange}
        isDisabled={
          isClientPortal
            ? true
            : orderStatus?.length > 0 && orderStatus[0]?.confirmed === true
        }
      />
    </FormContainer>
  );
}

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

export default Carrier;
