import { useState, useRef } from 'react';
import { Input, Button, App, Grid } from 'antd';
import type { InputRef } from 'antd';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import { useCanvassStore } from '@/stores/canvass.store';

interface Props {
  onFlyTo: (lat: number, lng: number) => void;
  style?: React.CSSProperties;
}

export default function AddressSearchOverlay({ onFlyTo, style }: Props) {
  const [expanded, setExpanded] = useState(false);
  const [searching, setSearching] = useState(false);
  const [query, setQuery] = useState('');
  const inputRef = useRef<InputRef>(null);
  const { message } = App.useApp();
  const { geocodeSearch } = useCanvassStore();
  const screens = Grid.useBreakpoint();
  const isMobile = !screens.md;

  const handleSearch = async () => {
    if (!query.trim()) return;
    setSearching(true);
    try {
      const result = await geocodeSearch(query.trim());
      onFlyTo(result.latitude, result.longitude);
      setExpanded(false);
      setQuery('');
    } catch {
      message.error('Address not found');
    } finally {
      setSearching(false);
    }
  };

  if (!expanded) {
    return (
      <button
        onClick={() => setExpanded(true)}
        title="Search address"
        style={{
          ...style,
          width: 40,
          height: 40,
          borderRadius: 8,
          border: '1px solid rgba(255,255,255,0.3)',
          background: 'rgba(0,0,0,0.6)',
          color: 'rgba(255,255,255,0.8)',
          cursor: 'pointer',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: 16,
          backdropFilter: 'blur(4px)',
        }}
      >
        <SearchOutlined />
      </button>
    );
  }

  return (
    <div
      style={{
        ...style,
        display: 'flex',
        gap: 4,
        background: 'rgba(0,0,0,0.75)',
        borderRadius: 8,
        padding: '4px 6px',
        backdropFilter: 'blur(8px)',
        border: '1px solid rgba(255,255,255,0.2)',
      }}
    >
      <Input
        ref={inputRef}
        placeholder="Search address..."
        value={query}
        onChange={(e) => setQuery(e.target.value)}
        onPressEnter={handleSearch}
        size="small"
        style={{
          width: isMobile ? '100%' : 200,
          maxWidth: isMobile ? '100%' : 200,
          background: 'rgba(255,255,255,0.1)',
          border: 'none',
          color: '#fff',
        }}
        autoFocus
      />
      <Button
        type="primary"
        size="small"
        icon={<SearchOutlined />}
        onClick={handleSearch}
        loading={searching}
      />
      <Button
        size="small"
        icon={<CloseOutlined />}
        onClick={() => { setExpanded(false); setQuery(''); }}
        style={{ background: 'rgba(255,255,255,0.1)', border: 'none', color: '#fff' }}
      />
    </div>
  );
}
