import { InputHTMLAttributes, forwardRef, useState, useEffect } from 'react';

interface DateTimeInputProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'type' | 'value' | 'onChange'> {
    label?: string;
    error?: string;
    helperText?: string;
    value?: number; // Unix timestamp
    onChange?: (timestamp: number) => void;
}

const DateTimeInput = forwardRef<HTMLInputElement, DateTimeInputProps>(
    ({ label, error, helperText, value, onChange, className = '', required, ...props }, ref) => {
        // Convert unix timestamp to datetime-local format (YYYY-MM-DDTHH:mm)
        const formatDateTimeLocal = (timestamp?: number): string => {
            if (!timestamp) return '';
            const date = new Date(timestamp * 1000);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day}T${hours}:${minutes}`;
        };

        // Convert datetime-local format to unix timestamp
        const parseDateTimeLocal = (dateTimeString: string): number => {
            if (!dateTimeString) return 0;
            const date = new Date(dateTimeString);
            return Math.floor(date.getTime() / 1000);
        };

        const [localValue, setLocalValue] = useState(formatDateTimeLocal(value));

        useEffect(() => {
            setLocalValue(formatDateTimeLocal(value));
        }, [value]);

        const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
            const newValue = e.target.value;
            setLocalValue(newValue);
            if (onChange) {
                const timestamp = parseDateTimeLocal(newValue);
                onChange(timestamp);
            }
            // Update hidden input if exists
            if (props.name) {
                const form = e.target.closest('form');
                if (form) {
                    const hiddenInput = form.querySelector(`input[type="hidden"][name="${props.name}"]`) as HTMLInputElement;
                    if (hiddenInput) {
                        hiddenInput.value = parseDateTimeLocal(newValue).toString();
                    }
                }
            }
        };

        const inputClasses = `
            block w-full rounded-lg border px-4 py-3 text-sm
            transition-all duration-200
            placeholder:text-gray-400
            focus:outline-none focus:ring-2 focus:ring-offset-0
            dark:placeholder:text-gray-500
            ${
                error
                    ? 'border-red-300 bg-red-50 text-red-900 focus:border-red-500 focus:ring-red-500 dark:border-red-700 dark:bg-red-900/20 dark:text-red-200'
                    : 'border-gray-300 bg-white text-gray-900 shadow-sm focus:border-[#d4af37] focus:ring-[#d4af37]/20 dark:border-gray-600 dark:bg-gray-800 dark:text-white dark:focus:border-[#b8941f] dark:focus:ring-[#b8941f]/20'
            }
            ${className}
        `;

        return (
            <div className="w-full">
                {label && (
                    <label
                        htmlFor={props.id}
                        className="mb-2 block text-sm font-semibold text-gray-700 dark:text-gray-300"
                    >
                        {label}
                        {required && <span className="ml-1 text-red-500">*</span>}
                    </label>
                )}
                <div className="relative">
                    <input
                        ref={ref}
                        type="datetime-local"
                        value={localValue}
                        onChange={handleChange}
                        className={inputClasses}
                        required={required}
                        {...(props.name ? { name: undefined } : {})}
                        {...props}
                    />
                </div>
                {error && (
                    <p className="mt-2 flex items-center gap-1 text-sm font-medium text-red-600 dark:text-red-400">
                        <svg
                            className="h-4 w-4"
                            fill="none"
                            viewBox="0 0 24 24"
                            strokeWidth="2"
                            stroke="currentColor"
                        >
                            <path
                                strokeLinecap="round"
                                strokeLinejoin="round"
                                d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
                            />
                        </svg>
                        {error}
                    </p>
                )}
                {helperText && !error && (
                    <p className="mt-2 text-sm text-gray-500 dark:text-gray-400">{helperText}</p>
                )}
            </div>
        );
    }
);

DateTimeInput.displayName = 'DateTimeInput';

export default DateTimeInput;

