import React, { useMemo, useEffect, useState } from 'react'
import { Select, DatePicker, Tooltip } from 'antd'
import dayjs from 'dayjs'

const { Option } = Select

// Utility: format JS Date to YYYY-MM-DD
const formatDateToYmd = date => {
  const year = date.getFullYear()
  const month = ('0' + (date.getMonth() + 1)).slice(-2)
  const day = ('0' + date.getDate()).slice(-2)
  return `${year}-${month}-${day}`
}

// Utility: compute date string based on range key (e.g., '3_days', '1_month', '1_year')
const computeArchiveDate = range => {
  if (!range || range === 'custom_date') return ''
  const parts = range.split('_')
  if (parts.length < 2) return ''
  const amount = parseInt(parts[0])
  const unit = parts[1]
  const currentDate = new Date()
  switch (unit) {
    case 'days':
      currentDate.setDate(currentDate.getDate() - amount)
      break
    case 'month':
    case 'months':
      currentDate.setMonth(currentDate.getMonth() - amount)
      break
    case 'year':
      currentDate.setFullYear(currentDate.getFullYear() - amount)
      break
    default:
      return ''
  }
  return formatDateToYmd(currentDate)
}

/**
 * ArchiveRangeSelect
 * Props:
 * - t: translation function
 * - defaultValue: initial range value
 * - value: controlled value (optional)
 * - onChange: (value, dateString) => void
 * - className: select class
 * - variant: 'onboarding' | 'settings' (controls translation keys)
 * - isPro: boolean (to apply pro locks) — optional; if not provided, derive from window.archm_admin.is_pro
 * - falshDoor: function to trigger upgrade popup when not pro
 * - includeCustomDate: boolean (show 'custom_date' option and DatePicker when selected)
 * - datePickerDefault: string (YYYY-MM-DD) default for DatePicker
 */
