import React from 'react';
import TranslateTextKey from '../../i18n/translateTextKey';
import styled from 'styled-components';
import {
  RadioInputContainer,
  FormTextInput,
  CheckboxInputContainer,
  TextInputContainer,
  AddressTextInput,
  InputError,
} from './input.styles';
import {
  AddressContainer,
  LinkIconContainer,
  ListItemContainer,
  ResponseContainer,
  SelectContainer,
  UnorderedListContainer,
} from './container.styles';
import {HiExternalLink} from 'react-icons/hi';
import Link from 'next/link';
import {DropdownSelect} from 'src/components/core';
import {
  ADDRESSLINE1,
  ADDRESSLINE2,
  BASE_QUIT_URL,
  COMMUNICATION,
  CONTROLLED,
  HOUSEHOLD,
  KIC_API_QUERY_KEYS,
  NONRESIDENT,
  PHONE,
  PRE,
} from 'src/forms/_resources/utils/formConstants';
import FIELD_TYPES from 'src/constants/fieldTypes';

interface TitleProp {
  title: string;
}
interface HeadingProp {
  heading: string;
}
interface TextProp {
  text: string;
}
interface UserInputProps {
  response: Array<any>;
  value?: string;
  secondaryValue?: string;
  translateKey: (key: string) => undefined;
  currentQuestion: any;
  inputHandler: (evt: any, name: string, currentQuestion: any) => void;
  secondaryHandler: (evt: any, name: string, currentQuestion: any) => void;
  error?: string;
  maxLength?: number;
}
interface MdInputProps {
  response: Array<any>;
  value?: string;
  secondaryValue?: string;
  translateKey: (key: string) => undefined;
  currentQuestion: any;
  inputHandler: (evt: any, name: string, currentQuestion: any) => void;
  secondaryHandler: (evt: any, name: string, currentQuestion: any) => void;
  error?: string;
  maxLength?: number;
  checkboxValues: any;
  checkboxName: string;
  checkboxHandler: (item: any, currentQuestion: any) => void;
}
interface IAddressProps {
  response: Array<any>;
  value: any;
  translateKey: (key: string) => undefined;
  currentQuestion: any;
  inputHandler: (evt: any, currentQuestion: any) => void;
  maxLength?: number;
  half?: boolean;
  error: string;
}
interface UserRadioInputProps {
  response: Array<any>;
  currentQuestion: any;
  radioValues: any;
  radioHandler: (evt: any, item: any, currentQuestion: any) => void;
}

interface OptionsProps {
  options: Array<any>;
  onClick: (value: string) => void;
}
interface OptionsInputProps {
  options: Array<any>;
  optionName: string;
  displayOptions: boolean;
  value: string;
  onClick: (value: string) => void;
  onChange: (value: string) => void;
}

interface UserOtherInputProps {
  name: string;
  onChange: (value: string) => void;
  value: string;
}

interface UserCheckboxInputProps {
  response: Array<any>;
  currentQuestion: any;
  checkboxValues: any;
  checkboxName: string;
  checkboxHandler: (item: any, currentQuestion: any) => void;
}
interface MultiSelectProps {
  response: Array<any>;
  currentQuestion: any;
  checkboxValues: any;
  checkboxName: string;
  displayOptions: boolean;
  toggle: () => void;
  checkboxHandler: (item: any, currentQuestion: any) => void;
}

interface ListProps {
  language: any;
  response: Array<any>;
  currentQuestion: any;
  currentResults?: any;
}

interface IEligibility {
  response: Array<any>;
  currentQuestion: any;
  language: any;
  isBusinessOpen?: boolean;
}

const OptionsDiv = styled.div`
  width: 100%;
  position: absolute;
  border-radius: 3px;
  top: 80px;
  z-index: 5;
  max-height: 240px;
  height: auto;
  background: #f4f7f7;
  overflow-x: hidden;
  scroll-x: auto;
`;

const Option = styled.div`
  width: 100%;
  padding: 0px 10px;
  borderbottom: 1px solid black;
  &:hover {
    background: (0, 0, 0, 0.2);
    cursor: pointer;
  }
`;

