import React from "react";
import styled from "styled-components";

const Widget = styled.div`
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-start;
  width: 100%;
  margin: 0 -0.5rem 0.5rem;

  > input {
    margin: 0 0.5rem;
  }
`;

interface DatetimeWidgetProps {
  value: string;
  onChange: (value: string) => void;
  onFocus: () => void;
  onBlur: () => void;
  required: boolean;
  disabled: boolean;
}

const DatetimeWidget: React.FC<DatetimeWidgetProps> = ({
  value, onChange, onFocus, onBlur, required, disabled,
}) => {
  let date;
  let time;
  if (value && value.length !== 0) {
    let rest;
    [date, rest] = value.split("T");
    time = rest.slice(0, 5);
  }

  const commonProps = {
    onFocus,
    onBlur,
    required,
    disabled,
  };

  return (
    <Widget>
      <input
        type="date"
        onChange={(event) => onChange(`${event.target.value}T${time}`)}
        value={date}
        {...commonProps}
      />
      <input
        type="time"
        onChange={(event) => onChange(`${date}T${event.target.value}:00`)}
        value={time}
        {...commonProps}
      />
    </Widget>
  );
};

export default DatetimeWidget;
