import { useState } from 'react'

interface Props {
  onInstall: () => void
}

export default function InstallPage({ onInstall }: Props) {
  const [step, setStep] = useState(1)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  
  const [config, setConfig] = useState({
    database: {
      type: 'sqlite',
      host: 'localhost',
      port: 3306,
      user: 'root',
      password: '',
      database: 'anticaptcha',
      sqlite: { path: './data/app.db' }
    },
    redis: {
      enabled: false,
      host: 'localhost',
      port: 6379,
      password: '',
      db: 0
    },
    admin: {
      username: 'admin',
      password: ''
    }
  })

  const handleSubmit = async () => {
    setLoading(true)
    setError('')

    try {
      const res = await fetch('/api/install', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config)
      })

      const data = await res.json()

      if (!res.ok) {
        setError(data.error || '安装失败')
        return
      }

      onInstall()
      window.location.href = '/'
    } catch {
      setError('网络错误')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="container" style={{ maxWidth: '600px', marginTop: '50px' }}>
      <div className="card">
        <h1 style={{ marginBottom: '8px' }}>AntiCaptcha 安装向导</h1>
        <p style={{ color: 'var(--text-muted)', marginBottom: '32px' }}>
          步骤 {step} / 3
        </p>

        {step === 1 && (
          <>
            <h2 className="mb-4">数据库配置</h2>
            
            <div className="form-group">
              <label className="label">数据库类型</label>
              <select 
                className="input"
                value={config.database.type}
                onChange={e => setConfig({
                  ...config,
                  database: { ...config.database, type: e.target.value }
                })}
              >
                <option value="sqlite">SQLite</option>
                <option value="mysql">MySQL</option>
              </select>
            </div>

            {config.database.type === 'sqlite' ? (
              <div className="form-group">
                <label className="label">数据库文件路径</label>
                <input
                  type="text"
                  className="input"
                  value={config.database.sqlite.path}
                  onChange={e => setConfig({
                    ...config,
                    database: {
                      ...config.database,
                      sqlite: { path: e.target.value }
                    }
                  })}
                />
              </div>
            ) : (
              <>
                <div className="grid grid-cols-2 gap-4">
                  <div className="form-group">
                    <label className="label">主机</label>
                    <input
                      type="text"
                      className="input"
                      value={config.database.host}
                      onChange={e => setConfig({
                        ...config,
                        database: { ...config.database, host: e.target.value }
                      })}
                    />
                  </div>
                  <div className="form-group">
                    <label className="label">端口</label>
                    <input
                      type="number"
                      className="input"
                      value={config.database.port}
                      onChange={e => setConfig({
                        ...config,
                        database: { ...config.database, port: Number(e.target.value) }
                      })}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="form-group">
                    <label className="label">用户名</label>
                    <input
                      type="text"
                      className="input"
                      value={config.database.user}
                      onChange={e => setConfig({
                        ...config,
                        database: { ...config.database, user: e.target.value }
                      })}
                    />
                  </div>
                  <div className="form-group">
                    <label className="label">密码</label>
                    <input
                      type="password"
                      className="input"
                      value={config.database.password}
                      onChange={e => setConfig({
                        ...config,
                        database: { ...config.database, password: e.target.value }
                      })}
                    />
                  </div>
                </div>

                <div className="form-group">
                  <label className="label">数据库名</label>
                  <input
                    type="text"
                    className="input"
                    value={config.database.database}
                    onChange={e => setConfig({
                      ...config,
                      database: { ...config.database, database: e.target.value }
                    })}
                  />
                </div>
              </>
            )}

            <button className="button" onClick={() => setStep(2)}>
              下一步
            </button>
          </>
        )}

        {step === 2 && (
          <>
            <h2 className="mb-4">Redis 配置（可选）</h2>

            <div className="form-group">
              <label className="flex gap-2 items-center">
                <input
                  type="checkbox"
                  checked={config.redis.enabled}
                  onChange={e => setConfig({
                    ...config,
                    redis: { ...config.redis, enabled: e.target.checked }
                  })}
                />
                启用 Redis
              </label>
            </div>

            {config.redis.enabled && (
              <>
                <div className="grid grid-cols-2 gap-4">
                  <div className="form-group">
                    <label className="label">主机</label>
                    <input
                      type="text"
                      className="input"
                      value={config.redis.host}
                      onChange={e => setConfig({
                        ...config,
                        redis: { ...config.redis, host: e.target.value }
                      })}
                    />
                  </div>
                  <div className="form-group">
                    <label className="label">端口</label>
                    <input
                      type="number"
                      className="input"
                      value={config.redis.port}
                      onChange={e => setConfig({
                        ...config,
                        redis: { ...config.redis, port: Number(e.target.value) }
                      })}
                    />
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                  <div className="form-group">
                    <label className="label">密码</label>
                    <input
                      type="password"
                      className="input"
                      value={config.redis.password}
                      onChange={e => setConfig({
                        ...config,
                        redis: { ...config.redis, password: e.target.value }
                      })}
                    />
                  </div>
                  <div className="form-group">
                    <label className="label">数据库</label>
                    <input
                      type="number"
                      className="input"
                      value={config.redis.db}
                      onChange={e => setConfig({
                        ...config,
                        redis: { ...config.redis, db: Number(e.target.value) }
                      })}
                    />
                  </div>
                </div>
              </>
            )}

            <div className="flex gap-2">
              <button className="button button-secondary" onClick={() => setStep(1)}>
                上一步
              </button>
              <button className="button" onClick={() => setStep(3)}>
                下一步
              </button>
            </div>
          </>
        )}

        {step === 3 && (
          <>
            <h2 className="mb-4">管理员账号</h2>

            <div className="form-group">
              <label className="label">用户名</label>
              <input
                type="text"
                className="input"
                value={config.admin.username}
                onChange={e => setConfig({
                  ...config,
                  admin: { ...config.admin, username: e.target.value }
                })}
              />
            </div>

            <div className="form-group">
              <label className="label">密码</label>
              <input
                type="password"
                className="input"
                value={config.admin.password}
                onChange={e => setConfig({
                  ...config,
                  admin: { ...config.admin, password: e.target.value }
                })}
                placeholder="请输入管理员密码"
              />
            </div>

            {error && <div className="error">{error}</div>}

            <div className="flex gap-2">
              <button className="button button-secondary" onClick={() => setStep(2)}>
                上一步
              </button>
              <button 
                className="button" 
                onClick={handleSubmit}
                disabled={loading}
              >
                {loading ? '安装中...' : '完成安装'}
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  )
}