const DesktopNum = styled.div`
  width: auto;
  margin: 0 auto;
  display: none;
  @media (min-width: 1024px) {
    display: block;
  }
`;

const MobileNum = styled.div`
  width: auto;
  margin: 0 auto;
  display: block;
  @media (min-width: 1024px) {
    display: none;
  }
`;

export const UserEligibility: React.FC<IEligibility> = ({response, currentQuestion, language, isBusinessOpen}) => {
  if (isBusinessOpen) {
    return (
      <React.Fragment>
        <FormText text={currentQuestion.text} />
        <DesktopNum>
          <h2>{response[0].text[language].desktop}</h2>
        </DesktopNum>
        <MobileNum>
          <h2>{response[0].text[language].mobile}</h2>
        </MobileNum>
      </React.Fragment>
    );
  } else {
    return (
      <React.Fragment>
        <FormText text={currentQuestion.afterHoursText} />
        <Link href={`${BASE_QUIT_URL}/1`}>Here</Link>
      </React.Fragment>
    );
  }
};

export const UserEligibilityOther: React.FC<IEligibility> = ({response, currentQuestion, language}) => {
  return (
    <React.Fragment>
      <FormText text={currentQuestion.text} />
      <DesktopNum>
        <h2>{response[0].text[language].desktop}</h2>
      </DesktopNum>
      <MobileNum>
        <a href={`tel:${response[0].text[language].mobile}`} data-click-category="phone" data-click-action="Call" data-click-label={response[0].text[language].mobile}>
          <h3>{response[0].text[language].mobile}</h3>
        </a>
      </MobileNum>
      <br />
      <br />
      {currentQuestion.subtext && <FormText text={currentQuestion.subtext} />}
    </React.Fragment>
  );
};

const OptionList: React.FC<OptionsProps> = ({options, onClick}) => {
  return (
    <OptionsDiv>
      {options.map((option, index) => (
        <Option key={index} onClick={() => onClick(option)}>
          <p>{option}</p>
        </Option>
      ))}
    </OptionsDiv>
  );
};

const AutoComplete: React.FC<OptionsInputProps> = ({options, optionName, onClick, displayOptions, onChange, value}) => {
  return (
    <div style={{position: 'relative'}}>
      <br />
      <FormTextInput name={optionName} value={value} type={'text'} onChange={evt => onChange(evt.target.value)} />
      {displayOptions && <OptionList options={options} onClick={onClick} />}
    </div>
  );
};

export const GenderAutoComplete: React.FC<OptionsInputProps> = ({
  options,
  optionName,
  onClick,
  displayOptions,
  onChange,
  value,
}) => {
  return (
    <React.Fragment>
      <TranslateTextKey label textKey={'BASIC.RESPONSE.OTHER'} name={'other'} />
      <AutoComplete
        options={options}
        displayOptions={displayOptions}
        onClick={onClick}
        onChange={onChange}
        value={value}
        optionName={optionName}
      />
    </React.Fragment>
  );
};

export const UserTextOtherInput: React.FC<UserOtherInputProps> = ({name, onChange, value}) => {
  return (
    <React.Fragment>
      <FormTextInput type={'text'} name={name} value={value} onChange={evt => onChange(evt.target.value)} />
      <div style={{width:"100%", height:"20px"}}></div>
    </React.Fragment>
  );
};

export const FormTitle: React.FC<TitleProp> = ({title}) => <TranslateTextKey title textKey={title} />;
export const FormHeading: React.FC<HeadingProp> = ({heading}) => <TranslateTextKey formHeading textKey={heading} />;
export const FormText: React.FC<TextProp> = ({text}) => <TranslateTextKey formText textKey={text} />;

