/**
 * 流水线配置页面
 */
import { useState, useEffect } from 'react'
import { View, Text, ScrollView, Input, Switch } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { AtButton, AtSwitch, AtTag, AtActivityIndicator, AtInput, AtModal } from 'taro-ui'
import {
  getPipelineConfig,
  updatePipelineConfig,
  addEnvVar,
  deleteEnvVar,
  getBranches,
} from '../../../../api/cicd'
import type { PipelineConfig, BranchRule, EnvVar } from '../../../../types/cicd'
import './pipeline.scss'

export default function Pipeline() {
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [config, setConfig] = useState<PipelineConfig>({})
  const [branches, setBranches] = useState<string[]>([])
  const [showEnvModal, setShowEnvModal] = useState(false)
  const [newEnvKey, setNewEnvKey] = useState('')
  const [newEnvValue, setNewEnvValue] = useState('')
  const [newEnvSecret, setNewEnvSecret] = useState(false)
  const [appId, setAppId] = useState('')

  useEffect(() => {
    const pages = Taro.getCurrentPages()
    const current = pages[pages.length - 1]
    if (current?.options?.appId) {
      setAppId(current.options.appId)
    }
  }, [])

  useEffect(() => {
    if (appId) {
      fetchConfig()
      fetchBranches()
    }
  }, [appId])

  // 获取流水线配置
  const fetchConfig = async () => {
    try {
      const res = await getPipelineConfig(Number(appId))
      if (res.data) {
        setConfig(res.data)
      }
    } catch (err) {
      console.error('获取流水线配置失败', err)
    } finally {
      setLoading(false)
    }
  }

  // 获取分支列表
  const fetchBranches = async () => {
    try {
      const res = await getBranches(Number(appId))
      if (res.data) {
        setBranches(res.data.branches || [])
      }
    } catch (err) {
      console.error('获取分支列表失败', err)
    }
  }

  // 更新配置
  const handleUpdateConfig = async () => {
    try {
      setSaving(true)
      await updatePipelineConfig({
        ...config,
        websiteId: Number(appId),
      })
      Taro.showToast({ title: '保存成功', icon: 'success' })
    } catch (err) {
      Taro.showToast({ title: '保存失败', icon: 'none' })
    } finally {
      setSaving(false)
    }
  }

  // 添加环境变量
  const handleAddEnvVar = async () => {
    if (!newEnvKey.trim()) {
      Taro.showToast({ title: '请输入变量名', icon: 'none' })
      return
    }

    try {
      await addEnvVar(Number(appId), {
        key: newEnvKey,
        value: newEnvValue,
        isSecret: newEnvSecret,
      })
      Taro.showToast({ title: '添加成功', icon: 'success' })
      setShowEnvModal(false)
      setNewEnvKey('')
      setNewEnvValue('')
      setNewEnvSecret(false)
      fetchConfig()
    } catch (err) {
      Taro.showToast({ title: '添加失败', icon: 'none' })
    }
  }

  // 删除环境变量
  const handleDeleteEnvVar = (key: string) => {
    Taro.showModal({
      title: '确认删除',
      content: `确定要删除环境变量 ${key} 吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            await deleteEnvVar(Number(appId), key)
            Taro.showToast({ title: '删除成功', icon: 'success' })
            fetchConfig()
          } catch (err) {
            Taro.showToast({ title: '删除失败', icon: 'none' })
          }
        }
      },
    })
  }

  // 复制环境变量值
  const handleCopyEnvValue = (value: string) => {
    Taro.setClipboardData({ data: value })
    Taro.showToast({ title: '已复制', icon: 'success' })
  }

  if (loading) {
    return (
      <View className="pipeline-page loading-wrap">
        <AtActivityIndicator size={32} />
        <Text className="loading-text">加载中...</Text>
      </View>
    )
  }

  return (
    <View className="pipeline-page">
      <ScrollView scrollY className="pipeline-content">
        {/* 基础配置 */}
        <View className="config-section">
          <Text className="section-title">基础配置</Text>

          <View className="config-item">
            <View className="item-info">
              <Text className="item-label">启用流水线</Text>
              <Text className="item-desc">开启后支持自动构建和部署</Text>
            </View>
            <Switch
              checked={config.enabled}
              onChange={(e) => setConfig({ ...config, enabled: e.detail.value })}
              color="#1890ff"
            />
          </View>

          <View className="config-item">
            <View className="item-info">
              <Text className="item-label">自动部署</Text>
              <Text className="item-desc">构建成功后自动部署到对应环境</Text>
            </View>
            <Switch
              checked={config.autoDeploy}
              onChange={(e) => setConfig({ ...config, autoDeploy: e.detail.value })}
              color="#1890ff"
            />
          </View>
        </View>

        {/* 分支规则 */}
        <View className="config-section">
          <View className="section-header">
            <Text className="section-title">分支规则</Text>
            <AtButton size="small" type="primary">
              添加规则
            </AtButton>
          </View>

          {config.branchRules && config.branchRules.length > 0 ? (
            config.branchRules.map((rule, index) => (
              <View className="rule-item" key={index}>
                <View className="rule-info">
                  <View className="rule-branch">
                    <Text className="iconfont icon-git-branch" />
                    <Text>{rule.branch || 'main'}</Text>
                  </View>
                  <View className="rule-tags">
                    {rule.autoBuild && <AtTag size="small">自动构建</AtTag>}
                    {rule.autoDeploy && <AtTag size="small" type="success">自动部署</AtTag>}
                    {rule.requireApproval && <AtTag size="small" type="warning">需要审批</AtTag>}
                  </View>
                </View>
                <Text className="rule-env">
                  {rule.deployEnv === 'development' ? '开发' : rule.deployEnv === 'staging' ? '预发布' : '生产'}
                </Text>
              </View>
            ))
          ) : (
            <View className="empty-rules">
              <Text className="iconfont icon-empty" />
              <Text>暂无分支规则</Text>
            </View>
          )}
        </View>

        {/* 环境变量 */}
        <View className="config-section">
          <View className="section-header">
            <Text className="section-title">环境变量</Text>
            <AtButton size="small" type="primary" onClick={() => setShowEnvModal(true)}>
              添加变量
            </AtButton>
          </View>

          {config.environmentVars && config.environmentVars.length > 0 ? (
            <View className="env-list">
              {config.environmentVars.map((env, index) => (
                <View className="env-item" key={index}>
                  <View className="env-info">
                    <View className="env-key">
                      <Text className="key">{env.key}</Text>
                      {env.isSecret && <AtTag size="small" type="warning">加密</AtTag>}
                    </View>
                    <Text
                      className="env-value"
                      onClick={() => !env.isSecret && env.value && handleCopyEnvValue(env.value)}
                    >
                      {env.isSecret ? '******' : env.value}
                    </Text>
                  </View>
                  <Text
                    className="env-delete iconfont icon-delete"
                    onClick={() => env.key && handleDeleteEnvVar(env.key)}
                  />
                </View>
              ))}
            </View>
          ) : (
            <View className="empty-envs">
              <Text className="iconfont icon-empty" />
              <Text>暂无环境变量</Text>
            </View>
          )}
        </View>

        {/* Webhook 配置 */}
        <View className="config-section">
          <View className="section-header">
            <Text className="section-title">Webhook 配置</Text>
            <AtButton size="small" type="primary">
              添加 Webhook
            </AtButton>
          </View>

          {config.webhooks && config.webhooks.length > 0 ? (
            <View className="webhook-list">
              {config.webhooks.map((webhook, index) => (
                <View className="webhook-item" key={index}>
                  <View className="webhook-info">
                    <Text className="webhook-url">{webhook.url}</Text>
                    <View className="webhook-tags">
                      {webhook.enabled ? (
                        <AtTag size="small" type="success">启用</AtTag>
                      ) : (
                        <AtTag size="small">禁用</AtTag>
                      )}
                      {webhook.events?.map((event, i) => (
                        <AtTag key={i} size="small" type="primary">{event}</AtTag>
                      ))}
                    </View>
                  </View>
                </View>
              ))}
            </View>
          ) : (
            <View className="empty-webhooks">
              <Text className="iconfont icon-empty" />
              <Text>暂无 Webhook</Text>
            </View>
          )}
        </View>
      </ScrollView>

      {/* 保存按钮 */}
      <View className="save-bar">
        <AtButton
          type="primary"
          loading={saving}
          onClick={handleUpdateConfig}
        >
          保存配置
        </AtButton>
      </View>

      {/* 添加环境变量弹窗 */}
      <AtModal
        isOpened={showEnvModal}
        title="添加环境变量"
        cancelText="取消"
        confirmText="添加"
        onClose={() => setShowEnvModal(false)}
        onCancel={() => setShowEnvModal(false)}
        onConfirm={handleAddEnvVar}
        content={
          <View className="env-modal-content">
            <View className="modal-item">
              <Text className="modal-label">变量名 *</Text>
              <Input
                className="modal-input"
                placeholder="如: API_KEY"
                value={newEnvKey}
                onInput={(e) => setNewEnvKey(e.detail.value)}
              />
            </View>
            <View className="modal-item">
              <Text className="modal-label">变量值</Text>
              <Input
                className="modal-input"
                placeholder="变量对应的值"
                value={newEnvValue}
                onInput={(e) => setNewEnvValue(e.detail.value)}
              />
            </View>
            <View className="modal-item">
              <View className="modal-switch">
                <Text className="modal-label">加密存储</Text>
                <AtSwitch
                  checked={newEnvSecret}
                  onChange={(e) => setNewEnvSecret(e.detail.value)}
                  size="small"
                />
              </View>
              <Text className="modal-hint">加密后值将不可见</Text>
            </View>
          </View>
        }
      />
    </View>
  )
}
