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

const PekLocationInput: React.FC = () => {
  const {
    kanton: _kanton,
    setKanton: _setKanton,
    gemeinde: _gemeinde,
    setGemeinde: _setGemeinde,
    adresse,
    setAdresse,
    buildLocationString,
    useCurrentLocation,
    isGettingLocation,
    locationError: _locationError,
    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="z.B. Bundesplatz 3"
            label="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}
          >
            Suchen
          </Button>
          <Button
            variant="secondary"
            size="md"
            icon={FaLocationArrow}
            onClick={handleUseCurrentLocation}
            disabled={isGettingLocation || isSearchingParcel}
            loading={isGettingLocation}
            className={styles.locationButton}
          >
            Meine Position
          </Button>
        </div>
      </div>
    </div>
  );
};

export default PekLocationInput;