export const UserTextInput: React.FC<UserInputProps> = ({
  response,
  translateKey,
  secondaryValue,
  secondaryHandler,
  currentQuestion,
  inputHandler,
  value,
  error,
  maxLength,
}) => {
  return (
    <React.Fragment>
      {response.map((item, index: number, responseData) => {
        const {responseType, type, name} = responseData[index];
        const componentValue = index === 1 ? secondaryValue : value;
        const componentHandler = index === 1 ? secondaryHandler : inputHandler;

        return (
          <React.Fragment key={index}>
            <FormTextInput
              type={type}
              value={componentValue}
              name={name}
              onChange={evt => componentHandler(currentQuestion, evt.target.value, name)}
              placeholder={translateKey(item.placeholder)}
              maxLength={maxLength}
              style={{marginTop: '8px'}}
              inputMode={type === 'number' ? 'numeric' : undefined}
            />
            {currentQuestion.queryKey === KIC_API_QUERY_KEYS.MDPHONE && responseType === FIELD_TYPES.CHECKBOX && (
              <CheckboxInputContainer>
                <React.Fragment>
                  <input name={item.text} type={currentQuestion.type} />
                  <TranslateTextKey
                    label
                    name={name}
                    textKey={item.text}
                    style={{marginTop: 'auto', cursor: 'pointer'}}
                  />
                </React.Fragment>
              </CheckboxInputContainer>
            )}
            <br />
            {error ? <InputError>{error}</InputError> : null}
          </React.Fragment>
        );
      })}
    </React.Fragment>
  );
};

export const MdPhoneInput: React.FC<MdInputProps> = ({
  response,
  translateKey,
  currentQuestion,
  inputHandler,
  value,
  error,
  maxLength,
  checkboxValues,
  checkboxHandler,
  checkboxName,
}) => {
  const isChecked = checkboxValues.includes(response[1].text);
  return (
    <React.Fragment>
      <TranslateTextKey label textKey="" name={response[0].name} />
      <FormTextInput
        type={response[0].responseType}
        value={value}
        name={response[0].name}
        onChange={evt => inputHandler(currentQuestion, evt.target.value, response[0].name)}
        placeholder={translateKey(response[0].placeholder)}
        maxLength={maxLength}
        style={{margin: '8px 0px 24px 0px'}}
      />
      <CheckboxInputContainer onClick={() => checkboxHandler(response[1], checkboxName)} isChecked={isChecked} full>
        <React.Fragment>
          <input
            name={response[1].text}
            type={response[1].responseType}
            checked={isChecked}
            onChange={() => checkboxHandler(response[1], checkboxName)}
          />
          <TranslateTextKey
            label
            name={response[1].name}
            textKey={response[1].text}
            style={{marginTop: 'auto', cursor: 'pointer'}}
          />
        </React.Fragment>
      </CheckboxInputContainer>

      <br />
      {error ? <h5 style={{color: 'red'}}>{error}</h5> : null}
    </React.Fragment>
  );
};

export const AddressInput: React.FC<IAddressProps> = ({
  response,
  translateKey,
  currentQuestion,
  inputHandler,
  value,
  maxLength,
  error,
}) => {
  return (
    <AddressContainer>
      {response.map((item, index: number) => {
        const isAddressLine = item.name === ADDRESSLINE1 || item.name === ADDRESSLINE2;
        return (
          <React.Fragment key={index}>
            {isAddressLine && (
              <TextInputContainer>
                <AddressTextInput
                  type={currentQuestion.type}
                  value={value[item.key]}
                  name={item.name}
                  onChange={evt => inputHandler(item, evt.target.value)}
                  placeholder={translateKey(item.placeholder)}
                  maxLength={maxLength}
                  style={{marginTop: '4px'}}
                />
              </TextInputContainer>
            )}
            {!isAddressLine && (
              <TextInputContainer half>
                <AddressTextInput
                  type={currentQuestion.type}
                  value={value[item.key]}
                  name={item.name}
                  onChange={evt => inputHandler(item, evt.target.value)}
                  placeholder={translateKey(item.placeholder)}
                  maxLength={maxLength}
                  style={{marginTop: '4px'}}
                />
              </TextInputContainer>
            )}
          </React.Fragment>
        );
      })}
      {error ? <InputError>{error}</InputError> : null}
    </AddressContainer>
  );
};

