'use client';
import {useEffect,useId,useRef,useState} from 'react';
import {birthDateError,persianBirthDateToIso,isoToPersianBirthDate,gregorianBirthDateLabel} from '@/lib/birth-date';

export function PersianBirthDate({defaultValue='',disabled=false}:{defaultValue?:string;disabled?:boolean}){
 const [value,setValue]=useState(()=>isoToPersianBirthDate(defaultValue)),[touched,setTouched]=useState(false);
 const input=useRef<HTMLInputElement>(null),hintId=useId(),errorId=useId();
 const date=persianBirthDateToIso(value),error=birthDateError(value);
 useEffect(()=>{input.current?.setCustomValidity(error)},[error]);
 function change(next:string){setValue(next);input.current?.setCustomValidity(birthDateError(next));}
 return <label className="dash-birth-date">تاریخ تولد <small>(شمسی)</small>
  <input ref={input} type="text" inputMode="numeric" dir="ltr" value={value} disabled={disabled} maxLength={10}
   aria-label="تاریخ تولد شمسی" aria-describedby={`${hintId}${touched&&error?' '+errorId:''}`} aria-invalid={touched&&!!error}
   placeholder="سال / ماه / روز" onChange={e=>change(e.target.value)}
   onInvalid={()=>setTouched(true)} onBlur={()=>{setTouched(true);if(date&&!error)change(isoToPersianBirthDate(date));}}/>
  <input type="hidden" name="birth_date" value={error?'':date||''} disabled={disabled}/>
  <small id={hintId} className="dash-birth-gregorian" aria-live="polite" aria-atomic="true">{date&&!error?<>
   میلادی: <bdi dir="ltr" lang="en">{gregorianBirthDateLabel(date)}</bdi>
  </>:'معادل میلادی پس از واردکردن تاریخ نمایش داده می‌شود.'}</small>
  {touched&&error&&<small id={errorId} className="dash-birth-error" role="alert">{error}</small>}
 </label>;
}
