import React, {FC, useEffect, useState} from 'react';
import { Select } from '../Select';
import { DateRangePickerModal } from '../Pickers';
import { Switch } from '../Switch';
import { Link } from '../Link';
import { TimeFrameProps } from './TimeFrame.types';
import { Pill } from '../Pill';
import { useLocale } from '../../hooks/useLocale';

import "./styles.scss"
import { Label } from '../Label';

import { TimePickerInputs } from '../Pickers/TimePicker/TimePickerInputs';
import { AssistiveText } from '../AssistiveText';


export const TimeFrame: FC<TimeFrameProps> = ({
  label,
  option,
  onChangeSelect,
  options = [],
  placeholder = "",
  isRequired = false,
  requiredMessage = "",
  titleStyles,
  customWithTwoMonths = true,
  withTime = true,
  startDate,
  endDate,
  minDate,
  maxDate,
  customRangeDate,
  onChangeDateRange,
  onChangeTime,
  advancedFilter,
  setAdvancedFilter,
  dateFormat,
  filterSwitch = true,
  onAdvancedFilter,
  className,
  componentClassName,
  style,
  isValid,
  setIsValid,
  openDateRangePickerModalAutomatically = true
}) => {
  const [showPill, setShowPill] = useState(true)
  const [showTimeError, setShowTimeError] = useState(false)

  const timeErrorMessage = useLocale("same_time_or_after_validation")

  switch (dateFormat) {
    case "m/d/Y":
        dateFormat = "MM/DD/YYYY hh:mm A"
        break;
    case "d/m/Y":
        dateFormat = "DD/MM/YYYY hh:mm A"
        break;
    case "Y/m/d":
        dateFormat = "YYYY/MM/DD hh:mm A"
        break;
    default:
  }

  return (
    <div className={`gtc-rc-timeframe ${componentClassName}`} style={style}>
      {label && 
        <>
          <Label>{label}</Label>
          { isRequired &&
            <span style={{color: "red", fontSize: "12px"}}> *</span>
          }
        </>
      }
      <Select
        name="timeframe"
        style={{marginTop: "9px"}}
        className={!isValid && isRequired ? "gtc-rc-invalid-select" : className}
        placeholder={placeholder}
        //label={props.label}
        //value={option?.id == "custom" ? option : []}
        value={option}
        onChange={(e) => {
          onChangeSelect(e)
          setShowPill(true)
          if (isRequired && !isValid) {
            setIsValid(true)
          }
        }}
        isSearchable
        options={options}
        textField="label"
        valueField="id"
        onSelectAll={() => {}}
      />
      { !isValid && isRequired &&
        <AssistiveText warning>{requiredMessage}</AssistiveText>
      }
      {option && option.id != "custom" &&
        <div 
          style={{
            width: "100%", 
            marginTop: "5px", 
            display: "flex", 
            justifyContent: "center"
          }}
        >
          { showPill &&
          <Pill
            item={{label: `${startDate?.format(dateFormat)} - ${endDate?.format(dateFormat)}`, id: "selectedTimeRange", color: "default-green"}}
            icon="cancel"
            onClickIcon={() => {
              setShowPill(false); 
              onChangeSelect(null)
            }}
          />
          }
        </div>
      }
      {
        option && option.id === "custom" &&
        <div>
          <DateRangePickerModal
            style={{ paddingTop: "9px" }}
            startDate={startDate && startDate}
            endDate={endDate}
            minDate={minDate}
            maxDate={maxDate}
            customRangeDate={customRangeDate}
            onChange={(selectedStartDateMoment, selectedEndDateMoment, selectedStartDate, selectedEndDate) => {
              if ((selectedStartDateMoment.format("MM/DD/YY") != startDate?.format("MM/DD/YY")) || (selectedEndDateMoment.format("MM/DD/YY") != endDate?.format("MM/DD/YY"))){
                if (setAdvancedFilter) {
                  setAdvancedFilter(false);
                }
              }

              if (onChangeDateRange) {
                onChangeDateRange(selectedStartDateMoment, selectedEndDateMoment);
              }
            }}
            dateFormat={dateFormat}
            showTwoMonths={customWithTwoMonths}
            openDateRangePickerModalAutomatically={openDateRangePickerModalAutomatically}
          />
          <div 
            style={{
              width: "100%", 
              display: "flex", 
              flexDirection: "column",
              alignItems: "flex-start",
            }}
          >
            {filterSwitch && withTime && (startDate?.format("M/D/Y") != endDate?.format("M/D/Y")) &&
              <Switch
                style={{marginTop: "13px"}}
                checked={advancedFilter}
                id="switch-filter"
                label="advanced_filters"
                labelPosition="right"
                name="Advanced Filters"
                onChange={() => {     
                  setAdvancedFilter(!advancedFilter)
                }}
                size="small"
              />
            }

            {advancedFilter && withTime &&
              <div style={{marginTop: "15px"}}>
                <Link 
                  className="gtc-rc-timeframe-link" 
                  text={"advanced_filter_options"}
                  onClick={onAdvancedFilter}
                />
              </div>
            }
            {!advancedFilter && withTime &&
              <div 
                style={{
                  marginTop: "14px", 
                  width: "100%",
                }}
              >
                <div 
                  style={{
                      display: "flex",
                      justifyContent: "space-between"
                  }}
                >
                  <TimePickerInputs
                    label="start"
                    style={{
                      marginTop: "9px",
                      borderColor: showTimeError ? "red" : undefined
                    }}
                    value={startDate}
                    onChange={(startTime) => {
                      if(startDate){
                        onChangeTime(startTime.set({"second": 0}), null)
                        if((startTime.format("DD/MM/YYYY hh:mm:ss A") == endDate?.format("DD/MM/YYYY hh:mm:ss A")) || startTime?.isSameOrAfter(endDate)){
                          setShowTimeError(true)
                        } else {
                          setShowTimeError(false)
                          if (isRequired && !isValid) {
                            setIsValid(true)
                          }
                        }
                      }
                    }}
                  />

                  <TimePickerInputs
                    label="end"
                    style={{
                      marginTop: "9px", 
                      borderColor: showTimeError ? "red" : undefined
                    }}
                    value={endDate}
                    onChange={(endTime) => {
                      if(startDate){
                        onChangeTime(null, endTime.set({"second": 0}))
                        if((startDate?.format("DD/MM/YYYY hh:mm:ss A") == endTime?.format("DD/MM/YYYY hh:mm:ss A")) || startDate?.isSameOrAfter(endTime)){
                          setShowTimeError(true)
                        } else {
                          setShowTimeError(false)
                          if (isRequired && !isValid) {
                            setIsValid(true)
                          }
                        }
                      }
                    }}
                  />
                </div>
                { showTimeError &&
                  <AssistiveText warning>
                    {timeErrorMessage}
                  </AssistiveText>
                }
              </div>
            }
          </div>
        </div>
      }
    </div>
  )
};

export default TimeFrame;