import { useState } from 'react'
import { ChevronRight, ChevronLeft, Check, Hash, Sparkles, Key, User } from 'lucide-react'
import { MarkdownEditor } from './MarkdownEditor'

const API = '/api'

const STEPS = [
  { id: 1, title: '欢迎', icon: Sparkles },
  { id: 2, title: '关于你', icon: User },
  { id: 3, title: 'API 配置', icon: Key },
]

const DEFAULT_PROFILE = `# 我的简介

## 我是谁
我是[你的名字]，[职业/背景]。

## 工作风格
- 喜欢[沟通方式]
- 重视[重视的点]
- 不喜欢[不喜欢的]

## 期望的回复方式
- 用 bullet point 列出要点
- 重要的决定给出 pros 和 cons
- 提供数据支持`

interface OnboardingProps {
  onComplete: () => void
}

export function Onboarding({ onComplete }: OnboardingProps) {
  const [step, setStep] = useState(1)
  const [name, setName] = useState('')
  const [description, setDescription] = useState('')
  const [profile, setProfile] = useState('')
  const [provider, setProvider] = useState('deepseek')
  const [model, setModel] = useState('deepseek-chat')
  const [apiKey, setApiKey] = useState('')
  const [saving, setSaving] = useState(false)

  const handleNext = () => {
    if (step < 3) {
      setStep(step + 1)
    }
  }

  const handlePrev = () => {
    if (step > 1) {
      setStep(step - 1)
    }
  }

  const handleComplete = async () => {
    setSaving(true)
    try {
      await fetch(`${API}/user/config`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: name || '用户',
          description,
          provider,
          model,
          api_key_env: provider.toUpperCase() + '_API_KEY',
        })
      })

      await fetch(`${API}/user/profile`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: profile || DEFAULT_PROFILE })
      })

      localStorage.setItem('onboarding_completed', 'true')
      onComplete()
    } catch (err) {
      console.error(err)
    } finally {
      setSaving(false)
    }
  }

  const handleSkip = () => {
    localStorage.setItem('onboarding_completed', 'true')
    onComplete()
  }

  const providerModels: Record<string, string[]> = {
    deepseek: ['deepseek-chat', 'deepseek-coder'],
    kimi: ['moonshot-v1-8k', 'moonshot-v1-32k'],
    ollama: ['qwen2.5', 'llama3', 'mistral'],
    openai: ['gpt-4o', 'gpt-4-turbo', 'gpt-3.5-turbo'],
  }

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 p-4">
      <div className="bg-[var(--bg-secondary)] border border-[var(--border)] rounded-xl w-full max-w-2xl max-h-[90vh] flex flex-col shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--border)]">
          <div className="flex items-center gap-2">
            <Hash className="w-5 h-5 text-[var(--accent)]" />
            <span className="font-semibold">Agent Team</span>
          </div>
          <button
            onClick={handleSkip}
            className="text-[var(--text-muted)] hover:text-[var(--text-primary)] text-sm"
          >
            跳过
          </button>
        </div>

        {/* Progress */}
        <div className="px-6 py-4 border-b border-[var(--border)]">
          <div className="flex items-center justify-center gap-2">
            {STEPS.map((s, i) => (
              <div key={s.id} className="flex items-center">
                <div
                  className={`
                    w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors
                    ${step === s.id
                      ? 'bg-[var(--accent)] text-white'
                      : step > s.id
                      ? 'bg-[var(--color-success)] text-white'
                      : 'bg-[var(--bg-tertiary)] text-[var(--text-muted)]'
                    }
                  `}
                >
                  {step > s.id ? <Check className="w-4 h-4" /> : s.id}
                </div>
                {i < STEPS.length - 1 && (
                  <div className={`w-12 h-0.5 mx-1 ${step > s.id ? 'bg-[var(--color-success)]' : 'bg-[var(--border)]'}`} />
                )}
              </div>
            ))}
          </div>
          <div className="flex justify-center gap-4 mt-2">
            {STEPS.map(s => (
              <span
                key={s.id}
                className={`text-xs ${step === s.id ? 'text-[var(--text-primary)]' : 'text-[var(--text-muted)]'}`}
              >
                {s.title}
              </span>
            ))}
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          {/* Step 1: Welcome */}
          {step === 1 && (
            <div className="space-y-4">
              <div className="text-center">
                <div className="w-16 h-16 bg-[var(--accent)] rounded-2xl flex items-center justify-center mx-auto mb-4">
                  <Sparkles className="w-8 h-8 text-white" />
                </div>
                <h2 className="text-xl font-bold mb-2">欢迎使用 Agent Team</h2>
                <p className="text-[var(--text-muted)] text-sm">
                  这是一个本地部署的多 Agent 协作平台，通过类似 Discord 的群聊界面与你的 AI 团队协作完成复杂任务。
                </p>
              </div>

              <div className="bg-[var(--bg-tertiary)] rounded-lg p-4 space-y-2">
                <p className="text-sm font-medium">📋 你将体验到：</p>
                <ul className="text-sm text-[var(--text-secondary)] space-y-1">
                  <li>• 创建和管理 AI Agent 团队</li>
                  <li>• 通过群聊与 Agent 协作</li>
                  <li>• Agent 自动沉淀经验，持续成长</li>
                  <li>• 支持 DeepSeek、Kimi、Ollama、OpenAI</li>
                </ul>
              </div>
            </div>
          )}

          {/* Step 2: About You */}
          {step === 2 && (
            <div className="space-y-4">
              <div className="text-center">
                <div className="w-14 h-14 bg-[var(--accent)] rounded-xl flex items-center justify-center mx-auto mb-3">
                  <User className="w-7 h-7 text-white" />
                </div>
                <h2 className="text-lg font-bold">介绍一下你自己</h2>
                <p className="text-[var(--text-muted)] text-sm">
                  用 Markdown 写下你的简介，Agent 会根据这些信息更好地帮助你
                </p>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-sm font-medium mb-1.5 block">名称</label>
                  <input
                    type="text"
                    value={name}
                    onChange={e => setName(e.target.value)}
                    placeholder="张三"
                    className="w-full bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm outline-none focus:border-[var(--accent)]"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium mb-1.5 block">一句话简介</label>
                  <input
                    type="text"
                    value={description}
                    onChange={e => setDescription(e.target.value)}
                    placeholder="产品经理，擅长需求分析"
                    className="w-full bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm outline-none focus:border-[var(--accent)]"
                  />
                </div>
              </div>

              <div>
                <label className="text-sm font-medium mb-1.5 block">详细简介（支持 Markdown）</label>
                <div className="mt-2">
                  <MarkdownEditor
                    value={profile || `# 我的简介

## 我是谁
我是[你的名字]，[职业/背景]。

## 工作风格
- 喜欢[沟通方式]
- 重视[重视的点]
- 不喜欢[不喜欢的]

## 期望的回复方式
- 用 bullet point 列出要点
- 重要的决定给出 pros 和 cons
- 提供数据支持`}
                    onChange={(v: string) => setProfile(v)}
                    height={250}
                  />
                </div>
              </div>
            </div>
          )}

          {/* Step 3: API Config */}
          {step === 3 && (
            <div className="space-y-4 max-w-md mx-auto">
              <div className="text-center mb-4">
                <div className="w-12 h-12 bg-[var(--accent)] rounded-xl flex items-center justify-center mx-auto mb-3">
                  <Key className="w-6 h-6 text-white" />
                </div>
                <h2 className="text-lg font-bold">配置默认 API</h2>
                <p className="text-[var(--text-muted)] text-sm">
                  选择默认的模型提供商，所有 Agent 将使用此配置（可在 Agent 级别覆盖）
                </p>
              </div>

              <div>
                <label className="text-sm font-medium mb-2 block">提供商</label>
                <div className="grid grid-cols-4 gap-2">
                  {['deepseek', 'kimi', 'ollama', 'openai'].map(p => (
                    <button
                      key={p}
                      onClick={() => {
                        setProvider(p)
                        setModel(providerModels[p][0])
                      }}
                      className={`
                        py-2 px-3 rounded-lg text-sm font-medium transition-colors border
                        ${provider === p
                          ? 'bg-[var(--accent)] border-[var(--accent)] text-white'
                          : 'bg-[var(--bg-tertiary)] border-[var(--border)] hover:border-[var(--accent)]'
                        }
                      `}
                    >
                      {p === 'deepseek' ? 'DeepSeek' : p === 'kimi' ? 'Kimi' : p === 'ollama' ? 'Ollama' : 'OpenAI'}
                    </button>
                  ))}
                </div>
              </div>

              <div>
                <label className="text-sm font-medium mb-2 block">模型</label>
                <select
                  value={model}
                  onChange={e => setModel(e.target.value)}
                  className="w-full bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm outline-none focus:border-[var(--accent)]"
                >
                  {providerModels[provider].map(m => (
                    <option key={m} value={m}>{m}</option>
                  ))}
                </select>
              </div>

              <div>
                <label className="text-sm font-medium mb-2 block">
                  API Key
                  <span className="text-[var(--text-muted)] font-normal ml-2">
                    (将保存到 {provider.toUpperCase()}_API_KEY 环境变量)
                  </span>
                </label>
                <input
                  type="password"
                  value={apiKey}
                  onChange={e => setApiKey(e.target.value)}
                  placeholder="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxx"
                  className="w-full bg-[var(--bg-tertiary)] border border-[var(--border)] rounded-lg px-3 py-2 text-sm outline-none focus:border-[var(--accent)]"
                />
              </div>

              <div className="bg-[var(--bg-tertiary)] rounded-lg p-3 text-xs text-[var(--text-muted)]">
                <p>💡 提示：API Key 将保存在浏览器本地存储中，每次启动后端时会自动读取。</p>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between px-6 py-4 border-t border-[var(--border)]">
          <button
            onClick={handlePrev}
            disabled={step === 1}
            className={`
              flex items-center gap-1 px-4 py-2 rounded-lg text-sm transition-colors
              ${step === 1
                ? 'text-[var(--text-muted)] cursor-not-allowed'
                : 'hover:bg-[var(--bg-hover)]'
              }
            `}
          >
            <ChevronLeft className="w-4 h-4" />
            上一步
          </button>

          {step < 3 ? (
            <button
              onClick={handleNext}
              className="flex items-center gap-1 bg-[var(--accent)] hover:bg-[var(--accent-hover)] px-6 py-2 rounded-lg text-sm font-medium transition-colors"
            >
              下一步
              <ChevronRight className="w-4 h-4" />
            </button>
          ) : (
            <button
              onClick={handleComplete}
              disabled={saving}
              className="flex items-center gap-2 bg-[var(--color-success)] hover:opacity-90 px-6 py-2 rounded-lg text-sm font-medium transition-colors"
            >
              {saving ? '保存中...' : '完成'}
              <Check className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
