import React from 'react';
import { TextField, Button } from '../../../../components/UiComponents';
import { FaLocationArrow } from 'react-icons/fa';
import { IoMdSend } from 'react-icons/io';
import { usePekContext } from '../../../../contexts/PekContext';
import styles from './PekLocationInput.module.css';

import { useLanguage } from '../../../../providers/language/LanguageContext';

const PekLocationInput: React.FC = () => {
    const { t } = useLanguage();

  const {
    adresse,
    setAdresse,
    buildLocationString,
    useCurrentLocation,
    isGettingLocation,
    searchParcel,
    isSearchingParcel
  } = usePekContext();

  const handleSearch = async () => {
    const locationString = buildLocationString();
    if (locationString.trim()) {
      await searchParcel(locationString.trim(), true);
    }
  };

  const handleUseCurrentLocation = async () => {
    await useCurrentLocation();
  };

  return (
    <div className={styles.locationInputContainer}>
      <div className={styles.fieldsRow}>
        <div className={styles.fieldWrapper}>
          <TextField
            value={adresse}
            onChange={setAdresse}
            placeholder={t('z.B. Bundesplatz 3')}
            label={t('Adresse oder Parzelle')}
            disabled={isGettingLocation || isSearchingParcel}
            size="md"
            type="text"
            name="adresse"
            onKeyDown={(e) => {
              if (e.key === 'Enter') {
                e.preventDefault();
                handleSearch();
              }
            }}
          />
        </div>
        <div className={styles.buttonsWrapper}>
          <Button
            variant="primary"
            size="md"
            icon={IoMdSend}
            onClick={handleSearch}
            disabled={!buildLocationString().trim() || isGettingLocation || isSearchingParcel}
            loading={isSearchingParcel}
            className={styles.searchButton}
          >
            {t('Suchen')}
          </Button>
          <Button
            variant="secondary"
            size="md"
            icon={FaLocationArrow}
            onClick={handleUseCurrentLocation}
            disabled={isGettingLocation || isSearchingParcel}
            loading={isGettingLocation}
            className={styles.locationButton}
          >
            {t('Meine Position')}
          </Button>
        </div>
      </div>
    </div>
  );
};

export default PekLocationInput;
