<script lang="ts">
  import { Button } from "$lib/components/ui/button";
  import { Input } from "$lib/components/ui/input";
  import { Slider } from "$lib/components/ui/slider";
  import { Combobox } from "$lib/components/ui/combobox";
  import CityAutocomplete from "$lib/components/CityAutocomplete.svelte";
  import {
    MapPin,
    Navigation,
    Globe,
    MapPinned,
    Loader2,
    Filter,
    ChevronDown,
    ChevronUp,
  } from "lucide-svelte";

  type Props = {
    // Mode selection
    mode?: "zone" | "address";

    // Zone mode
    countries?: any[];
    selectedCountry?: string;
    selectedRegion?: string;
    selectedDepartment?: string;
    availableRegions?: string[];
    availableDepartments?: string[];

    // Address mode
    searchAddress?: string;
    addressRadius?: number;
    userPosition?: { lat: number; lng: number } | null;

    // Filters (multiselect)
    selectedLocationTypes?: string[];
    selectedProviders?: string[];
    locationTypes?: any[];
    providers?: any[];

    // Callbacks
    onModeChange?: (mode: "zone" | "address") => void;
    onCountryChange?: (country: string) => void;
    onRegionChange?: (region: string) => void;
    onDepartmentChange?: (department: string) => void;
    onAddressChange?: (address: string) => void;
    onRadiusChange?: (radius: number) => void;
    onGeolocate?: () => void;
    onLocationTypesChange?: (types: string[]) => void;
    onProvidersChange?: (providers: string[]) => void;
  };

  let {
    mode = $bindable("zone"),
    countries = [],
    selectedCountry = $bindable(""),
    selectedRegion = $bindable(""),
    selectedDepartment = $bindable(""),
    availableRegions = [],
    availableDepartments = [],
    searchAddress = $bindable(""),
    addressRadius = $bindable(10),
    userPosition = $bindable(null),
    selectedLocationTypes = $bindable([]),
    selectedProviders = $bindable([]),
    locationTypes = [],
    providers = [],
    onModeChange,
    onCountryChange,
    onRegionChange,
    onDepartmentChange,
    onAddressChange,
    onRadiusChange,
    onGeolocate,
    onLocationTypesChange,
    onProvidersChange,
  }: Props = $props();

  let isGeolocating = $state(false);
  let showFilters = $state(false);

  // Get country info for dynamic labels
  let selectedCountryInfo = $derived(
    countries.find((c) => c.code === selectedCountry)
  );

  // Call onRadiusChange when addressRadius changes (real-time)
  // On utilise une variable pour tracker le changement réel
  let previousRadius = $state(addressRadius);
  $effect(() => {
    const currentRadius = addressRadius;
    if (currentRadius !== previousRadius) {
      previousRadius = currentRadius;
      if (onRadiusChange) onRadiusChange(currentRadius);
    }
  });

  function getCountryName(country: any): string {
    return country.name || country.code;
  }

  async function handleGeolocate() {
    if (!navigator.geolocation) {
      alert("La géolocalisation n'est pas supportée par votre navigateur");
      return;
    }

    isGeolocating = true;

    navigator.geolocation.getCurrentPosition(
      (position) => {
        userPosition = {
          lat: position.coords.latitude,
          lng: position.coords.longitude,
        };
        isGeolocating = false;
        if (onGeolocate) onGeolocate();
      },
      (error) => {
        console.error("Geolocation error:", error);
        alert("Impossible d'obtenir votre position");
        isGeolocating = false;
      }
    );
  }

  function toggleLocationType(type: string) {
    if (selectedLocationTypes.includes(type)) {
      selectedLocationTypes = selectedLocationTypes.filter((t) => t !== type);
    } else {
      selectedLocationTypes = [...selectedLocationTypes, type];
    }
    if (onLocationTypesChange) onLocationTypesChange(selectedLocationTypes);
  }

  function toggleProvider(provider: string) {
    if (selectedProviders.includes(provider)) {
      selectedProviders = selectedProviders.filter((p) => p !== provider);
    } else {
      selectedProviders = [...selectedProviders, provider];
    }
    if (onProvidersChange) onProvidersChange(selectedProviders);
  }
</script>

