import { Input, Label } from '@bjsdistribution/dms-component-library';
import React from 'react';
import styled from 'styled-components';
import { errorAtom, useAtom, useOrderDetails } from '../../../../store';
import { handleKeyDown } from '../../../../utils';

function ContactWork() {
  const [errors, setErrors] = useAtom(errorAtom);
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const orderRecipient = orderDetails?.order_recipient;

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

    // Validate only if there is a value entered
    if (val) {
      if (val.length < 10) {
        setErrors(prevErrors => ({
          ...prevErrors,
          workCOntanctError: 'Phone number must be at least 10 digits.',
        }));
      } else if (val.length > 10) {
        setErrors(prevErrors => ({
          ...prevErrors,
          workCOntanctError: 'Phone number must not exceed 10 digits.',
        }));
      } else {
        setErrors(prevErrors => ({
          ...prevErrors,
          workCOntanctError: '',
        }));
      }
    } else {
      setErrors(prevErrors => ({
        ...prevErrors,
        workCOntanctError: '',
      }));
    }
  };

  return (
    <Container>
      <Wrapper>
        <Label label="Contact Work" htmlFor="contact-work" />
      </Wrapper>
      <InputContainer>
        <CustomInput
          name="contact-work"
          type="text"
          placeholder="Work Number"
          onKeyDown={handleKeyDown}
          value={orderRecipient?.contact_work || ''}
          onChange={onChange}
          minLength={10}
          maxLength={10}
        />
      </InputContainer>
      {errors.workCOntanctError && (
        <ErrorText>{errors.workCOntanctError}</ErrorText>
      )}
    </Container>
  );
}

const InputContainer = styled.div`
  display: flex;
  gap: 7px;
  align-items: center;
`;

const Wrapper = styled.div`
  display: flex;
  align-items: center;
  gap: 5px;
`;

const CustomInput = styled(Input)`
  width: 100%;

  &::-webkit-outer-spin-button,
  &::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  &:focus-visible {
    outline: none;
  }
`;

const Container = styled.div`
  display: flex;
  flex-direction: column;
  gap: 6px;
  flex: 1;
`;
const ErrorText = styled.span`
  color: red;
  font-size: 0.85rem;
  margin-top: 4px;
`;

export default ContactWork;
