import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons'
import { Button, Form, Input, Table } from 'antd'
import TextArea from 'antd/lib/input/TextArea'
import { ColumnsType } from 'antd/lib/table'

import { MaintenanceClusterOpsMaintenanceWindowSlot } from 'apiClient/services/devops/interface'
import { ClusterSearchInput } from 'components/ResourceSearchInput/DevOps/ClusterSearchInput'
import { UserSearchInput } from 'components/ResourceSearchInput/DevOps/UserSearchInput'

export type ClusterOpsMaintenanceWindowFormValues = {
  approvers: string[]
  cluster_id: string
  windows: MaintenanceClusterOpsMaintenanceWindowSlot[]
}

type RenderClusterOpsMaintenanceWindowFormOptions = {
  editable: boolean
  initValues?: Partial<ClusterOpsMaintenanceWindowFormValues>
}

export const renderClusterOpsMaintenanceWindowForm = ({
  editable,
  initValues
}: RenderClusterOpsMaintenanceWindowFormOptions) => {
  type WindowField = {
    key: number
    name: number
    fieldKey?: number
  }

  return (
    <>
      <Form.Item
        name="cluster_id"
        label="Cluster ID"
        initialValue={initValues?.cluster_id}
        normalize={(nextValue?: string) => nextValue?.trim()}
        rules={[
          { required: true, message: 'Please input cluster id' },
          {
            pattern: /^[0-9]+$/,
            message: 'Please input pure-number cluster id'
          }
        ]}
      >
        <ClusterSearchInput disabled={!editable} />
      </Form.Item>
      <Form.Item
        name="approvers"
        label="Approvers"
        initialValue={initValues?.approvers || []}
        normalize={(nextValue?: string[]) =>
          (nextValue || []).map((item) => item.trim()).filter(Boolean)
        }
      >
        <UserSearchInput mode="multiple" placeholder="Search approver emails" />
      </Form.Item>
      <div style={{ fontWeight: 500, marginBottom: 4 }}>Windows</div>
      <div style={{ color: '#8c8c8c', marginBottom: 12 }}>
        Configure one or more maintenance windows.
      </div>
      <Form.List
        name="windows"
        rules={[
          {
            validator: async (_, windows) => {
              if (!windows || windows.length < 1) {
                return Promise.reject(
                  new Error('At least 1 window should be added')
                )
              }
            }
          }
        ]}
      >
        {(fields, { add, remove }, { errors }) => {
          const windowFields = fields as WindowField[]
          const columns: ColumnsType<WindowField> = [
            {
              title: (
                <div>
                  <div>Cron Spec (UTC+0)</div>
                  <div style={{ fontSize: 12, color: '#8c8c8c' }}>
                    Cron expression of window start time.
                  </div>
                </div>
              ),
              render: (_, field) => (
                <Form.Item
                  {...field}
                  name={[field.name, 'start_cron_spec']}
                  validateTrigger={['onChange', 'onBlur']}
                  rules={[
                    {
                      required: true,
                      whitespace: true,
                      message: 'Start cron spec is required'
                    }
                  ]}
                  style={{ marginBottom: 0, width: '100%' }}
                >
                  <Input
                    placeholder="e.g. 0 0 * * *"
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              ),
              width: '30%'
            },
            {
              title: (
                <div>
                  <div>Duration</div>
                  <div style={{ fontSize: 12, color: '#8c8c8c' }}>
                    {'String format of time.Duration, e.g. "1h", "50m".'}
                  </div>
                </div>
              ),
              render: (_, field) => (
                <Form.Item
                  {...field}
                  name={[field.name, 'duration']}
                  validateTrigger={['onChange', 'onBlur']}
                  rules={[
                    {
                      required: true,
                      whitespace: true,
                      message: 'Duration is required'
                    }
                  ]}
                  style={{ marginBottom: 0 }}
                >
                  <Input placeholder='e.g. "1h", "50m"' />
                </Form.Item>
              ),
              width: '30%'
            },
            {
              title: (
                <div>
                  <div>Description</div>
                  <div style={{ fontSize: 12, color: '#8c8c8c' }}>
                    Description of this maintenance window.
                  </div>
                </div>
              ),
              render: (_, field) => (
                <Form.Item
                  {...field}
                  name={[field.name, 'description']}
                  validateTrigger={['onChange', 'onBlur']}
                  style={{ marginBottom: 0, width: '100%' }}
                >
                  <TextArea
                    placeholder="Maintenance purpose / notes"
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              ),
              width: '40%'
            },
            {
              title: '',
              width: '10%',
              render: (_, field) => (
                <Button
                  type="text"
                  danger
                  icon={<MinusCircleOutlined />}
                  onClick={() => remove(field.name)}
                />
              )
            }
          ]

          return (
            <>
              <Table<WindowField>
                dataSource={windowFields}
                rowKey="key"
                pagination={false}
                size="small"
                tableLayout="fixed"
                columns={columns}
                style={{ width: '100%' }}
              />
              <Form.Item style={{ marginTop: 16, marginBottom: 0 }}>
                <Button
                  type="dashed"
                  onClick={() =>
                    add({
                      description: '',
                      start_cron_spec: '',
                      duration: ''
                    })
                  }
                  icon={<PlusOutlined />}
                >
                  Add window
                </Button>
              </Form.Item>
              <Form.ErrorList errors={errors} />
            </>
          )
        }}
      </Form.List>
    </>
  )
}
