import { useEffect, useState } from 'react'
import { api, type RepoConfig, type Task } from '@/api'
import { TASK_TYPE } from '@/constants'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
import { Field } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Modal } from '@/components/ui/modal'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'

function parseRepoConfig(task?: Partial<Task>): Partial<RepoConfig> {
  try {
    if (task?.config) {
      const cfg = JSON.parse(task.config)
      return cfg.repo || cfg || {}
    }
  } catch {
    // ignore
  }
  return {}
}

export function RepoDialog({
  open,
  task,
  isEdit,
  onClose,
  onSaved,
}: {
  open: boolean
  task?: Partial<Task>
  isEdit: boolean
  onClose: () => void
  onSaved: () => void
}) {
  const [name, setName] = useState('')
  const [remark, setRemark] = useState('')
  const [schedule, setSchedule] = useState('0 0 0 * * *')
  const [enabled, setEnabled] = useState(true)
  const [repo, setRepo] = useState<Partial<RepoConfig>>({
    source_type: 'git',
    source_url: '',
    target_path: '',
    branch: 'main',
    sparse_path: '',
    single_file: false,
    proxy: '',
    proxy_url: '',
    auth_token: '',
    auto_add_cron: true,
    whitelist_paths: '',
    blacklist: '',
    extensions: '',
    dependence: '',
    concurrency: 1,
    commenttotask: '',
  })
  const [showAdvanced, setShowAdvanced] = useState(false)
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (!open) return
    setError('')
    setName(task?.name || '')
    setRemark(task?.remark || '')
    setSchedule(task?.schedule || '0 0 0 * * *')
    setEnabled(task?.enabled !== false)
    const parsed = parseRepoConfig(task)
    setRepo({
      source_type: 'git',
      branch: 'main',
      auto_add_cron: true,
      single_file: false,
      concurrency: 1,
      whitelist_paths: '',
      blacklist: '',
      extensions: '',
      dependence: '',
      commenttotask: '',
      ...parsed,
    })
    setShowAdvanced(
      !!(
        parsed.whitelist_paths ||
        parsed.blacklist ||
        parsed.extensions ||
        parsed.dependence ||
        parsed.commenttotask ||
        (parsed.concurrency && parsed.concurrency !== 1) ||
        parsed.single_file
      ),
    )
  }, [open, task])

  function patchRepo<K extends keyof RepoConfig>(key: K, value: RepoConfig[K]) {
    setRepo((r) => ({ ...r, [key]: value }))
  }

  async function save() {
    if (!name.trim()) {
      setError('请填写任务名称')
      return
    }
    if (!repo.source_url?.trim()) {
      setError('请填写仓库地址')
      return
    }
    setSaving(true)
    setError('')
    try {
      const config = JSON.stringify({
        ...(task?.config ? (() => { try { return JSON.parse(task.config!) } catch { return {} } })() : {}),
        repo,
      })
      const payload: Partial<Task> = {
        ...task,
        name: name.trim(),
        remark,
        schedule,
        enabled,
        type: TASK_TYPE.REPO,
        trigger_type: 'cron',
        command: `repo-sync:${repo.source_url}`,
        config,
      }
      if (isEdit && task?.id) {
        await api.tasks.update(task.id, payload)
      } else {
        await api.tasks.create(payload)
      }
      onSaved()
      onClose()
    } catch (e: any) {
      setError(e?.message || '保存失败')
    } finally {
      setSaving(false)
    }
  }

  return (
    <Modal
      open={open}
      title={isEdit ? '编辑仓库任务' : '新建仓库同步'}
      onClose={onClose}
      size="lg"
      footer={
        <>
          <Button variant="secondary" onClick={onClose}>
            取消
          </Button>
          <Button onClick={save} disabled={saving}>
            {saving ? '保存中...' : '保存'}
          </Button>
        </>
      }
    >
      {error ? <div className="rounded-md bg-[color-mix(in_srgb,var(--danger)_14%,transparent)] px-3 py-2 text-sm text-[var(--danger)]">{error}</div> : null}
      <Field label="任务名称">
        <Input value={name} onChange={(e) => setName(e.target.value)} />
      </Field>
      <Field label="备注">
        <Input value={remark} onChange={(e) => setRemark(e.target.value)} />
      </Field>
      <Field label="仓库地址">
        <Input value={repo.source_url || ''} onChange={(e) => patchRepo('source_url', e.target.value)} placeholder="https://github.com/user/repo.git" />
      </Field>
      <div className="grid gap-3 sm:grid-cols-2">
        <Field label="分支">
          <Input value={repo.branch || ''} onChange={(e) => patchRepo('branch', e.target.value)} />
        </Field>
        <Field label="目标路径">
          <Input value={repo.target_path || ''} onChange={(e) => patchRepo('target_path', e.target.value)} placeholder="可选" />
        </Field>
      </div>
      <Field label="Sparse 路径">
        <Input value={repo.sparse_path || ''} onChange={(e) => patchRepo('sparse_path', e.target.value)} placeholder="可选，稀疏检出路径" />
      </Field>
      <Field label="Auth Token">
        <Input value={repo.auth_token || ''} onChange={(e) => patchRepo('auth_token', e.target.value)} placeholder="私有仓库 Token" />
      </Field>
      <Field label="代理 URL">
        <Input value={repo.proxy_url || ''} onChange={(e) => patchRepo('proxy_url', e.target.value)} placeholder="可选" />
      </Field>
      <Field label="Cron">
        <Input value={schedule} onChange={(e) => setSchedule(e.target.value)} />
      </Field>
      <div className="flex items-center gap-2 text-sm">
        <Checkbox checked={!!repo.auto_add_cron} onCheckedChange={(v) => patchRepo('auto_add_cron', v)} />
        <span>同步后自动添加定时任务</span>
      </div>
      <div className="flex items-center gap-2 text-sm">
        <Checkbox checked={!!repo.single_file} onCheckedChange={(v) => patchRepo('single_file', v)} />
        <span>单文件模式</span>
      </div>
      <button
        type="button"
        className="text-left text-sm text-[var(--text-secondary)] hover:text-[var(--text-primary)]"
        onClick={() => setShowAdvanced((v) => !v)}
      >
        {showAdvanced ? '收起高级配置' : '展开高级配置（白/黑名单、扩展名、并发等）'}
      </button>
      {showAdvanced ? (
        <div className="space-y-3 rounded-md border border-[var(--border)] p-3">
          <Field label="白名单路径">
            <Textarea
              value={repo.whitelist_paths || ''}
              onChange={(e) => patchRepo('whitelist_paths', e.target.value)}
              placeholder="多行或逗号分隔，仅同步匹配路径"
            />
          </Field>
          <Field label="黑名单">
            <Textarea
              value={repo.blacklist || ''}
              onChange={(e) => patchRepo('blacklist', e.target.value)}
              placeholder="排除路径/文件，多行或逗号分隔"
            />
          </Field>
          <Field label="扩展名过滤">
            <Input
              value={repo.extensions || ''}
              onChange={(e) => patchRepo('extensions', e.target.value)}
              placeholder="例如 js,py,sh（留空不限）"
            />
          </Field>
          <Field label="依赖保留 / 说明">
            <Textarea
              value={repo.dependence || ''}
              onChange={(e) => patchRepo('dependence', e.target.value)}
              placeholder="可选，依赖安装说明或保留策略"
            />
          </Field>
          <Field label="注释转任务">
            <Input
              value={repo.commenttotask || ''}
              onChange={(e) => patchRepo('commenttotask', e.target.value)}
              placeholder="可选，脚本注释解析规则"
            />
          </Field>
          <Field label="并发数">
            <Input
              type="number"
              min={1}
              value={String(repo.concurrency ?? 1)}
              onChange={(e) => patchRepo('concurrency', Math.max(1, Number(e.target.value) || 1))}
            />
          </Field>
        </div>
      ) : null}
      <div className="flex items-center justify-between rounded-md border border-[var(--border)] px-3 py-2">
        <span className="text-sm">启用</span>
        <Switch checked={enabled} onCheckedChange={setEnabled} />
      </div>
    </Modal>
  )
}
