"use client";

import { useEffect, useState } from "react";

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

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

export default function CountryDropdown({ value, onChange, className }: CountryDropdownProps) {
  const [countries, setCountries] = useState<Country[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    fetch("/api/v1/countries")
      .then((res) => res.json())
      .then((data) => setCountries(data.data || []))
      .catch((err) => console.error("Failed to load countries:", err))
      .finally(() => setIsLoading(false));
  }, []);

  return (
    <select
      value={value ?? ""}
      onChange={(e) => onChange(e.target.value ? Number(e.target.value) : null)}
      disabled={isLoading}
      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 country...</option>
      {countries.map((country) => (
        <option key={country.id} value={country.id}>
          {country.name}
        </option>
      ))}
    </select>
  );
}
