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

function What3words() {
  const w3wRegex = /^\/{0,}[^0-9`~!@#$%^&*()+\-_=[{\]}\\|'<,.>?/";:£§º©®\s]{1,}[・.。][^0-9`~!@#$%^&*()+\-_=[{\]}\\|'<,.>?/";:£§º©®\s]{1,}[・.。][^0-9`~!@#$%^&*()+\-_=[{\]}\\|'<,.>?/";:£§º©®\s]{1,}$/;
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const [errors, setErrors] = useAtom(errorAtom);
  const orderRecipient = orderDetails?.order_recipient;

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

  const validateInput = (value: string) => {
    if (value.trim()) {
      const isValid = w3wRegex.test(value);
      setErrors(prev => ({
        ...prev,
        w3wError: isValid ? '' : 'Please enter a valid input (word.word.word)',
      }));
    } else {
      setErrors(prev => ({
        ...prev,
        w3wError: '',
      }));
    }
  };

  return (
    <Container>
      <Label label="What3Words Address" htmlFor="w3w" />
      <Wrapper>
        <What3wordsPrefix>
          <What3WordsIcon />
        </What3wordsPrefix>
        <CustomInput
          name="w3w"
          type="text"
          placeholder="Format: word.word.word"
          value={orderRecipient?.what_3words_address || ''}
          onChange={onChange}
        />
      </Wrapper>
      {errors.w3wError && <ErrorText>{errors.w3wError}</ErrorText>}
    </Container>
  );
}
const What3wordsPrefix = styled.div`
  position: absolute;
  top: 13px;
  left: 12px;
`;

const Wrapper = styled.div`
  position: relative;
`;

const CustomInput = styled(Input)`
  border-radius: 25px;
  &::-webkit-outer-spin-button,
  &::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  &:focus-visible {
    outline: none;
  }
  padding-left: 40px;
`;

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