const ArchiveRangeSelect = ({
  t,
  defaultValue,
  value,
  onChange,
  className,
  variant = 'onboarding',
  isPro = true,
  falshDoor,
  includeCustomDate = false,
  datePickerDefault
}) => {
  const [proState, setProState] = useState(() => {
    if (typeof isPro === 'boolean') return isPro
    try {
      return (
        (typeof window !== 'undefined' && window.archm_admin?.is_pro == 1) ||
        false
      )
    } catch (e) {
      return false
    }
  })

  useEffect(() => {
    if (typeof isPro === 'boolean') {
      setProState(isPro)
    } else {
      try {
        setProState(
          (typeof window !== 'undefined' && window.archm_admin?.is_pro == 1) ||
            false
        )
      } catch (e) {
        setProState(false)
      }
    }
  }, [isPro])

  const labelScope = useMemo(
    () => (variant === 'settings' ? 'time_period' : 'archive_range_options'),
    [variant]
  )

  const handleChange = v => {
    const dateStr = v === 'custom_date' ? '' : computeArchiveDate(v)
    onChange && onChange(v, dateStr)
  }

  const handleDateChange = (_date, dateString) => {
    onChange && onChange('custom_date', dateString)
  }

  // Build base options list
  const options = [
    { value: '3_days' },
    { value: '7_days' },
    { value: '15_days' },
    { value: '1_month' },
    { value: '3_months' }
  ]

  return (
    <div className='arcm-flex arcm-items-center arcm-gap-3 arcm-flex-wrap'>
      <Select
        defaultValue={defaultValue}
        value={value}
        onChange={handleChange}
        className={className}
      >
        <Option value='default' disabled>
          {variant === 'settings'
            ? t('form.select_archive_range_placeholder')
            : t('select_archive_range')}
        </Option>

        {options.map(opt => (
          <Option key={opt.value} value={opt.value}>
            {t(`${labelScope}.${opt.value}`)}
          </Option>
        ))}

        {/* Pro-locked options */}
        {['6_months', '1_year'].map(v => (
          <Option key={v} value={v} disabled={!proState}>
            {t(`${labelScope}.${v}`)}
            {!proState && (
              <>
                <div
                  onClick={() => falshDoor && falshDoor()}
                  className='arcm-absolute arcm-w-full arcm-h-full arcm-inline-flex arcm-top-0 arcm-left-0'
                ></div>
                <button
                  onClick={e => {
                    e.stopPropagation()
                    falshDoor && falshDoor()
                  }}
                  className='arcm-ml-2 arcm-cursor-pointer arcm-px-1.5 btn-prolock arcm-inline-flex arcm-items-center arcm-pt-[3px] arcm-pb-[4px] arcm-bg-[#FFE9FE] arcm-rounded-[26px] arcm-text-[#4d1c4b] arcm-text-sm arcm-font-normal arcm-z-50'
                >
                  <span className='icon-wrap'>
                    <svg
                      xmlns='http://www.w3.org/2000/svg'
                      width='13'
                      height='11'
                      viewBox='0 0 13 11'
                      fill='none'
                    >
                      <path
                        d='M0.806113 7.65309C0.542977 5.94268 0.279841 4.23232 0.0167049 2.52191C-0.0416496 2.14276 0.389758 1.88417 0.696628 2.11434C1.51645 2.7292 2.33622 3.34402 3.15604 3.95889C3.42597 4.16133 3.81053 4.09545 3.99766 3.81471L6.04517 0.743421C6.26154 0.41886 6.73842 0.41886 6.95479 0.743421L9.0023 3.81471C9.18944 4.09545 9.574 4.16129 9.84392 3.95889C10.6637 3.34402 11.4835 2.7292 12.3033 2.11434C12.6102 1.88417 13.0416 2.14276 12.9833 2.52191C12.7202 4.23232 12.457 5.94268 12.1939 7.65309H0.806113Z'
                        fill='#F748F0'
                      />
                      <path
                        d='M11.6001 10.5H1.39974C1.07185 10.5 0.80603 10.2342 0.80603 9.90627V8.60205H12.1938V9.90627C12.1938 10.2342 11.9279 10.5 11.6001 10.5Z'
                        fill='#F748F0'
                      />
                    </svg>
                  </span>
                  <span className='text'>{t('button.upgrade')}</span>
                </button>
              </>
            )}
          </Option>
        ))}

        {includeCustomDate && (
          <Option value='custom_date' disabled={!proState}>
            {t(`${labelScope}.custom_date`)}
            {!proState && (
              <>
                <div
                  onClick={() => falshDoor && falshDoor()}
                  className='arcm-absolute arcm-w-full arcm-h-full arcm-inline-flex arcm-top-0 arcm-left-0'
                ></div>
                <button
                  onClick={e => {
                    e.stopPropagation()
                    falshDoor && falshDoor()
                  }}
                  className='arcm-ml-2 arcm-cursor-pointer arcm-px-1.5 btn-prolock arcm-inline-flex arcm-items-center arcm-pt-[3px] arcm-pb-[4px] arcm-bg-[#FFE9FE] arcm-rounded-[26px] arcm-text-[#4d1c4b] arcm-text-sm arcm-font-normal arcm-z-50'
                >
                  <span className='icon-wrap'>
                    <svg
                      xmlns='http://www.w3.org/2000/svg'
                      width='13'
                      height='11'
                      viewBox='0 0 13 11'
                      fill='none'
                    >
                      <path
                        d='M0.806113 7.65309C0.542977 5.94268 0.279841 4.23232 0.0167049 2.52191C-0.0416496 2.14276 0.389758 1.88417 0.696628 2.11434C1.51645 2.7292 2.33622 3.34402 3.15604 3.95889C3.42597 4.16133 3.81053 4.09545 3.99766 3.81471L6.04517 0.743421C6.26154 0.41886 6.73842 0.41886 6.95479 0.743421L9.0023 3.81471C9.18944 4.09545 9.574 4.16129 9.84392 3.95889C10.6637 3.34402 11.4835 2.7292 12.3033 2.11434C12.6102 1.88417 13.0416 2.14276 12.9833 2.52191C12.7202 4.23232 12.457 5.94268 12.1939 7.65309H0.806113Z'
                        fill='#F748F0'
                      />
                      <path
                        d='M11.6001 10.5H1.39974C1.07185 10.5 0.80603 10.2342 0.80603 9.90627V8.60205H12.1938V9.90627C12.1938 10.2342 11.9279 10.5 11.6001 10.5Z'
                        fill='#F748F0'
                      />
                    </svg>
                  </span>
                  <span className='text'>{t('button.upgrade')}</span>
                </button>
              </>
            )}
          </Option>
        )}
      </Select>

      {includeCustomDate &&
        (value === 'custom_date' || defaultValue === 'custom_date') && (
          <DatePicker
            className='arcm-min-w-full sm:arcm-min-w-[320px]'
            autoFocus={true}
            defaultValue={
              datePickerDefault
                ? dayjs(datePickerDefault, 'YYYY-MM-DD')
                : undefined
            }
            onChange={handleDateChange}
          />
        )}
    </div>
  )
}

export default ArchiveRangeSelect
