import React from 'react';
import styled from 'styled-components';
import { Input } from 'antd';
import {
  useErrorConfirmOrder,
  useOrderDetailsConfirmOrder,
} from '../../../../store';
import { handleKeyDown } from '../../../../utils';

function ContactMobile() {
  const [orderDetails, setOrderDetails] = useOrderDetailsConfirmOrder();
  const orderRecipient = orderDetails?.order_recipient;
  const [errors, setErrors] = useErrorConfirmOrder();

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const val = e.target.value;
    const updatedOrderRecipient = {
      ...(orderRecipient === null
        ? { contact_mobile: val }
        : { ...orderRecipient, contact_mobile: val }),
    };
    setOrderDetails(prev => {
      return {
        ...prev,
        order_recipient: updatedOrderRecipient,
      };
    });

    if (e.target.value) {
      if (e.target.value.length < 10) {
        setErrors(prevErrors => ({
          ...prevErrors,
          mobileError: 'Phone number must be at least 10 digits.',
        }));
      } else if (e.target.value.length > 11) {
        setErrors(prevErrors => ({
          ...prevErrors,
          mobileError: 'Phone number must not exceed 10 digits.',
        }));
      } else {
        setErrors(prevErrors => ({
          ...prevErrors,
          mobileError: '',
        }));
      }
    } else {
      setErrors(prevErrors => ({
        ...prevErrors,
        mobileError: '',
      }));
    }
  };
  return (
    <Container>
      <Label>Contact Mobile</Label>
      <Input
        name="contact-work"
        type="text"
        placeholder="Mobile Number"
        style={{ borderRadius: '15px' }}
        value={orderRecipient?.contact_mobile || ''}
        onKeyDown={handleKeyDown}
        onChange={onChange}
      />
      {errors.mobileError && <ErrorText>{errors.mobileError}</ErrorText>}
    </Container>
  );
}

const Label = styled.label`
  color: #6a7378;
  font-family: 'Lato', sans-serif;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
`;

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

const ErrorText = styled.span`
  color: red;
  font-size: 0.85rem;
  margin-top: 4px;
`;

export default ContactMobile;
