import { useEffect, useState } from 'react'
import { User, Key, Save, Loader2 } from 'lucide-react'
import { MarkdownEditor } from './MarkdownEditor'

const API = '/api'

export function UserSettings() {
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [tab, setTab] = useState<'profile' | 'config'>('profile')
  const [user, setUser] = useState({
    name: '',
    description: '',
    provider: 'deepseek',
    model: 'deepseek-chat',
    api_key_env: 'DEEPSEEK_API_KEY',
    avatar_color: '#5865F2',
  })
  const [profile, setProfile] = useState('')

  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'],
  }

  useEffect(() => {
    async function load() {
      try {
        const [userRes, profileRes] = await Promise.all([
          fetch(`${API}/user`).then(r => r.json()),
          fetch(`${API}/user/profile`).then(r => r.json())
        ])
        setUser(userRes)
        setProfile(profileRes.content || '')
      } catch (err) {
        console.error(err)
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  const handleSaveConfig = async () => {
    setSaving(true)
    try {
      await fetch(`${API}/user/config`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(user)
      })
    } catch (err) {
      console.error(err)
    } finally {
      setSaving(false)
    }
  }

  const handleSaveProfile = async () => {
    setSaving(true)
    try {
      await fetch(`${API}/user/profile`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ content: profile })
      })
    } catch (err) {
      console.error(err)
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <Loader2 className="w-6 h-6 animate-spin text-[var(--accent)]" />
      </div>
    )
  }

  return (
    <div className="flex flex-1 overflow-hidden">
      {/* Sidebar */}
      <div className="w-56 border-r border-[var(--border)] bg-[var(--channel-list-bg)] flex flex-col">
        <div className="p-4 border-b border-[var(--border)]">
          <div className="flex items-center gap-2">
            <div className="w-10 h-10 rounded-full bg-[var(--accent)] flex items-center justify-center text-white font-semibold">
              {user.name?.[0]?.toUpperCase() || 'U'}
            </div>
            <div>
              <div className="font-medium text-sm">{user.name || '用户'}</div>
              <div className="text-xs text-[var(--text-muted)]">{user.provider}</div>
            </div>
          </div>
        </div>
        <nav className="flex-1 py-2">
          <button
            onClick={() => setTab('profile')}
            className={`
              w-full flex items-center gap-2 px-4 py-2 text-sm transition-colors
              ${tab === 'profile'
                ? 'bg-[var(--accent-muted)] text-[var(--text-primary)]'
                : 'text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]'
              }
            `}
          >
            <User className="w-4 h-4" />
            个人简介
          </button>
          <button
            onClick={() => setTab('config')}
            className={`
              w-full flex items-center gap-2 px-4 py-2 text-sm transition-colors
              ${tab === 'config'
                ? 'bg-[var(--accent-muted)] text-[var(--text-primary)]'
                : 'text-[var(--text-secondary)] hover:bg-[var(--bg-hover)]'
              }
            `}
          >
            <Key className="w-4 h-4" />
            API 配置
          </button>
        </nav>
      </div>

      {/* Content */}
      <div className="flex-1 flex flex-col overflow-hidden bg-[var(--bg-primary)]">
        {tab === 'profile' && (
          <>
            <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--border)] bg-[var(--bg-secondary)]">
              <h2 className="font-semibold">个人简介</h2>
              <button
                onClick={handleSaveProfile}
                disabled={saving}
                className="flex items-center gap-2 bg-[var(--accent)] hover:bg-[var(--accent-hover)] px-4 py-1.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
              >
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                保存
              </button>
            </div>
            <div className="flex-1 overflow-auto p-4">
              <MarkdownEditor
                value={profile}
                onChange={(v: string) => setProfile(v)}
                height={300}
              />
            </div>
          </>
        )}

        {tab === 'config' && (
          <>
            <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--border)] bg-[var(--bg-secondary)]">
              <h2 className="font-semibold">API 配置</h2>
              <button
                onClick={handleSaveConfig}
                disabled={saving}
                className="flex items-center gap-2 bg-[var(--accent)] hover:bg-[var(--accent-hover)] px-4 py-1.5 rounded-lg text-sm font-medium transition-colors disabled:opacity-50"
              >
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                保存
              </button>
            </div>
            <div className="flex-1 overflow-y-auto p-6">
              <div className="max-w-lg space-y-4">
                <div>
                  <label className="text-sm font-medium mb-2 block">名称</label>
                  <input
                    type="text"
                    value={user.name}
                    onChange={e => setUser({ ...user, name: 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)]"
                  />
                </div>

                <div>
                  <label className="text-sm font-medium mb-2 block">简介</label>
                  <input
                    type="text"
                    value={user.description}
                    onChange={e => setUser({ ...user, description: 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-2 block">提供商</label>
                  <div className="grid grid-cols-4 gap-2">
                    {['deepseek', 'kimi', 'ollama', 'openai'].map(p => (
                      <button
                        key={p}
                        onClick={() => setUser({ ...user, provider: p, model: providerModels[p][0] })}
                        className={`
                          py-2 px-3 rounded-lg text-sm font-medium transition-colors border
                          ${user.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={user.model}
                    onChange={e => setUser({ ...user, model: 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[user.provider].map(m => (
                      <option key={m} value={m}>{m}</option>
                    ))}
                  </select>
                </div>

                <div>
                  <label className="text-sm font-medium mb-2 block">环境变量名</label>
                  <input
                    type="text"
                    value={user.api_key_env}
                    onChange={e => setUser({ ...user, api_key_env: 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)]"
                  />
                  <p className="text-xs text-[var(--text-muted)] mt-1">
                    API Key 将从这个环境变量读取
                  </p>
                </div>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  )
}
