import DateTimeField, { toMinutePrecisionIsoUtc } from '@/components/common/DateTimeField'
import FormField from '@/components/common/FormField'
import { Button } from '@/components/ui/button'

import type { FC } from 'react'

type Props = {
    disabled?:                boolean
    originalCreatedFrom:      string | null
    setOriginalCreatedFrom:   (x: string | null) => void
    originalCreatedBefore:    string | null
    setOriginalCreatedBefore: (x: string | null) => void
    errors?:                  string[] }


const PostOriginalCreatedTimeField: FC<Props> = (
    { disabled,
      originalCreatedFrom,
      setOriginalCreatedFrom,
      originalCreatedBefore,
      setOriginalCreatedBefore,
      errors }: Props) => {
  return (
      <FormField label="オリジナルの作成日時" messages={errors}>
	  {({ describedBy, invalid }) => (
	      <>
		<div className="my-1 flex">
		  <div className="w-80">
		    <DateTimeField
			className="mr-2"
			disabled={disabled ?? false}
			aria-describedby={describedBy}
			aria-invalid={invalid}
			invalid={invalid}
			value={originalCreatedFrom ?? undefined}
			onChange={setOriginalCreatedFrom}
			onBlur={ev => {
			  const v = ev.target.value
			  if (!(v))
			    return

			  const d = new Date (v)
			  if (d.getMinutes () === 0 && d.getHours () === 0)
			    d.setDate (d.getDate () + 1)
			  else
			    d.setMinutes (d.getMinutes () + 1)
			  setOriginalCreatedBefore (toMinutePrecisionIsoUtc (d.toISOString ()))
			}}/>
		    以降
		  </div>
		  <div>
		    <Button
			type="button"
			className="bg-gray-600 text-white rounded"
			disabled={disabled}
			onClick={() => {
			  setOriginalCreatedFrom (null)
			}}>
		      リセット
		    </Button>
		  </div>
		</div>

		<div className="my-1 flex">
		  <div className="w-80">
		    <DateTimeField
			className="mr-2"
			disabled={disabled}
			aria-describedby={describedBy}
			aria-invalid={invalid}
			invalid={invalid}
			value={originalCreatedBefore ?? undefined}
			onChange={setOriginalCreatedBefore}/>
		    より前
		  </div>
		  <div>
		    <Button
			type="button"
			className="bg-gray-600 text-white rounded"
			disabled={disabled}
			onClick={() => {
			  setOriginalCreatedBefore (null)
			}}>
		      リセット
		    </Button>
		  </div>
		</div>
	      </>)}
      </FormField>)
}

export default PostOriginalCreatedTimeField
