import React, { useState } from 'react';
import { AntSelect, useAxios } from '@bjsdistribution/dms-component-library';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import { ContentContainer, Label, Row, SplitLayout } from '../modalstyle';
import {
  useCurrentAction,
  useCustomerData,
  useOrderDetails,
  useOrderId,
} from '../../../store';
import { Input, notification } from 'antd';
import { ApiResponse } from '../../../types';
interface IProps {
  callOrdersApi?: any;
}

function ChangeCustomerAccModal(props: IProps) {
  const [orderId] = useOrderId();
  const [customerData] = useCustomerData();
  const [, setCurrentAction] = useCurrentAction();
  const [orderDetails] = useOrderDetails();
  const [selectedCustomerId, setSelectedCustomerId] = useState<any>(
    orderDetails?.customer_id ?? null
  );
  const [tradingName, setTradingName] = useState<string>(
    orderDetails?.trading_name || ''
  );
  const orderRecipient = orderDetails?.order_recipient;
  const infoText = `${orderRecipient?.recipient_name}, ${orderRecipient?.postcode}`;
  const closeModal = () => setCurrentAction(undefined);

  const customerMappedData = customerData?.map((customer: any) => ({
    label: customer?.customer_name,
    value: customer?.id,
  }));

  const { fetchData } = useAxios<{
    data: ApiResponse[];
  }>({
    endpoint: `/orders/change_customer_account`,
    method: 'PUT',
  });

  const handleChangeAcc = async () => {
    if (selectedCustomerId == null || !tradingName?.trim()) {
      notification.warning({
        message: 'Validation Error',
        description: 'Please select a customer and enter a trading name.',
      });
      return;
    }

    try {
      const payload = [
        {
          order_id: +orderId,
          customer_id: +selectedCustomerId,
          trading_name: tradingName,
        },
      ];
      const response = (await fetchData({ payload })) as {
        code: number | null;
        error?: string | null | undefined;
        [key: string]: any;
      };

      if (response?.code === 200) {
        notification.success({
          message: 'Success',
          description: `${response.message}`,
        });
        await props?.callOrdersApi();
        closeModal();
      }
    } catch {
      notification.error({
        message: 'Error',
        description: 'Something went wrong while saving.',
      });
    }
  };

  const handleSelectChange = (value: string) => {
    setSelectedCustomerId(+value);
    const selected = customerMappedData?.find(c => c?.value === +value);
    if (selected) {
      setSelectedCustomerId(selected?.value);
    }
  };

  return (
    <OrderActionModal
      headerTitle="Change customer account"
      onCloseHeader={closeModal}
      onSubmit={handleChangeAcc}
      showAdditionalInfo
      infoText={infoText}
      submitBtnTitle="Save Details"
    >
      <ContentContainer>
        <SplitLayout>
          <Row>
            <Label>New Customer</Label>
            <AntSelect
              options={customerMappedData}
              placeholder="Select Customer"
              onChange={handleSelectChange}
              style={{ width: '22vw', height: 40 }}
              showSearch
              popupClassName="dropDownStyle"
              selectWrapperClass="rounded"
              defaultValue={selectedCustomerId}
            />
          </Row>

          <Row>
            <Label>New Trading Name</Label>
            <Input
              style={{ borderRadius: '15px', minWidth: '22vw' }}
              value={tradingName}
              onChange={e => setTradingName(e.target.value)}
            />
          </Row>
        </SplitLayout>
      </ContentContainer>
    </OrderActionModal>
  );
}

export default ChangeCustomerAccModal;