export const UserRadioInput: React.FC<UserRadioInputProps> = ({
  response,
  currentQuestion,
  radioValues,
  radioHandler,
}) => {
  const isPreference = currentQuestion.queryKey === COMMUNICATION && currentQuestion.id === 4;
  const centered = !isPreference && response.length <= 2;
  return (
    <ResponseContainer center={centered}>
      {response.map((item, index: number) => {
        const name = `${currentQuestion.context}_radioGroup_${currentQuestion.id}`;
        const isChecked = radioValues[name] === item.text;
        const isFullWidth = response.length <= 2 && !isPreference;
        const isThirdWidth = response.length > 4;
        const isHbpControlled = currentQuestion.queryKey === CONTROLLED;
        const isAllergic = currentQuestion.queryKey === KIC_API_QUERY_KEYS.ADHESIVE;

        return (
          <RadioInputContainer
            key={index}
            onClick={() => radioHandler({target: {name, value: item.text}}, item, currentQuestion)}
            isChecked={isChecked}
            full={isFullWidth}
            large={isFullWidth || isPreference}
            third={isThirdWidth}
            auto={isHbpControlled || isAllergic}
          >
            <input
              name={name}
              value={item.text}
              checked={isChecked}
              type={currentQuestion.type}
              onChange={evt => radioHandler(evt, item, currentQuestion)}
              style={{alignSelf: 'flex-end'}}
            />
            <TranslateTextKey label name={name} textKey={item.text} style={{marginTop: 'auto', cursor: 'pointer'}} />
          </RadioInputContainer>
        );
      })}
    </ResponseContainer>
  );
};

export const UserCheckboxInput: React.FC<UserCheckboxInputProps> = ({
  response,
  checkboxValues,
  checkboxHandler,
  currentQuestion,
  checkboxName,
}) => {
  return (
    <ResponseContainer center={response.length <= 2}>
      {response.map((item, index: number) => {
        const isChecked = checkboxValues.includes(item.text);
        const name = `${currentQuestion.context}_checkboxGroup_${currentQuestion.id}`;
        const isFullWidth = response.length <= 2;
        const isThirdWidth = response.length > 4;
        const isHousehold =
          currentQuestion.queryKey === HOUSEHOLD || currentQuestion.queryKey === KIC_API_QUERY_KEYS.PRE.PRODUCTS;

        return (
          <CheckboxInputContainer
            key={index}
            onClick={() => checkboxHandler(item, checkboxName)}
            isChecked={isChecked}
            full={isFullWidth}
            large={isFullWidth}
            third={isThirdWidth}
            auto={isHousehold}
          >
            <React.Fragment>
              <input
                name={item.text}
                type={currentQuestion.type}
                checked={isChecked}
                onChange={() => checkboxHandler(item, checkboxName)}
              />
              <TranslateTextKey label name={name} textKey={item.text} style={{marginTop: 'auto', cursor: 'pointer'}} />
            </React.Fragment>
          </CheckboxInputContainer>
        );
      })}
    </ResponseContainer>
  );
};

export const MultiSelectInput: React.FC<MultiSelectProps> = ({
  response,
  checkboxValues,
  checkboxHandler,
  currentQuestion,
  checkboxName,
  toggle,
  displayOptions,
}) => {
  const primaryList = response.slice(0, 4);
  const secondaryList = response.slice(4);
  const name = `${currentQuestion.context}_checkboxGroup_${currentQuestion.id}`;
  const isFullWidth = response.length <= 2;
  const isThirdWidth = response.length > 4;

  if (!displayOptions) {
    return (
      <ResponseContainer center={response.length <= 2}>
        {primaryList.map((item, index: number) => {
          const isChecked = checkboxValues.includes(item.text);

          return (
            <CheckboxInputContainer
              key={index}
              onClick={() => checkboxHandler(item, checkboxName)}
              isChecked={isChecked}
              full={isFullWidth}
              large={isFullWidth}
              third={isThirdWidth}
            >
              <input
                name={item.text}
                type={currentQuestion.type}
                checked={isChecked}
                onChange={() => checkboxHandler(item, checkboxName)}
              />
              <TranslateTextKey label name={name} textKey={item.text} style={{marginTop: 'auto', cursor: 'pointer'}} />
            </CheckboxInputContainer>
          );
        })}
        <CheckboxInputContainer
          onClick={() => toggle()}
          full={isFullWidth}
          large={isFullWidth}
          third={isThirdWidth}
          option
        >
          <input type={currentQuestion.type} onChange={() => toggle()} />
          <TranslateTextKey
            label
            name={name}
            textKey={'INTAKE.SELF.RESPONSE.ETHNICITY.MORE'}
            style={{marginTop: 'auto', cursor: 'pointer'}}
          />
        </CheckboxInputContainer>
      </ResponseContainer>
    );
  } else {
    return (
      <ResponseContainer center={response.length <= 2}>
        <CheckboxInputContainer
          onClick={() => toggle()}
          full={isFullWidth}
          large={isFullWidth}
          third={isThirdWidth}
          option
        >
          <input type={currentQuestion.type} onChange={() => toggle()} />
          <TranslateTextKey
            label
            name={name}
            textKey={'INTAKE.SELF.RESPONSE.ETHNICITY.PREVIOUS'}
            style={{marginTop: 'auto', cursor: 'pointer'}}
          />
        </CheckboxInputContainer>
        {secondaryList.map((item, index: number) => {
          const isChecked = checkboxValues.includes(item.text);

          return (
            <CheckboxInputContainer
              key={index}
              onClick={() => checkboxHandler(item, checkboxName)}
              isChecked={isChecked}
              full={isFullWidth}
              large={isFullWidth}
              third={isThirdWidth}
            >
              <input
                name={item.text}
                type={currentQuestion.type}
                checked={isChecked}
                onChange={() => checkboxHandler(item, checkboxName)}
              />
              <TranslateTextKey label name={name} textKey={item.text} style={{marginTop: 'auto', cursor: 'pointer'}} />
            </CheckboxInputContainer>
          );
        })}
      </ResponseContainer>
    );
  }
};

