import { Checkbox, Modal, Space, Tag, Typography } from 'antd'
import { useEffect, useMemo, useState } from 'react'

import type { K8scalendarVersionLifecycle } from 'apiClient/services/devops/interface'

const { Text } = Typography

export const NOTIFICATION_FLAG_OPTIONS = [
  {
    value: 'notified_version_added_at',
    label: 'Version Added',
    field: 'notified_version_added_at' as const
  },
  {
    value: 'notified_eos_changed_fingerprint',
    label: 'EOS Changed',
    field: 'notified_eos_changed_fingerprint' as const
  },
  {
    value: 'eos_approaching_notified_for',
    label: 'EOS Approaching',
    field: 'eos_approaching_notified_for' as const
  }
] as const

export type NotificationFlagValue =
  (typeof NOTIFICATION_FLAG_OPTIONS)[number]['value']

export const getSetNotificationFlags = (
  record: K8scalendarVersionLifecycle
): NotificationFlagValue[] =>
  NOTIFICATION_FLAG_OPTIONS.filter((opt) => {
    const v = record[opt.field]
    return v !== undefined && v !== null && String(v).trim() !== ''
  }).map((opt) => opt.value)

type ResetNotificationModalProps = {
  record: K8scalendarVersionLifecycle | null
  loading: boolean
  onSubmit: (flags: NotificationFlagValue[]) => Promise<void>
  onCancel: () => void
}

const ResetNotificationModal = ({
  record,
  loading,
  onSubmit,
  onCancel
}: ResetNotificationModalProps) => {
  const setFlags = useMemo(
    () => (record ? getSetNotificationFlags(record) : []),
    [record]
  )

  const [selectedFlags, setSelectedFlags] = useState<NotificationFlagValue[]>(
    []
  )

  useEffect(() => {
    setSelectedFlags(setFlags)
  }, [record, setFlags])

  const handleOk = async () => {
    if (!record || selectedFlags.length === 0) return
    await onSubmit(selectedFlags)
  }

  return (
    <Modal
      visible={!!record}
      title="Reset Notification Flags"
      okText="Reset"
      okButtonProps={{
        disabled: selectedFlags.length === 0,
        loading
      }}
      onOk={handleOk}
      onCancel={onCancel}
      destroyOnClose
    >
      {record ? (
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <div>
            <Text type="secondary">Target</Text>
            <div>
              <Text strong>
                {record.cloud} / {record.version}
              </Text>
              {record.cloud_provider ? (
                <Text type="secondary"> ({record.cloud_provider})</Text>
              ) : null}
            </div>
          </div>

          {setFlags.length === 0 ? (
            <Text type="secondary">
              No notification markers are set for this version.
            </Text>
          ) : (
            <>
              <Text type="secondary">
                Select markers to clear (only set flags are listed):
              </Text>
              <Checkbox.Group
                style={{ width: '100%' }}
                value={selectedFlags}
                onChange={(values) =>
                  setSelectedFlags(values as NotificationFlagValue[])
                }
              >
                <Space direction="vertical">
                  {NOTIFICATION_FLAG_OPTIONS.filter((opt) =>
                    setFlags.includes(opt.value)
                  ).map((opt) => (
                    <Checkbox key={opt.value} value={opt.value}>
                      <Space size={8}>
                        <span>{opt.label}</span>
                        <Tag className="k8s-calendar-notify-flag-value">
                          {String(record[opt.field])}
                        </Tag>
                      </Space>
                    </Checkbox>
                  ))}
                </Space>
              </Checkbox.Group>
            </>
          )}
        </Space>
      ) : null}
    </Modal>
  )
}

export default ResetNotificationModal
