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

function ContactEmail() {
  const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [errors, setErrors] = useAtom(errorAtom);
  const orderRecipient = orderDetails?.order_recipient;

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

  const validateInput = (value: string) => {
    const isValid = emailRegex.test(value);
    setErrors(prev => ({
      ...prev,
      emailError: value && !isValid ? 'Please enter a valid Email Address' : '',
    }));
  };

  return (
    <Container>
      <Wrapper>
        <Label label="Email" htmlFor="email-id" />
      </Wrapper>
      <Input
        name="email-id"
        type="email"
        placeholder="Email"
        value={orderRecipient?.contact_email || ''}
        onChange={onChange}
      />
      {errors.emailError && <ErrorText>{errors.emailError}</ErrorText>}
    </Container>
  );
}

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

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 ContactEmail;
