import React from 'react'
import styled from 'styled-components'
import { Validator,Schema } from 'jsonschema'
import { IJsonSchema } from '../../types/IJsonSchema'
import { capitalCase } from 'change-case'

export type InputWrapperProps = {
  label?:string
  children: JSX.Element;
  jsonSchema?: IJsonSchema
  value?: unknown
};

export const InputWrapper = ({ children,label,jsonSchema={},value }: InputWrapperProps):JSX.Element => {
  label = capitalCase(label||'')
  const validator = new Validator()
  const { errors } = validator.validate(value, jsonSchema as Schema)
  const errorMessage = errors.length ? jsonSchema?.errorMessage||errors[0].message : ''

  return (
    <Container>
      <Wrapper error={errorMessage ? errorMessage.length > 0 : false} type={jsonSchema?.type}>
        <Label>{label && `${label}:`}</Label>
        {children}
      </Wrapper>
      {errorMessage && <ErrorMessage type={jsonSchema?.type}>{errorMessage}</ErrorMessage>} 
    </Container>
  )
}

const Container = styled.div`
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
  display: flex;
  flex-direction: column;  
  justify-content: center;
  width:100%;
`
const Wrapper = styled.div<{error?:boolean,type?:string}>`
  border-radius: 4px; 
  background: white;
  border: ${(p) => p.error ? '1px solid #fa5252' : '1px solid #ced4da'};
  min-height:40px;
  display: flex;
  align-items: center;
  flex:1;
  width:100%;
`
const Label = styled.span`
  font-size: 1rem;
  margin: 5px 5px;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
  font-weight: 600;
  white-space: nowrap;
  color: #4b4b4b;
`
const ErrorMessage = styled.span<{type?:string}>`
  color: #fa5252;
  font-size: 1rem;
  line-height: 1.2;
  margin-top: 3px;
  font-weight: 100;
  margin-top: ${(p) => p.type === 'boolean' &&  0};
`