export const UserList: React.FC<ListProps> = ({ response, currentQuestion, currentResults, language}) => {

  const isResource = currentQuestion.context === PRE && currentQuestion.id === 9;
  const forSomeoneElse = currentResults['seekingHelpFor'] === 25;
  const quitAll = currentResults.needHelpWith && currentResults.needHelpWith.length > 1;
  const quitKey = (param: any) => currentResults.needHelpWith.includes(param);
  const dynamic = currentQuestion.dynamicLinks;
  
  //const englishResponses = [response[0].link, response[1].link]; //, response[2].link, response[3].link];
  //const spanishResponses = [response[0].linkSp, response[1].linkSp]; //, response[2].linkSp, response[3].linkSp];
  //const responses = language === 'en' ? englishResponses : spanishResponses;
  
  return (
    <React.Fragment>
      <UnorderedListContainer half={isResource}>
        {!dynamic &&
          response.map((item, index: number) => {
            if (item.listType === PHONE) {
              // swap link based on language
              const telHref = language === 'en' ? item.link.en.mobile : item.link.es.mobile;

              return (
                <ListItemContainer key={index} href={`tel:${telHref}`} clickCategory="phone" clickAction="Call" clickLabel={telHref}>
                  <LinkIconContainer>
                    <HiExternalLink size="30px" />
                  </LinkIconContainer>
                  <TranslateTextKey textKey={item.text} />
                </ListItemContainer>
              );
            } else if (item.listType === NONRESIDENT) {
              // swap link based on language
              const telHref = language === 'en' ? item.link.en.nonResident.mobile : item.link.es.nonResident.mobile;

              return (
                <ListItemContainer key={index} href={`tel:${telHref}`} clickCategory="phone" clickAction="Call" clickLabel={telHref}>
                  <LinkIconContainer>
                    <HiExternalLink size="30px" />
                  </LinkIconContainer>
                  <TranslateTextKey textKey={item.text} />
                </ListItemContainer>
              );
            } else {
              // default spanish link to english if not provided
              const hrefSp = item.linkSp ? item.linkSp : item.link;
              // swap link based on language
              const href = language === 'en' ? item.link : hrefSp;

              return (
                <ListItemContainer key={index} href={`/${href}`} half={isResource} clickCategory="call-to-action" clickAction={item.text} clickLabel={href}>
                  <LinkIconContainer>
                    <HiExternalLink size="30px" />
                  </LinkIconContainer>
                  <TranslateTextKey textKey={item.text} />
                </ListItemContainer>
              );
            }
          })}
        {dynamic && quitAll && !forSomeoneElse && (
          <ListItemContainer href={`/${response[0]}`} half={isResource} clickCategory="call-to-action" clickAction={response[0].text} clickLabel={response[0].link}>
            <LinkIconContainer>
              <HiExternalLink size="30px" />
            </LinkIconContainer>
            <TranslateTextKey textKey={response[0].text} />
          </ListItemContainer>
        )}
        {dynamic && !quitAll && quitKey(6) && !forSomeoneElse && (
          <React.Fragment>
            <ListItemContainer href={`/${response[1]}`} half={isResource} clickCategory="call-to-action" clickAction={response[1].text} clickLabel={response[1].link}>
              <LinkIconContainer>
                <HiExternalLink size="30px" />
              </LinkIconContainer>
              <TranslateTextKey textKey={response[1].text} />
            </ListItemContainer>
            {!forSomeoneElse && (
              <React.Fragment>
                <TranslateTextKey textKey={response[1].subtext} />
                <br />
                <br />
                <MobileNum>
                  <a href="sms:66819?&body=QuitSmoking" data-click-category="call-to-action" data-click-action='Text QuitSmoking' data-click-label='sms:66819?&body=QuitSmoking'>
                    <TranslateTextKey textKey={response[1].smsText} style={{margin: '10px 0px'}} />
                  </a>
                </MobileNum>
                <TranslateTextKey textKey={response[1].smsText} style={{margin: '10px 0px'}} />
              </React.Fragment>
            )}
          </React.Fragment>
        )}
        {dynamic && !quitAll && quitKey(7) && !forSomeoneElse && (
          <React.Fragment>
            <ListItemContainer href={`/${response[2]}`} half={isResource} clickCategory="call-to-action" clickAction={response[2].text} clickLabel={response[2].link}>
              <LinkIconContainer>
                <HiExternalLink size="30px" />
              </LinkIconContainer>
              <TranslateTextKey textKey={response[2].text} />
            </ListItemContainer>
            {!forSomeoneElse && (
              <React.Fragment>
                <TranslateTextKey textKey={response[2].subtext} />
                <br />
                <br />
                <MobileNum>
                  <a href="sms:66819?&body=QuitVaping" data-click-category="call-to-action" data-click-action='Text QuitVaping' data-click-label='sms:66819?&body=QuitVaping'>
                    <TranslateTextKey textKey={response[2].smsText} style={{margin: '10px 0px'}} />
                  </a>
                </MobileNum>
                <TranslateTextKey textKey={response[2].smsText} style={{margin: '10px 0px'}} />
                <br />
              </React.Fragment>
            )}
          </React.Fragment>
        )}
        {dynamic && !quitAll && quitKey(8) && !forSomeoneElse && (
          <ListItemContainer href={`/${response[3]}`} half={isResource} clickCategory="call-to-action" clickAction={response[3].text} clickLabel={response[3].link}>
            <LinkIconContainer>
              <HiExternalLink size="30px" />
            </LinkIconContainer>
            <TranslateTextKey textKey={response[3].text} />
          </ListItemContainer>
        )}
        {!dynamic && currentQuestion.enrollment && <TranslateTextKey center textKey={currentQuestion.enrollment} />}
        {!dynamic && currentQuestion.enrollment && (
          <DesktopNum>
            <TranslateTextKey textKey={currentQuestion.desktopPrompt} />
          </DesktopNum>
        )}
        {!dynamic && currentQuestion.enrollment && (
          <MobileNum>
            <TranslateTextKey textKey={currentQuestion.mobilePrompt} />
          </MobileNum>
        )}
      </UnorderedListContainer>
    </React.Fragment>
  );
};

interface IScheduler {
  items: string[];
  currentQuestion?: any;
  handleChange: (value: string) => void;
}

export const Scheduler: React.FC<IScheduler> = ({items, handleChange, currentQuestion}) => {
  return (
    <SelectContainer>
      <TranslateTextKey textKey={currentQuestion.text} />
      {currentQuestion.selectDate && (
        <DropdownSelect full defaultValue={'Select Date'} items={items} handleSelectChange={handleChange} />
      )}
      {currentQuestion.selectTime && (
        <DropdownSelect full defaultValue={'Select Time'} items={items} handleSelectChange={handleChange} />
      )}
    </SelectContainer>
  );
};