"use client"

import { useMemo, useState } from "react"
import { ChevronDown, Search } from "lucide-react"
import { CountryCode } from "libphonenumber-js"

import { Drawer, DrawerContent, DrawerDescription, DrawerHeader, DrawerTitle } from "@/components/ui/drawer"
import { callingCode, countryOptions, formatNational, readPhoneInput, toLatinDigits } from "@/lib/helpers/phone.helper"
import { cn } from "@/lib/utils"

type PhoneFieldProps = {
  country: CountryCode
  national: string
  error?: string | null
  disabled?: boolean
  onChange: (value: { country: CountryCode; national: string }) => void
  onBlur?: () => void
}

/** A mobile number: country (Iran by default) and the national number, left to right like every phone. */
export default function PhoneField({ country, national, error, disabled, onChange, onBlur }: PhoneFieldProps) {
  const [pickerOpen, setPickerOpen] = useState(false)
  const errorId = "phone-error"

  return (
    <div className="flex flex-col">
      <label htmlFor="phone" className="text-body-sm font-bold text-ink mb-2">شماره موبایل</label>

      <div
        dir="ltr"
        className={cn(
          "flex items-stretch h-14 rounded-2xl border bg-canvas transition focus-within:ring-2",
          error ? "border-rose focus-within:ring-rose/20" : "border-line focus-within:border-sienna focus-within:ring-sienna/15",
        )}
      >
        <button
          type="button"
          disabled={disabled}
          onClick={() => setPickerOpen(true)}
          aria-label="انتخاب کشور"
          className="flex items-center gap-1.5 px-3 border-r border-line text-body font-bold text-ink shrink-0 disabled:opacity-50"
        >
          <span className="tabular-nums">{callingCode(country)}</span>
          <ChevronDown className="w-4 h-4 text-ink-soft" aria-hidden="true" />
        </button>

        <input
          id="phone"
          type="tel"
          inputMode="tel"
          autoComplete="tel-national"
          autoFocus
          disabled={disabled}
          value={formatNational(national, country)}
          placeholder={country === "IR" ? "0912 345 6789" : ""}
          aria-invalid={!!error}
          aria-describedby={error ? errorId : undefined}
          onChange={(e) => onChange(readPhoneInput(e.target.value, country))}
          onPaste={(e) => {
            e.preventDefault()
            onChange(readPhoneInput(toLatinDigits(e.clipboardData.getData("text")), country))
          }}
          onBlur={onBlur}
          className="flex-1 min-w-0 bg-transparent px-3 text-[1.0625rem] tracking-wide tabular-nums text-ink outline-none placeholder:text-ink-soft/50"
        />
      </div>

      <p id={errorId} role={error ? "alert" : undefined} className={cn("text-caption mt-2 min-h-5", error ? "text-rose" : "text-ink-soft")}>
        {error ?? "کد ورود را به این شماره پیامک می‌کنیم."}
      </p>

      <CountryPicker
        open={pickerOpen}
        selected={country}
        onOpenChange={setPickerOpen}
        onSelect={(code) => {
          setPickerOpen(false)
          onChange({ country: code, national })
        }}
      />
    </div>
  )
}

function CountryPicker({ open, selected, onOpenChange, onSelect }: {
  open: boolean
  selected: CountryCode
  onOpenChange: (open: boolean) => void
  onSelect: (code: CountryCode) => void
}) {
  const [query, setQuery] = useState("")
  const options = useMemo(() => countryOptions(), [])
  const term = toLatinDigits(query).trim().toLowerCase().replace(/^\+/, "")
  const shown = term === ""
    ? options
    : options.filter((o) => o.name.toLowerCase().includes(term) || o.code.toLowerCase() === term || o.dial.slice(1).startsWith(term))

  return (
    <Drawer open={open} onOpenChange={(next) => { onOpenChange(next); if (!next) setQuery("") }}>
      <DrawerContent className="mx-auto w-full max-w-[480px]">
        <DrawerHeader className="text-right">
          <DrawerTitle className="text-title-3 font-extrabold">کشور شماره</DrawerTitle>
          <DrawerDescription className="sr-only">کشور شماره‌ی موبایل را انتخاب کن</DrawerDescription>
        </DrawerHeader>
        <div className="px-4 pb-2">
          <label className="flex items-center gap-2 h-11 rounded-2xl border border-line bg-canvas px-3 focus-within:border-sienna">
            <Search className="w-4 h-4 text-ink-soft" aria-hidden="true" />
            <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="نام کشور یا کد" aria-label="جستجوی کشور"
                   className="flex-1 bg-transparent text-body outline-none" />
          </label>
        </div>
        <ul className="px-2 pb-[max(16px,env(safe-area-inset-bottom))] max-h-[55vh] overflow-y-auto">
          {shown.map((o) => (
            <li key={o.code}>
              <button
                type="button"
                onClick={() => onSelect(o.code)}
                className={cn("w-full flex items-center gap-3 px-3 py-3 rounded-xl text-right", o.code === selected ? "bg-sienna-soft/60" : "active:bg-paper-2")}
              >
                <span className="flex-1 text-body text-ink truncate">{o.name === o.code ? o.code : o.name}</span>
                <span dir="ltr" className="text-body-sm text-ink-soft tabular-nums">{o.dial}</span>
              </button>
            </li>
          ))}
          {shown.length === 0 && <li className="px-3 py-6 text-center text-body-sm text-ink-soft">کشوری پیدا نشد.</li>}
        </ul>
      </DrawerContent>
    </Drawer>
  )
}
