"use client";
import classNames from "classnames";
import style from "./TextTime.module.css";
import { useTimePickerStore } from "@store/TimePicker.Store";
import { useEffect, useState } from "react";
import dayjs from "dayjs";
import "dayjs/locale/es";

dayjs.locale("es");

export type TextboxWidth = "80%" | "100%";
interface TextTimeProps {
    value?: dayjs.Dayjs;
    timeFraction?: number;
    defaultValue?: dayjs.Dayjs;
    placeholder: string;
    width?: TextboxWidth;
    onChange?: (newValue: dayjs.Dayjs) => void;
}

export default function TextTime(props: TextTimeProps): React.ReactElement {
    const { width = "80%" } = props;
    const timePicker = useTimePickerStore();
    const [timeValue, setTimeValue] = useState<dayjs.Dayjs>(
        props.value ? props.value : dayjs(new Date())
    );

    useEffect(() => {
        if (props.value) {
            setTimeValue(props.value);
        }
    }, [props.value]);

    /* eslint-disable @typescript-eslint/no-explicit-any */
    const getWidth = (base: any) => {
        if (width === "100%") {
            return classNames(base, style.textTimeWidth100);
        } else if (width === "80%") {
            return classNames(base, style.textTimeWidth80);
        }
        return classNames(base, style.textTimeWidth80);
    };

    const configureTimePicker = () => {
        if (props.defaultValue) {
            timePicker.setDefaultValue(props.defaultValue);
        }

        if (props.timeFraction) {
            timePicker.setTimeFraction(props.timeFraction);
        }

        if (props.value) {
            timePicker.setValue(props.value);
        }
    };

    const onClickHandler = () => {
        configureTimePicker();
        timePicker.show(onAcceptHandler);
    };

    const formatValue = () => {
        return timeValue.format("HH:mm") + " hs.";
    };

    const onAcceptHandler = (newValue: dayjs.Dayjs) => {
        setTimeValue(newValue);
        if (props.onChange) {
            props.onChange(newValue);
        }
        configureTimePicker();
    };

    return (
        <>
            {props.placeholder && (
                <>
                    <div className={getWidth(style.textTimeLabelContainer)}>
                        <div className={getWidth(style.textTimeLabel)}>{props.placeholder}</div>
                    </div>
                </>
            )}
            <div className={getWidth(style.textTime)} onClick={onClickHandler}>
                {formatValue()}
            </div>
        </>
    );
}
