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

function EmailAddress() {
  const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;

  const [orderDetails, setOrderDetails] = useOrderDetailsConfirmOrder();

  const orderRecipient = orderDetails?.order_recipient;
  const [errors, setErrors] = useErrorConfirmOrder();

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

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

  return (
    <Container>
      <Label>Email Address</Label>
      <Input
        style={{ borderRadius: '15px' }}
        type="text"
        value={orderRecipient?.contact_email || ''}
        onChange={onChange}
      />
      {errors.emailError && <ErrorText>{errors.emailError}</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 EmailAddress;
