"use client";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from "@/components/ui/select";
import { CountryFlag } from "@/components/ui/country-flag";
import {
  DEFAULT_SHIPPING_COUNTRY,
  SHIPPING_COUNTRIES,
  shippingCountryName,
} from "@/lib/shipping-countries";
import { cn } from "@/lib/utils";

export type CountrySelectProps = {
  value?: string;
  onChange: (countryCode: string) => void;
  id?: string;
  disabled?: boolean;
  className?: string;
};

export function CountrySelect({
  value = DEFAULT_SHIPPING_COUNTRY,
  onChange,
  id,
  disabled,
  className,
}: CountrySelectProps) {
  const code = value || DEFAULT_SHIPPING_COUNTRY;

  return (
    <Select value={code} disabled={disabled} onValueChange={onChange}>
      <SelectTrigger id={id} className={cn("border-input bg-gray-100", className)}>
        <span className="flex min-w-0 items-center gap-2">
          <CountryFlag code={code} />
          <span className="truncate">
            {shippingCountryName(code)} ({code})
          </span>
        </span>
      </SelectTrigger>
      <SelectContent className="max-h-64">
        {SHIPPING_COUNTRIES.map((c) => (
          <SelectItem key={c.code} value={c.code}>
            <span className="flex items-center gap-2">
              <CountryFlag code={c.code} />
              <span>
                {c.name} ({c.code})
              </span>
            </span>
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
}

export default CountrySelect;
