"use client";

import React, { useState } from "react";
import { useFormContext, Controller } from "react-hook-form";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { X, MapPin, ChevronDown, Plus } from "lucide-react";
import { cn } from "@/lib/utils";

interface LocalityOption {
  value: string;
  label: string; // e.g., "Gota"
  city: string; // e.g., "Ahmedabad"
  state: string; // e.g., "Gujarat"
}

// Mock data - replace with actual data from your backend/constants
const mockLocalities: LocalityOption[] = [
  { value: "gota-ahmedabad-gujarat", label: "Gota", city: "Ahmedabad", state: "Gujarat" },
  { value: "navrangpura-ahmedabad-gujarat", label: "Navrangpura", city: "Ahmedabad", state: "Gujarat" },
  { value: "satellite-ahmedabad-gujarat", label: "Satellite", city: "Ahmedabad", state: "Gujarat" },
  { value: "bopal-ahmedabad-gujarat", label: "Bopal", city: "Ahmedabad", state: "Gujarat" },
  { value: "prahlad-nagar-ahmedabad-gujarat", label: "Prahlad Nagar", city: "Ahmedabad", state: "Gujarat" },
  { value: "thaltej-ahmedabad-gujarat", label: "Thaltej", city: "Ahmedabad", state: "Gujarat" },
  { value: "sg-highway-ahmedabad-gujarat", label: "S.G. Highway", city: "Ahmedabad", state: "Gujarat" },
  { value: "maninagar-ahmedabad-gujarat", label: "Maninagar", city: "Ahmedabad", state: "Gujarat" },
];

interface LocalitySearchSelectProps {
  name: string;
  label?: string;
  required?: boolean;
  description?: string;
}

export const LocalitySearchSelect: React.FC<LocalitySearchSelectProps> = ({
  name,
  label = "Preferred Localities",
  required = false,
  description,
}) => {
  const { control } = useFormContext();
  const [open, setOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [showGooglePlacesInput, setShowGooglePlacesInput] = useState(false);
  const [googlePlacesSearch, setGooglePlacesSearch] = useState("");

  const filteredLocalities = mockLocalities.filter((locality) => {
    const searchLower = searchTerm.toLowerCase();
    return (
      locality.label.toLowerCase().includes(searchLower) ||
      locality.city.toLowerCase().includes(searchLower) ||
      locality.state.toLowerCase().includes(searchLower)
    );
  });

  const handleAddNewLocality = () => {
    setShowGooglePlacesInput(true);
    setOpen(false);
  };

  const handleGooglePlacesSearch = () => {
    // TODO: Integrate with Google Places API
    console.log("Searching Google Places for:", googlePlacesSearch);
    // After successful addition, reset and close
    setGooglePlacesSearch("");
    setShowGooglePlacesInput(false);
  };

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState }) => {
        const selectedValues: string[] = field.value || [];

        const toggleLocality = (value: string) => {
          const newValues = selectedValues.includes(value)
            ? selectedValues.filter((v) => v !== value)
            : [...selectedValues, value];
          field.onChange(newValues);
        };

        const removeLocality = (value: string) => {
          field.onChange(selectedValues.filter((v) => v !== value));
        };

        const getLocalityLabel = (value: string) => {
          const locality = mockLocalities.find((l) => l.value === value);
          return locality?.label || value;
        };

        return (
          <div className="space-y-2">
            <Label htmlFor={name}>
              {label}
              {required && <span className="text-destructive ml-1">*</span>}
            </Label>

            {/* Selected Tags */}
            {selectedValues.length > 0 && (
              <div className="flex flex-wrap gap-2 mb-2">
                {selectedValues.map((value) => (
                  <Badge
                    key={value}
                    variant="secondary"
                    className="px-2 py-1 flex items-center gap-1"
                  >
                    {getLocalityLabel(value)}
                    <button
                      type="button"
                      onClick={() => removeLocality(value)}
                      className="ml-1 hover:bg-muted rounded-full p-0.5"
                    >
                      <X className="h-3 w-3" />
                    </button>
                  </Badge>
                ))}
              </div>
            )}

            {/* Search and Select Dropdown */}
            <Popover open={open} onOpenChange={setOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={open}
                  className={cn(
                    "w-full justify-between",
                    !selectedValues.length && "text-muted-foreground"
                  )}
                >
                  {selectedValues.length > 0
                    ? `${selectedValues.length} selected`
                    : "Search and select localities"}
                  <ChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0" align="start">
                <Command>
                  <CommandInput
                    placeholder="Search locality, city, or state..."
                    value={searchTerm}
                    onValueChange={setSearchTerm}
                  />
                  <CommandList>
                    <CommandEmpty>No localities found.</CommandEmpty>
                    <CommandGroup>
                      {filteredLocalities.map((locality) => (
                        <CommandItem
                          key={locality.value}
                          value={locality.value}
                          onSelect={() => toggleLocality(locality.value)}
                          className="flex items-center justify-between"
                        >
                          <div className="flex items-center gap-2">
                            <div
                              className={cn(
                                "h-4 w-4 border rounded flex items-center justify-center",
                                selectedValues.includes(locality.value)
                                  ? "bg-primary border-primary"
                                  : "border-input"
                              )}
                            >
                              {selectedValues.includes(locality.value) && (
                                <span className="text-primary-foreground text-xs">✓</span>
                              )}
                            </div>
                            <div>
                              <div className="font-medium">{locality.label}</div>
                              <div className="text-xs text-muted-foreground">
                                {locality.city}, {locality.state}
                              </div>
                            </div>
                          </div>
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>

            {/* Helper Text - Add New Locality */}
            {!showGooglePlacesInput && (
              <p className="text-xs text-muted-foreground">
                Locality not found?{" "}
                <button
                  type="button"
                  onClick={handleAddNewLocality}
                  className="text-primary hover:underline font-medium"
                >
                  Click here to Add new locality
                </button>
              </p>
            )}

            {/* Google Places Search Input */}
            {showGooglePlacesInput && (
              <div className="space-y-2 border rounded-lg p-3 bg-muted/50">
                <Label htmlFor="google-places-search" className="text-sm font-medium">
                  Add New Locality
                </Label>
                <div className="flex gap-2">
                  <div className="relative flex-1">
                    <MapPin className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      id="google-places-search"
                      placeholder="Type Locality, City and State name to search"
                      value={googlePlacesSearch}
                      onChange={(e) => setGooglePlacesSearch(e.target.value)}
                      className="pl-9"
                    />
                  </div>
                  <Button
                    type="button"
                    size="sm"
                    onClick={handleGooglePlacesSearch}
                    disabled={!googlePlacesSearch.trim()}
                  >
                    <Plus className="h-4 w-4 mr-1" />
                    Add
                  </Button>
                </div>
                <button
                  type="button"
                  onClick={() => {
                    setShowGooglePlacesInput(false);
                    setGooglePlacesSearch("");
                  }}
                  className="text-xs text-muted-foreground hover:text-foreground"
                >
                  Cancel
                </button>
              </div>
            )}

            {description && !showGooglePlacesInput && (
              <p className="text-xs text-muted-foreground">{description}</p>
            )}

            {fieldState.error && (
              <p className="text-xs text-destructive">{fieldState.error.message}</p>
            )}
          </div>
        );
      }}
    />
  );
};