<div class="space-y-6">
  <!-- Zone Mode -->
  {#if mode === "zone"}
    <div class="grid grid-cols-3 gap-4">
      <!-- Country -->
      <div>
        <label class="block text-sm font-medium mb-1.5 flex items-center gap-2">
          <Globe class="h-4 w-4" />
          Pays <span class="text-destructive">*</span>
        </label>
        <Combobox
          items={countries.map((c) => ({
            value: c.code,
            label: `${c.flag_emoji || ""} ${getCountryName(c)}`,
          }))}
          bind:value={selectedCountry}
          placeholder="Choisir un pays"
          searchPlaceholder="Rechercher un pays..."
          emptyText="Aucun pays trouvé."
          class="w-full"
          onSelect={(value) => {
            if (onCountryChange) onCountryChange(value);
          }}
        />
      </div>

      <!-- Region -->
      <div>
        <span class="block text-sm font-medium mb-1.5">
          {selectedCountryInfo?.region_term || "Région"}
        </span>
        {#if selectedCountry && availableRegions.length > 0}
          <Combobox
            items={[
              {
                value: "",
                label: selectedCountryInfo?.region_term_plural
                  ? `Toutes les ${selectedCountryInfo.region_term_plural}`
                  : "Toutes",
              },
              ...availableRegions.map((r) => ({ value: r, label: r })),
            ]}
            bind:value={selectedRegion}
            placeholder={selectedCountryInfo?.region_term || "Région"}
            searchPlaceholder="Rechercher..."
            emptyText="Aucune région trouvée."
            class="w-full"
            onSelect={(value) => {
              if (onRegionChange) onRegionChange(value);
            }}
          />
        {:else}
          <div
            class="h-10 flex items-center text-sm text-muted-foreground border border-dashed rounded-md px-3"
          >
            Sélectionnez d'abord un pays
          </div>
        {/if}
      </div>

      <!-- Department -->
      <div>
        <span class="block text-sm font-medium mb-1.5">
          {selectedCountryInfo?.department_term || "Département"}
        </span>
        {#if selectedRegion && availableDepartments.length > 0}
          <Combobox
            items={[
              {
                value: "",
                label: selectedCountryInfo?.department_term_plural
                  ? `Tous les ${selectedCountryInfo.department_term_plural}`
                  : "Tous",
              },
              ...availableDepartments.map((d) => ({ value: d, label: d })),
            ]}
            bind:value={selectedDepartment}
            placeholder={selectedCountryInfo?.department_term || "Département"}
            searchPlaceholder="Rechercher..."
            emptyText="Aucun département trouvé."
            class="w-full"
            onSelect={(value) => {
              if (onDepartmentChange) onDepartmentChange(value);
            }}
          />
        {:else}
          <div
            class="h-10 flex items-center text-sm text-muted-foreground border border-dashed rounded-md px-3"
          >
            Sélectionnez d'abord une région
          </div>
        {/if}
      </div>
    </div>
  {:else}
    <!-- Address Mode -->
    <div class="space-y-4">
      <!-- Address Search and Geolocation -->
      <div class="grid grid-cols-3 gap-4">
        <div class="col-span-2 space-y-2">
          <label class="flex items-center gap-2 text-sm font-medium">
            <MapPin class="h-4 w-4" />
            Adresse <span class="text-destructive">*</span>
          </label>
          <CityAutocomplete
            bind:value={searchAddress}
            placeholder="Rechercher une adresse..."
            onSelect={(city) => {
              searchAddress = city.name;
              if (onAddressChange) onAddressChange(city.name);
            }}
          />
        </div>

        <div class="space-y-2">
          <label class="flex items-center gap-2 text-sm font-medium">
            <Navigation class="h-4 w-4" />
            Localisation
          </label>
          <Button
            variant="outline"
            class="w-full h-10 gap-2"
            onclick={handleGeolocate}
            disabled={isGeolocating}
          >
            {#if isGeolocating}
              <Loader2 class="h-4 w-4 animate-spin" />
            {:else if userPosition}
              <MapPinned class="h-4 w-4 text-green-600" />
            {:else}
              <Navigation class="h-4 w-4" />
            {/if}
            Me localiser
          </Button>
        </div>
      </div>

      <!-- Radius Slider -->
      <div class="space-y-3">
        <div class="flex items-center justify-between">
          <label class="flex items-center gap-2 text-sm font-medium">
            <MapPin class="h-4 w-4" />
            Rayon <span class="text-destructive">*</span>
          </label>
          <span class="text-sm font-semibold text-primary"
            >{addressRadius} km</span
          >
        </div>
        <Slider
          bind:value={addressRadius}
          min={1}
          max={600}
          step={5}
          class="w-full"
        />
        <div class="flex justify-between text-xs text-muted-foreground">
          <span>1 km</span>
          <span>200 km</span>
          <span>400 km</span>
          <span>600 km</span>
        </div>
      </div>
    </div>
  {/if}
</div>
