import type { Control, FieldErrorsImpl } from 'react-hook-form'
import { Controller } from 'react-hook-form'
import React from 'react'

import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'

import { Width } from '../Width'
import { Error } from '../Error'
import { countryOptions } from '../Country/options'

type PhoneFieldProps = {
  name: string
  label: string
  required?: boolean
  defaultCountry?: string
  width?: string
  control: Control
  errors: Partial<FieldErrorsImpl>
}

export const Phone: React.FC<PhoneFieldProps> = ({
  name,
  label,
  required,
  defaultCountry = 'IN',
  width,
  control,
  errors,
}) => {
  return (
    <Width width={width}>
      <Label htmlFor={name}>
        {label}
        {required && <span className="required">*</span>}
      </Label>

      <div className="flex gap-2">
        {/* Country selector */}
        <Controller
          name={`${name}.country`}
          control={control}
          defaultValue={defaultCountry}
          rules={{ required }}
          render={({ field }) => (
            <Select onValueChange={field.onChange} value={field.value}>
              <SelectTrigger className="w-[120px]">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                {countryOptions.map((c) => (
                  <SelectItem key={c.value} value={c.value}>
                    {c.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          )}
        />

        {/* Phone number input */}
        <Controller
          name={`${name}.number`}
          control={control}
          rules={{ required }}
          render={({ field }) => (
            <Input
              type="tel"
              placeholder="Phone number"
              {...field}
            />
          )}
        />
      </div>

      {errors?.[name] && <Error name={name} />}
    </Width>
  )
}
