import { useEffect, useState } from 'react'
import type {
  Connection,
  ConnectionCreateRequest,
  ConnectionModalSubmitPayload,
  SessionTreeFolderOption,
} from '../types'
import Modal from './Modal'

const emptyForm: ConnectionCreateRequest = {
  name: '',
  host: '',
  port: 22,
  username: 'root',
  authType: 'PASSWORD',
  password: '',
  privateKey: '',
  passphrase: '',
  setupMode: 'NONE',
  bootstrapPassword: '',
}

export default function ConnectionModal({
  open,
  connection,
  folderOptions,
  initialTargetFolderId,
  onClose,
  onSubmit,
}: {
  open: boolean
  connection?: Connection | null
  folderOptions: SessionTreeFolderOption[]
  initialTargetFolderId: string | null
  onClose: () => void
  onSubmit: (payload: ConnectionModalSubmitPayload) => Promise<void>
}) {
  const [form, setForm] = useState<ConnectionCreateRequest>(emptyForm)
  const [targetFolderId, setTargetFolderId] = useState<string | null>(null)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  useEffect(() => {
    if (!open) return
    if (connection) {
      setForm({
        name: connection.name,
        host: connection.host,
        port: connection.port,
        username: connection.username,
        authType: connection.authType,
        password: '',
        privateKey: '',
        passphrase: '',
        setupMode: 'NONE',
        bootstrapPassword: '',
      })
    } else {
      setForm(emptyForm)
    }
    setTargetFolderId(initialTargetFolderId)
    setError(null)
  }, [connection, initialTargetFolderId, open])

  if (!open) return null

  const useBootstrap = form.setupMode === 'PASSWORD_BOOTSTRAP'
  const isPassword = form.authType === 'PASSWORD'

  async function handleSave() {
    setSubmitting(true)
    setError(null)
    try {
      await onSubmit({
        ...form,
        port: Number(form.port || 22),
        targetFolderId,
      })
    } catch (err) {
      const message =
        (err as { response?: { data?: { message?: string; error?: string } } }).response?.data?.message || '保存连接失败'
      setError(message)
    } finally {
      setSubmitting(false)
    }
  }

  return (
    <Modal
      title={connection ? '编辑 SSH 连接' : '新建 SSH 连接'}
      onClose={onClose}
      maxWidth="max-w-2xl"
      footer={
        <>
          <button className="rounded-xl bg-surface-muted px-4 py-2 text-sm text-content-muted transition hover:bg-surface-panel hover:text-content-main" onClick={onClose}>
            取消
          </button>
          <button
            className="rounded-xl bg-blue-600 px-4 py-2 text-sm text-white transition hover:bg-blue-500 disabled:opacity-60"
            disabled={submitting}
            onClick={handleSave}
          >
            {submitting ? '保存中...' : connection ? '保存修改' : '保存并连接'}
          </button>
        </>
      }
    >
      <div className="grid gap-4 md:grid-cols-2">
        <label className="space-y-2">
          <span className="text-sm text-content-muted">连接名称</span>
          <input
            className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
            placeholder="例如：prod-web-01"
            value={form.name}
            onChange={(e) => setForm((prev) => ({ ...prev, name: e.target.value }))}
          />
        </label>
        <label className="space-y-2">
          <span className="text-sm text-content-muted">分组 / 父文件夹</span>
          <select
            className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
            value={targetFolderId ?? '__ROOT__'}
            onChange={(event) => setTargetFolderId(event.target.value === '__ROOT__' ? null : event.target.value)}
          >
            <option value="__ROOT__">根目录</option>
            {folderOptions.map((option) => (
              <option key={option.id} value={option.id}>
                {`${'— '.repeat(option.depth)}${option.name}`}
              </option>
            ))}
          </select>
        </label>
      </div>

      <div className="mt-4 grid gap-4 md:grid-cols-[minmax(0,1.4fr)_120px_minmax(0,1fr)]">
        <label className="space-y-2">
          <span className="text-sm text-content-muted">主机 IP</span>
          <input
            className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
            value={form.host}
            onChange={(e) => setForm((prev) => ({ ...prev, host: e.target.value }))}
          />
        </label>
        <label className="space-y-2">
          <span className="text-sm text-content-muted">端口</span>
          <input
            type="number"
            className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
            value={form.port ?? 22}
            onChange={(e) => setForm((prev) => ({ ...prev, port: Number(e.target.value) }))}
          />
        </label>
        <label className="space-y-2">
          <span className="text-sm text-content-muted">用户名</span>
          <input
            className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
            value={form.username}
            onChange={(e) => setForm((prev) => ({ ...prev, username: e.target.value }))}
          />
        </label>
      </div>

      <div className="mt-6 rounded-[28px] border border-border-main bg-surface-muted/30 p-5">
        <div className="mb-4">
          <div className="text-sm font-medium text-content-main">认证方式</div>
          <div className="mt-1 text-xs text-content-dim">保留现有密码、私钥和一键免密部署能力。</div>
        </div>

        <div className="flex flex-wrap gap-3">
          <button
            className={`rounded-2xl border px-4 py-2 text-sm ${isPassword ? 'border-blue-500 bg-blue-500/10 text-blue-400' : 'border-border-main bg-surface-panel text-content-muted'}`}
            onClick={() => setForm((prev) => ({ ...prev, authType: 'PASSWORD', setupMode: prev.setupMode === 'PASSWORD_BOOTSTRAP' ? 'PASSWORD_BOOTSTRAP' : 'NONE' }))}
          >
            密码认证
          </button>
          <button
            className={`rounded-2xl border px-4 py-2 text-sm ${form.authType === 'PRIVATE_KEY' ? 'border-blue-500 bg-blue-500/10 text-blue-400' : 'border-border-main bg-surface-panel text-content-muted'}`}
            onClick={() => setForm((prev) => ({ ...prev, authType: 'PRIVATE_KEY', setupMode: 'NONE' }))}
          >
            私钥认证
          </button>
          <button
            className={`rounded-2xl border px-4 py-2 text-sm ${useBootstrap ? 'border-emerald-500 bg-emerald-500/10 text-emerald-400' : 'border-border-main bg-surface-panel text-content-muted'}`}
            onClick={() => setForm((prev) => ({ ...prev, authType: 'PASSWORD', setupMode: prev.setupMode === 'PASSWORD_BOOTSTRAP' ? 'NONE' : 'PASSWORD_BOOTSTRAP' }))}
          >
            一键免密部署
          </button>
        </div>

        {form.authType === 'PASSWORD' ? (
          <label className="block mt-4 space-y-2">
            <span className="text-sm text-content-muted">{useBootstrap ? '引导密码' : '密码'}</span>
            <input
              type="password"
              className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
              value={useBootstrap ? form.bootstrapPassword ?? '' : form.password ?? ''}
              onChange={(e) =>
                setForm((prev) =>
                  useBootstrap ? { ...prev, bootstrapPassword: e.target.value } : { ...prev, password: e.target.value },
                )
              }
            />
          </label>
        ) : (
          <div className="mt-4 space-y-4">
            <label className="block space-y-2">
              <span className="text-sm text-content-muted">私钥内容</span>
              <textarea
                rows={6}
                className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 font-mono text-sm text-content-main outline-none focus:border-blue-500"
                value={form.privateKey ?? ''}
                onChange={(e) => setForm((prev) => ({ ...prev, privateKey: e.target.value }))}
              />
            </label>
            <label className="block space-y-2">
              <span className="text-sm text-content-muted">私钥口令</span>
              <input
                type="password"
                className="w-full rounded-2xl border border-border-main bg-surface-muted px-4 py-3 text-content-main outline-none focus:border-blue-500"
                value={form.passphrase ?? ''}
                onChange={(e) => setForm((prev) => ({ ...prev, passphrase: e.target.value }))}
              />
            </label>
          </div>
        )}
      </div>

      {error ? <div className="mt-4 rounded-xl border border-red-500/20 bg-red-500/10 px-4 py-3 text-sm text-red-400">{error}</div> : null}
    </Modal>
  )
}
