import { useEffect, useState } from 'react'
import { useNavigate } from '@tanstack/react-router'
import { AlertCircle, CheckCircle, ChevronDown, ChevronRight, Database, Lock, Server, User } from 'lucide-react'
import { useInstall, useInstallStatus } from '@/api/hooks'
import { Button, Card, Input, Switch } from '@/components/ui'
import { cn } from '@/lib/utils'

export default function Install() {
  const navigate = useNavigate()
  const { data: statusData, isLoading: statusLoading } = useInstallStatus()
  const installMutation = useInstall()

  const [step, setStep] = useState(1) // 1: 数据库 2: 管理员
  const [dbType, setDbType] = useState<'sqlite' | 'mysql'>('sqlite')
  const [showRedis, setShowRedis] = useState(false)

  const [dbHost, setDbHost] = useState('localhost')
  const [dbPort, setDbPort] = useState('3306')
  const [dbUser, setDbUser] = useState('root')
  const [dbPassword, setDbPassword] = useState('')
  const [dbName, setDbName] = useState('taskpool')
  const [dbPath, setDbPath] = useState('')

  const [redisEnabled, setRedisEnabled] = useState(false)
  const [redisHost, setRedisHost] = useState('localhost')
  const [redisPort, setRedisPort] = useState('6379')
  const [redisPassword, setRedisPassword] = useState('')
  const [redisDB] = useState('0')

  const [adminUsername, setAdminUsername] = useState('admin')
  const [adminPassword, setAdminPassword] = useState('')
  const [adminEmail, setAdminEmail] = useState('')
  const [siteTitle, setSiteTitle] = useState('任务池')
  const [siteSubtitle, setSiteSubtitle] = useState('自动化任务调度平台')

  const [error, setError] = useState('')
  const [success, setSuccess] = useState(false)

  useEffect(() => {
    if (statusData?.installed && !success) {
      navigate({ to: '/login' })
    }
  }, [statusData?.installed, success, navigate])

  if (statusLoading) {
    return (
      <div className="flex min-h-screen items-center justify-center bg-[var(--bg-primary)] text-[var(--text-muted)]">
        加载中...
      </div>
    )
  }

  if (statusData?.installed && !success) {
    return null
  }

  async function handleInstall() {
    setError('')
    if (!adminUsername.trim()) {
      setError('请填写管理员用户名')
      return
    }
    if (adminPassword.length < 6) {
      setError('密码至少需要 6 位')
      return
    }
    if (dbType === 'mysql' && (!dbHost.trim() || !dbName.trim() || !dbUser.trim())) {
      setError('请完善 MySQL 连接信息')
      return
    }

    try {
      await installMutation.mutateAsync({
        db_type: dbType,
        db_host: dbType === 'mysql' ? dbHost : undefined,
        db_port: dbType === 'mysql' ? parseInt(dbPort, 10) : undefined,
        db_user: dbType === 'mysql' ? dbUser : undefined,
        db_password: dbType === 'mysql' ? dbPassword : undefined,
        db_name: dbType === 'mysql' ? dbName : undefined,
        db_path: dbType === 'sqlite' ? dbPath || undefined : undefined,
        redis_enabled: redisEnabled,
        redis_host: redisEnabled ? redisHost : undefined,
        redis_port: redisEnabled ? parseInt(redisPort, 10) : undefined,
        redis_password: redisEnabled ? redisPassword : undefined,
        redis_db: redisEnabled ? parseInt(redisDB, 10) : undefined,
        admin_username: adminUsername.trim(),
        admin_password: adminPassword,
        admin_email: adminEmail || undefined,
        site_title: siteTitle || '任务池',
        site_subtitle: siteSubtitle,
      })
      setSuccess(true)
    } catch (err: any) {
      setError(err?.message || '安装失败')
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-[var(--bg-primary)] p-5 text-[var(--text-primary)]">
      <Card className="w-full max-w-lg p-8">
        <div className="mb-8 text-center">
          <div className="ms-on-accent mx-auto mb-4 flex h-14 w-14 select-none items-center justify-center rounded-xl bg-[var(--bg-accent)] text-xl font-bold text-[var(--text-on-accent)]">T</div>
          <h1 className="mb-2 text-2xl font-semibold">安装向导</h1>
          <p className="text-sm text-[var(--text-muted)]">配置数据库与管理员账号，完成初始化</p>
        </div>

        {success ? (
          <div className="text-center">
            <CheckCircle size={48} className="mx-auto mb-4 text-[var(--success)]" strokeWidth={1.5} />
            <h2 className="mb-2 text-xl font-semibold">安装成功</h2>
            <p className="mb-6 text-sm text-[var(--text-muted)]">可使用管理员账号登录系统</p>
            <Button className="w-full" onClick={() => navigate({ to: '/login' })}>
              前往登录
            </Button>
          </div>
        ) : (
          <>
            <div className="mb-6 flex gap-2">
              {[1, 2].map((s) => (
                <div
                  key={s}
                  className={cn('h-1 flex-1 rounded-full', s <= step ? 'bg-[var(--bg-accent)]' : 'bg-[var(--border)]')}
                />
              ))}
            </div>

            {error ? (
              <div className="mb-4 flex items-center gap-2 rounded-md bg-[color-mix(in_srgb,var(--danger)_14%,transparent)] px-3 py-2 text-sm text-[var(--danger)]">
                <AlertCircle size={16} />
                <span>{error}</span>
              </div>
            ) : null}

            {step === 1 ? (
              <div className="space-y-4">
                <h2 className="text-lg font-semibold">数据库配置</h2>
                <div className="grid grid-cols-2 gap-3">
                  <button
                    type="button"
                    onClick={() => setDbType('sqlite')}
                    className={cn(
                      'rounded-lg border p-4 text-left transition-colors',
                      dbType === 'sqlite'
                        ? 'border-[var(--bg-accent)] bg-[var(--bg-accent)] text-[var(--text-on-accent)]'
                        : 'border-[var(--border)] bg-[var(--bg-primary)] hover:bg-[var(--bg-hover)]',
                    )}
                  >
                    <Database size={20} className="mb-2" strokeWidth={1.5} />
                    <div className="font-medium">SQLite</div>
                    <div className={cn('mt-1 text-xs', dbType === 'sqlite' ? 'opacity-80' : 'text-[var(--text-muted)]')}>
                      轻量，开箱即用
                    </div>
                  </button>
                  <button
                    type="button"
                    onClick={() => setDbType('mysql')}
                    className={cn(
                      'rounded-lg border p-4 text-left transition-colors',
                      dbType === 'mysql'
                        ? 'border-[var(--bg-accent)] bg-[var(--bg-accent)] text-[var(--text-on-accent)]'
                        : 'border-[var(--border)] bg-[var(--bg-primary)] hover:bg-[var(--bg-hover)]',
                    )}
                  >
                    <Server size={20} className="mb-2" strokeWidth={1.5} />
                    <div className="font-medium">MySQL</div>
                    <div className={cn('mt-1 text-xs', dbType === 'mysql' ? 'opacity-80' : 'text-[var(--text-muted)]')}>
                      适合生产环境
                    </div>
                  </button>
                </div>

                {dbType === 'sqlite' ? (
                  <div>
                    <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">数据库路径（可选）</label>
                    <Input value={dbPath} onChange={(e) => setDbPath(e.target.value)} placeholder="默认 data/taskpool.db" />
                  </div>
                ) : (
                  <div className="space-y-3">
                    <div className="grid grid-cols-3 gap-3">
                      <div className="col-span-2">
                        <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">主机</label>
                        <Input value={dbHost} onChange={(e) => setDbHost(e.target.value)} placeholder="localhost" />
                      </div>
                      <div>
                        <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">端口</label>
                        <Input value={dbPort} onChange={(e) => setDbPort(e.target.value)} placeholder="3306" />
                      </div>
                    </div>
                    <div>
                      <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">用户名</label>
                      <Input value={dbUser} onChange={(e) => setDbUser(e.target.value)} placeholder="root" />
                    </div>
                    <div>
                      <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">密码</label>
                      <Input type="password" value={dbPassword} onChange={(e) => setDbPassword(e.target.value)} placeholder="数据库密码" />
                    </div>
                    <div>
                      <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">数据库名</label>
                      <Input value={dbName} onChange={(e) => setDbName(e.target.value)} placeholder="taskpool" />
                    </div>
                  </div>
                )}

                <div>
                  <button
                    type="button"
                    className="inline-flex items-center gap-1 text-sm text-[var(--text-muted)] hover:text-[var(--text-primary)]"
                    onClick={() => setShowRedis((v) => !v)}
                  >
                    {showRedis ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
                    Redis 配置（可选）
                  </button>
                  {showRedis ? (
                    <div className="mt-3 space-y-3 rounded-lg border border-[var(--border)] bg-[var(--bg-primary)] p-4">
                      <label className="flex items-center justify-between text-sm">
                        <span>启用 Redis</span>
                        <Switch checked={redisEnabled} onCheckedChange={setRedisEnabled} />
                      </label>
                      {redisEnabled ? (
                        <>
                          <div className="grid grid-cols-3 gap-3">
                            <div className="col-span-2">
                              <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">主机</label>
                              <Input value={redisHost} onChange={(e) => setRedisHost(e.target.value)} />
                            </div>
                            <div>
                              <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">端口</label>
                              <Input value={redisPort} onChange={(e) => setRedisPort(e.target.value)} />
                            </div>
                          </div>
                          <div>
                            <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">密码</label>
                            <Input
                              type="password"
                              value={redisPassword}
                              onChange={(e) => setRedisPassword(e.target.value)}
                              placeholder="可选"
                            />
                          </div>
                        </>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              </div>
            ) : (
              <div className="space-y-4">
                <h2 className="text-lg font-semibold">管理员账号</h2>
                <div>
                  <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">用户名</label>
                  <div className="relative">
                    <User size={16} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-muted)]" />
                    <Input className="pl-10" value={adminUsername} onChange={(e) => setAdminUsername(e.target.value)} />
                  </div>
                </div>
                <div>
                  <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">密码</label>
                  <div className="relative">
                    <Lock size={16} className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-[var(--text-muted)]" />
                    <Input
                      className="pl-10"
                      type="password"
                      value={adminPassword}
                      onChange={(e) => setAdminPassword(e.target.value)}
                      placeholder="至少 6 位"
                    />
                  </div>
                </div>
                <div>
                  <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">邮箱（可选）</label>
                  <Input type="email" value={adminEmail} onChange={(e) => setAdminEmail(e.target.value)} placeholder="admin@example.com" />
                </div>
                <div className="border-t border-[var(--border)] pt-4">
                  <h3 className="mb-3 text-sm font-semibold">站点设置</h3>
                  <div className="space-y-3">
                    <div>
                      <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">站点标题</label>
                      <Input value={siteTitle} onChange={(e) => setSiteTitle(e.target.value)} />
                    </div>
                    <div>
                      <label className="mb-2 block text-sm font-medium text-[var(--text-secondary)]">站点副标题</label>
                      <Input value={siteSubtitle} onChange={(e) => setSiteSubtitle(e.target.value)} />
                    </div>
                  </div>
                </div>
              </div>
            )}

            <div className="mt-8 flex gap-3">
              {step > 1 ? (
                <Button variant="secondary" className="flex-1" onClick={() => setStep((s) => s - 1)}>
                  上一步
                </Button>
              ) : null}
              {step < 2 ? (
                <Button className="flex-1" onClick={() => setStep(2)}>
                  下一步
                </Button>
              ) : (
                <Button className="flex-1" onClick={handleInstall} disabled={installMutation.isPending}>
                  {installMutation.isPending ? '安装中...' : '完成安装'}
                </Button>
              )}
            </div>
          </>
        )}
      </Card>
    </div>
  )
}
