import React, { useState } from 'react';
import { useCurrentAction, useOrderDetails, useOrderId } from '../../../store';
import OrderActionModal from '../../../../../common/modals/order-action-modal/OrderActionModal';
import { ContentContainer, Label, StyledInput } from '../modalstyle';
import { TextArea, useAxios } from '@bjsdistribution/dms-component-library';
import { ApiResponse } from '../../../types';
import styled from 'styled-components';

const CustomTextArea = styled(TextArea)`
  width: 700px;
  height: 140px;
  resize: none;
`;

const ErrorText = styled.div`
  color: red;
  font-size: 12px;
  margin-top: 4px;
`;

function SendSmsModal() {
  const [, setCurrentAction] = useCurrentAction();
  const [orderDetails] = useOrderDetails();
  const [orderId] = useOrderId();
  const initialTo = orderDetails?.order_recipient?.contact_home || '';
  const [toError, setToError] = useState('');
  const [formData, setFormData] = useState({
    to: initialTo,
    body: '',
  });

  const { fetchData: callSendSms, loading } = useAxios<{ data: ApiResponse[] }>(
    {
      endpoint: `/v1/orders/send-sms/`,
      method: 'POST',
    }
  );

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target;

    if (name === 'to') {
      const digitsOnly = value.replace(/\D/g, '');
      let error = '';

      if (digitsOnly.length < 10) {
        error = 'Phone number must be exactly 10 digits';
      } else if (digitsOnly.length > 10) {
        error = 'Phone number cannot exceed 10 digits';
      }

      setToError(error);

      setFormData(prev => ({
        ...prev,
        to: digitsOnly.slice(0, 10),
      }));
    } else {
      setFormData(prev => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  const handleSubmit = async () => {
    const trimmedTo = formData?.to?.trim();
    const trimmedBody = formData?.body?.trim();

    if (trimmedTo.length !== 10) {
      setToError('Phone number must be exactly 10 digits');
      return;
    }

    const payload = {
      order_id: +orderId,
      receiver: trimmedTo,
      message: trimmedBody,
      notification_type: 'Send SMS',
    };

    if (!trimmedTo || !trimmedBody) {
      return;
    }

    try {
      await callSendSms({ payload: payload });
      closeModal();
    } catch (error) {
      console.error('Error sending SMS:', error);
    }
  };

  const closeModal = () => {
    setCurrentAction(undefined);
  };

  const isFormValid =
    formData?.to.trim()?.length === 10 &&
    !toError &&
    formData?.body.trim().length > 0;

  return (
    <OrderActionModal
      headerTitle="Send SMS"
      onCloseHeader={closeModal}
      onSubmit={handleSubmit}
      submitBtnTitle={loading ? 'Sending...' : 'Send SMS'}
      isSubmitDisabled={!isFormValid || loading}
    >
      <ContentContainer>
        <Label>To</Label>
        <StyledInput
          type="text"
          name="to"
          value={formData.to}
          onChange={handleInputChange}
          required
          placeholder="Enter the number"
          maxLength={10}
        />
        {toError && <ErrorText>{toError}</ErrorText>}

        <Label>Body</Label>
        <CustomTextArea
          name="body"
          value={formData.body}
          onChange={handleInputChange}
          required
          placeholder="Write here..."
        />
      </ContentContainer>
    </OrderActionModal>
  );
}

export default SendSmsModal;
