"use client"
import { Select } from "@medusajs/ui"
import ChevronDown from "@modules/common/icons/chevron-down"
import {
  LayoutComponentDefinition,
  LayoutContext,
} from "@vibentec/component-map"
import { useMemo, useState, useEffect } from "react"
import { useParams, usePathname, useRouter } from "next/navigation"
import ReactCountryFlag from "react-country-flag"
import { HttpTypes } from "@medusajs/types"

export default function VtCountrySelectClient({
  nodes,
  context,
  regions,
}: {
  nodes: LayoutComponentDefinition
  context: LayoutContext
  regions?: HttpTypes.StoreRegion[]
}) {
  const props = nodes.config ?? {}
  const triggerText = props?.trigger?.text
  const [items, setItems] = useState<{ text: string; label?: string }[]>([])
  const { countryCode } = useParams()
  useEffect(() => {
    if (!regions || regions.length === 0) {
      setItems([])
      return
    }
    const opts = regions
      .map((r) =>
        (r.countries || []).map((c) => ({
          text: c.iso_2 ?? "",
          label: c.display_name,
        }))
      )
      .flat()
      .filter((o) => o.text)
      .sort((a, b) => (a.label ?? "").localeCompare(b.label ?? ""))
    setItems(opts)
  }, [regions])

  const initialValue = (countryCode as string) || triggerText || ""
  const [value, setValue] = useState(initialValue)
  const pathname = usePathname()
  const router = useRouter()

  const handleChange = (next: string) => {
    setValue(next)
    if (!pathname || !next) return
    const parts = pathname.split("/")
    if (parts.length > 1) {
      parts[1] = next.toLowerCase()
      const newPath = parts.join("/")
      router.replace(newPath)
    }
  }
  const selectedItem = useMemo(() => {
    return items.find((i) => i.text === value)
  }, [items, value])
  if (!triggerText && items.length === 0) {
    return null
  }
  return (
    <Select value={value} onValueChange={handleChange}>
      <Select.Trigger
        className={
          (props.trigger?.className ?? "") +
          "flex items-center gap-1 [&_svg:not(:first-of-type)]:hidden"
        }
      >
        <span className="txt-compact-small flex items-center">
          {/* @ts-ignore */}
          {props.trigger?.isFlag && (
            <ReactCountryFlag
              svg
              style={{
                width: "16px",
                height: "16px",
              }}
              countryCode={value ?? ""}
            />
          )}
        </span>
        {props.trigger?.isDisplayFullname ? (selectedItem?.label || value) : (selectedItem?.text.toUpperCase() || value)} <ChevronDown />
      </Select.Trigger>
      <Select.Content>
        {items.length > 0 &&
          items.map((item: { text: string; label?: string }, index: number) => (
            <Select.Item value={item.text || ""} key={item.text + index}>
              <div className="flex items-center w-full gap-3">
                {props.trigger?.isFlag && item.text && (
                  <ReactCountryFlag
                    svg
                    style={{
                      width: "16px",
                      height: "16px",
                    }}
                    countryCode={item.text ?? ""}
                  />
                )}
                {item.text.toUpperCase()}
              </div>
            </Select.Item>
          ))}
      </Select.Content>
    </Select>
  )
}
