import {
 IonRow,
 IonCol,
 IonInput,
 IonButton,
 IonIcon,
 IonModal,
 IonDatetime,
} from "@ionic/react";
import { calendarOutline } from "ionicons/icons";
import { useState } from "react";

interface DatePickerProps {
 label: string;
 value: string | null;
 onChange: (val: string) => void;
 placeholder?: string;
 min?: string;
 max?: string;
}

const DatePicker: React.FC<DatePickerProps> = ({
 label,
 value,
 onChange,
 placeholder = "Select date",
 min,
 max,
}) => {
 const [showCalendar, setShowCalendar] = useState(false);

 return (
  <>
   <IonRow>
    <IonCol size="11">
     <IonInput
      label={label}
      labelPlacement="stacked"
      value={value ? new Date(value).toLocaleDateString() : ""}
      placeholder={placeholder}
      readonly
     />
    </IonCol>
    <IonCol size="1" className="ion-text-end">
     <IonButton
      fill="clear"
      shape="round"
      onClick={() => setShowCalendar(true)}
     >
      <IonIcon icon={calendarOutline} />
     </IonButton>
    </IonCol>
   </IonRow>

   <IonModal
    isOpen={showCalendar}
    onDidDismiss={() => setShowCalendar(false)}
    backdropDismiss={false}
   >
    <IonDatetime
     presentation="date"
     value={value ?? ""}
     min={min}
     max={max}
     onIonChange={(e) => {
      const selected = e.detail.value;
      if (typeof selected === "string") {
       onChange(selected);
       // setShowCalendar(false);
      }
     }}
    />
    <IonButton expand="block" onClick={() => setShowCalendar(false)}>
     Done
    </IonButton>
   </IonModal>
  </>
 );
};

export default DatePicker;
