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

function Latitude() {
  const [orderDetails, setOrderDetails] = useOrderDetails();
  const orderRecipient = orderDetails?.order_recipient;

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

  return (
    <Container>
      <Label label="Latitude" htmlFor="lat" />
      <CustomInput
        name="lat"
        type="number"
        placeholder="Latitude"
        onKeyDown={handleKeyDown}
        value={orderRecipient?.latitude || ''}
        onChange={onChange}
        readOnly
      />
    </Container>
  );
}

const CustomInput = styled(Input)`
  width: 100%;
  &::-webkit-outer-spin-button,
  &::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
  &:focus-visible {
    outline: none;
  }
  opacity: 0.8;
  background-color: #f4f4f4;
  pointer-events: none;
`;

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

export default Latitude;
