"use client";

import { useEffect, useState } from "react";

interface City {
  id: number;
  name: string;
}

interface CityDropdownProps {
  countryId?: number | null;
  value?: number | null;
  onChange: (cityId: number | null) => void;
  className?: string;
}

export default function CityDropdown({
  countryId,
  value,
  onChange,
  className,
}: CityDropdownProps) {
  const [cities, setCities] = useState<City[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!countryId) {
      setCities([]);
      onChange(null);
      return;
    }

    setIsLoading(true);
    fetch(`/api/v1/countries/${countryId}/cities`)
      .then((res) => res.json())
      .then((data) => setCities(data.data || []))
      .catch((err) => console.error("Failed to load cities:", err))
      .finally(() => setIsLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [countryId]);

  return (
    <select
      value={value ?? ""}
      onChange={(e) => onChange(e.target.value ? Number(e.target.value) : null)}
      disabled={isLoading || !countryId}
      className={`rounded-lg border border-zinc-700 bg-zinc-800 px-3 py-2 text-sm text-zinc-200 focus:border-purple-500 focus:outline-none focus:ring-1 focus:ring-purple-500 disabled:opacity-50 ${className || ""}`}
    >
      <option value="">Select city...</option>
      {cities.map((city) => (
        <option key={city.id} value={city.id}>
          {city.name}
        </option>
      ))}
    </select>
  );
}
