"use client"

import { MapPin } from "lucide-react"
import dynamic from "next/dynamic"
import { useState } from "react"

import { Button } from "@/src/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/src/components/ui/dialog"
import { Input } from "@/src/components/ui/input"

interface LocationData {
  lat: number
  lng: number
  address?: string
}

interface LocationInputProps {
  value?: LocationData | null
  onChange: (location: LocationData | null) => void
  placeholder?: string
  disabled?: boolean
  error?: boolean
}

const DynamicMapPicker = dynamic(
  () => import("./map-picker").then((mod) => mod.MapPicker),
  {
    ssr: false,
    loading: () => (
      <div className="h-64 w-full flex items-center justify-center bg-muted text-sm text-muted-foreground">
        Chargement de la carte...
      </div>
    ),
  },
)

export function LocationInput({
  value,
  onChange,
  placeholder = "Cliquez pour sélectionner un emplacement",
  disabled,
  error,
}: LocationInputProps) {
  const [isOpen, setIsOpen] = useState(false)

  const handleLocationSelect = (location: LocationData) => {
    onChange(location)
    setIsOpen(false)
  }

  const handleClear = (e: React.MouseEvent) => {
    e.stopPropagation()
    onChange(null)
  }

  return (
    <>
      <div className="relative">
        <Input
          readOnly
          value={value?.address ?? ""}
          placeholder={placeholder}
          disabled={disabled}
          aria-invalid={error}
          className="cursor-pointer pr-16"
          onClick={() => !disabled && setIsOpen(true)}
        />
        <div className="absolute right-2.5 top-1/2 -translate-y-1/2 flex items-center gap-1">
          {value && !disabled && (
            <Button
              type="button"
              variant="ghost"
              size="icon-xs"
              onClick={handleClear}
            >
              ×
            </Button>
          )}
          <MapPin className="size-4 text-muted-foreground" />
        </div>
      </div>

      <Dialog open={isOpen} onOpenChange={setIsOpen}>
        <DialogContent className="sm:max-w-[600px]">
          <DialogHeader>
            <DialogTitle>Sélectionner un emplacement</DialogTitle>
            <DialogDescription>
              Recherchez un lieu, collez un lien Google Maps, saisissez des coordonnées ou cliquez sur la carte.
            </DialogDescription>
          </DialogHeader>
          <div className="h-[420px] overflow-y-auto">
            <DynamicMapPicker
              onLocationSelect={handleLocationSelect}
              defaultLocation={value ?? undefined}
            />
          </div>
        </DialogContent>
      </Dialog>
    </>
  )
}
