import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import {
  Server,
  Mail,
  ChevronRight,
  Settings,
  Save,
  RefreshCw,
  Globe,
  ToggleLeft,
  ToggleRight
} from 'lucide-react'
import { Card, CardHeader, CardTitle, CardContent, Button, Input } from '../components/common'
import { useConfig } from '../hooks/useConfig'

export default function Config() {
  const { config, isConnected } = useConfig()
  const [loading, setLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)

  // 编辑状态
  const [editS2ABase, setEditS2ABase] = useState('')
  const [editS2AKey, setEditS2AKey] = useState('')
  const [editConcurrency, setEditConcurrency] = useState(2)
  const [editPriority, setEditPriority] = useState(0)
  const [editGroupIds, setEditGroupIds] = useState('')
  const [proxyEnabled, setProxyEnabled] = useState(false)
  const [proxyAddress, setProxyAddress] = useState('')

  // 获取服务器配置
  const fetchServerConfig = async () => {
    setLoading(true)
    try {
      const res = await fetch('/api/config')
      const data = await res.json()
      if (data.success) {
        setEditS2ABase(data.data.s2a_api_base || '')
        setEditS2AKey(data.data.s2a_admin_key || '')
        setEditConcurrency(data.data.concurrency || 2)
        setEditPriority(data.data.priority || 0)
        setEditGroupIds(data.data.group_ids?.join(', ') || '')
        setProxyEnabled(data.data.proxy_enabled || false)
        setProxyAddress(data.data.default_proxy || '')
      }
    } catch (error) {
      console.error('Failed to fetch config:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    fetchServerConfig()
  }, [])

  // 保存配置
  const handleSave = async () => {
    setSaving(true)
    setMessage(null)
    try {
      // 解析 group_ids
      const groupIds = editGroupIds
        .split(',')
        .map(s => parseInt(s.trim()))
        .filter(n => !isNaN(n))

      const res = await fetch('/api/config', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          s2a_api_base: editS2ABase,
          s2a_admin_key: editS2AKey,
          concurrency: editConcurrency,
          priority: editPriority,
          group_ids: groupIds,
          proxy_enabled: proxyEnabled,
          default_proxy: proxyAddress,
        }),
      })
      const data = await res.json()
      if (data.success) {
        setMessage({ type: 'success', text: '配置已保存' })
        fetchServerConfig()
      } else {
        setMessage({ type: 'error', text: data.error || '保存失败' })
      }
    } catch (error) {
      setMessage({ type: 'error', text: '网络错误' })
    } finally {
      setSaving(false)
    }
  }

  const configItems = [
    {
      to: '/config/s2a',
      icon: Server,
      title: 'S2A 高级配置',
      description: 'S2A 号池详细设置和测试',
      status: isConnected ? '已连接' : '未连接',
      statusColor: isConnected ? 'text-green-600 dark:text-green-400' : 'text-red-500',
    },
    {
      to: '/config/email',
      icon: Mail,
      title: '邮箱服务配置',
      description: '配置邮箱服务用于自动注册',
      status: (config.email?.services?.length ?? 0) > 0 ? '已配置' : '未配置',
      statusColor: (config.email?.services?.length ?? 0) > 0 ? 'text-green-600 dark:text-green-400' : 'text-orange-500',
    },
  ]

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
            <Settings className="h-7 w-7 text-slate-500" />
            系统配置
          </h1>
          <p className="text-sm text-slate-500 dark:text-slate-400">配置会自动保存到服务器</p>
        </div>
        <Button
          variant="outline"
          size="sm"
          onClick={fetchServerConfig}
          disabled={loading}
          icon={<RefreshCw className={`h-4 w-4 ${loading ? 'animate-spin' : ''}`} />}
        >
          刷新
        </Button>
      </div>

      {/* Message */}
      {message && (
        <div className={`p-3 rounded-lg text-sm ${message.type === 'success'
          ? 'bg-green-50 text-green-700 dark:bg-green-900/30 dark:text-green-400'
          : 'bg-red-50 text-red-700 dark:bg-red-900/30 dark:text-red-400'
          }`}>
          {message.text}
        </div>
      )}

      {/* Quick Config Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Server className="h-5 w-5 text-blue-500" />
            核心配置
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* S2A Config */}
          <div className="grid gap-4 md:grid-cols-2">
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                S2A API 地址
              </label>
              <Input
                value={editS2ABase}
                onChange={(e) => setEditS2ABase(e.target.value)}
                placeholder="https://your-s2a-server.com"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                S2A Admin Key
              </label>
              <Input
                type="password"
                value={editS2AKey}
                onChange={(e) => setEditS2AKey(e.target.value)}
                placeholder="admin-xxxxxx"
              />
            </div>
          </div>

          {/* Pooling Config */}
          <div className="grid gap-4 md:grid-cols-3">
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                入库并发
              </label>
              <Input
                type="number"
                value={editConcurrency}
                onChange={(e) => setEditConcurrency(parseInt(e.target.value) || 1)}
                min={1}
                max={100}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                优先级
              </label>
              <Input
                type="number"
                value={editPriority}
                onChange={(e) => setEditPriority(parseInt(e.target.value) || 0)}
                min={0}
                max={100}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">
                分组 ID (逗号分隔)
              </label>
              <Input
                value={editGroupIds}
                onChange={(e) => setEditGroupIds(e.target.value)}
                placeholder="1, 2, 3"
              />
            </div>
          </div>

          {/* Proxy Config */}
          <div className="border-t border-slate-200 dark:border-slate-700 pt-4">
            <div className="flex items-center justify-between mb-3">
              <div className="flex items-center gap-2">
                <Globe className="h-5 w-5 text-orange-500" />
                <span className="font-medium text-slate-700 dark:text-slate-300">代理设置</span>
              </div>
              <button
                onClick={() => setProxyEnabled(!proxyEnabled)}
                className="flex items-center gap-2 text-sm"
              >
                {proxyEnabled ? (
                  <>
                    <ToggleRight className="h-6 w-6 text-green-500" />
                    <span className="text-green-600 dark:text-green-400">已启用</span>
                  </>
                ) : (
                  <>
                    <ToggleLeft className="h-6 w-6 text-slate-400" />
                    <span className="text-slate-500">已禁用</span>
                  </>
                )}
              </button>
            </div>
            <Input
              value={proxyAddress}
              onChange={(e) => setProxyAddress(e.target.value)}
              placeholder="http://127.0.0.1:7890"
              disabled={!proxyEnabled}
              className={!proxyEnabled ? 'opacity-50' : ''}
            />
            <p className="text-xs text-slate-500 mt-1">
              服务器部署时通常不需要代理，在本地开发或特殊网络环境下可启用
            </p>
          </div>

          {/* Save Button */}
          <div className="flex justify-end pt-2">
            <Button
              onClick={handleSave}
              disabled={saving}
              icon={<Save className="h-4 w-4" />}
            >
              {saving ? '保存中...' : '保存配置'}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* Sub Config Cards */}
      <div className="grid gap-4 md:grid-cols-2">
        {configItems.map((item) => (
          <Link key={item.to} to={item.to} className="block group">
            <Card className="h-full transition-all duration-200 hover:shadow-lg hover:border-blue-300 dark:hover:border-blue-600">
              <CardContent className="flex items-center gap-4 py-4">
                <div className="p-3 rounded-xl bg-blue-50 dark:bg-blue-900/30 group-hover:bg-blue-100 dark:group-hover:bg-blue-900/50 transition-colors">
                  <item.icon className="h-6 w-6 text-blue-600 dark:text-blue-400" />
                </div>
                <div className="flex-1">
                  <h3 className="font-semibold text-slate-900 dark:text-slate-100">{item.title}</h3>
                  <p className="text-sm text-slate-500 dark:text-slate-400">{item.description}</p>
                </div>
                <span className={`text-sm font-medium ${item.statusColor}`}>
                  {item.status}
                </span>
                <ChevronRight className="h-5 w-5 text-slate-400 group-hover:text-blue-500 transition-colors" />
              </CardContent>
            </Card>
          </Link>
        ))}
      </div>

      {/* Info */}
      <Card>
        <CardContent>
          <div className="text-sm text-slate-500 dark:text-slate-400">
            <p>配置会保存在服务器端，重启后自动加载。首次启动时会自动创建默认配置。</p>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
