import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { Check, ChevronsUpDown, MapPin } from 'lucide-react';
import { cn } from '@/client/lib/utils';
import { Button } from '@/client/components/ui/button';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/client/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/client/components/ui/popover';
import { locationClient } from '@/client/api';

interface Location {
  id: number;
  name: string;
  address: string;
  area: {
    id: number;
    name: string;
    code: string;
  };
  latitude?: number;
  longitude?: number;
}

interface LocationSelectProps {
  value?: number;
  onValueChange: (value: number | undefined) => void;
  placeholder?: string;
  disabled?: boolean;
  className?: string;
}

/**
 * 地点选择组件
 * 用于在表单中选择出发地或目的地
 */
export const LocationSelect = ({
  value,
  onValueChange,
  placeholder = "选择地点...",
  disabled = false,
  className,
}: LocationSelectProps) => {
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');

  // 获取地点列表
  const { data: locationsData, isLoading } = useQuery({
    queryKey: ['locations', 'select'],
    queryFn: () => locationClient.$get({
      query: {
        pageSize: 100,
        isDisabled: 0 // 只获取启用的地点
      }
    }),
  });

  const locations = locationsData?.data?.data || [];

  // 根据搜索关键词过滤地点
  const filteredLocations = locations.filter((location: Location) =>
    location.name.toLowerCase().includes(search.toLowerCase()) ||
    location.address.toLowerCase().includes(search.toLowerCase()) ||
    location.area.name.toLowerCase().includes(search.toLowerCase())
  );

  // 获取选中的地点
  const selectedLocation = locations.find((location: Location) => location.id === value);

  const handleSelect = (locationId: string) => {
    const id = locationId === "" ? undefined : parseInt(locationId);
    onValueChange(id);
    setOpen(false);
    setSearch('');
  };

  const handleClear = () => {
    onValueChange(undefined);
    setSearch('');
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          variant="outline"
          role="combobox"
          aria-expanded={open}
          className={cn(
            "w-full justify-between",
            !selectedLocation && "text-muted-foreground",
            className
          )}
          disabled={disabled}
        >
          {selectedLocation ? (
            <div className="flex items-center gap-2">
              <MapPin className="h-4 w-4" />
              <span className="truncate">
                {selectedLocation.name}
              </span>
              <span className="text-xs text-muted-foreground truncate">
                ({selectedLocation.area.name})
              </span>
            </div>
          ) : (
            <span>{placeholder}</span>
          )}
          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-full p-0" align="start">
        <Command>
          <CommandInput
            placeholder="搜索地点名称、地址或区域..."
            value={search}
            onValueChange={setSearch}
          />
          <CommandList>
            <CommandEmpty>
              {isLoading ? "加载中..." : "未找到匹配的地点"}
            </CommandEmpty>
            <CommandGroup>
              {filteredLocations.map((location: Location) => (
                <CommandItem
                  key={location.id}
                  value={location.id.toString()}
                  onSelect={handleSelect}
                  className="flex flex-col items-start py-3"
                >
                  <div className="flex items-center gap-2">
                    <Check
                      className={cn(
                        "h-4 w-4",
                        value === location.id ? "opacity-100" : "opacity-0"
                      )}
                    />
                    <span className="font-medium">{location.name}</span>
                    <span className="text-xs text-muted-foreground bg-muted px-2 py-1 rounded">
                      {location.area.name}
                    </span>
                  </div>
                  <div className="text-xs text-muted-foreground mt-1 ml-6">
                    {location.address}
                  </div>
                </CommandItem>
              ))}
            </CommandGroup>
            {search && filteredLocations.length > 0 && (
              <CommandGroup>
                <CommandItem
                  value=""
                  onSelect={handleClear}
                  className="text-center text-muted-foreground"
                >
                  清除选择
                </CommandItem>
              </CommandGroup>
            )}
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
};

/**
 * 地点选择组组件
 * 用于同时选择出发地和目的地
 */
interface LocationSelectGroupProps {
  startLocationId?: number;
  endLocationId?: number;
  onStartLocationChange: (value: number | undefined) => void;
  onEndLocationChange: (value: number | undefined) => void;
  disabled?: boolean;
}

export const LocationSelectGroup = ({
  startLocationId,
  endLocationId,
  onStartLocationChange,
  onEndLocationChange,
  disabled = false,
}: LocationSelectGroupProps) => {
  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      <div className="space-y-2">
        <label className="text-sm font-medium">出发地</label>
        <LocationSelect
          value={startLocationId}
          onValueChange={onStartLocationChange}
          placeholder="选择出发地..."
          disabled={disabled}
        />
      </div>
      <div className="space-y-2">
        <label className="text-sm font-medium">目的地</label>
        <LocationSelect
          value={endLocationId}
          onValueChange={onEndLocationChange}
          placeholder="选择目的地..."
          disabled={disabled}
        />
      </div>
    </div>
  );
};