'use client';

import { useEffect, useState, useCallback } from 'react';
import { API_BASE } from '@/lib/config';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import * as Dialog from '@/components/ui/dialog';

interface Config {
  key: string;
  value: string;
  description: string;
  category: string;
}

const CATEGORIES = ['site', 'ai', 'member'];
const CATEGORY_NAMES: Record<string, string> = { site: '站点设置', ai: 'AI 配置', member: '会员设置' };

function getAuthHeaders() {
  const token = localStorage.getItem('adminToken');
  return { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
}

export default function ConfigPage() {
  const [configs, setConfigs] = useState<Config[]>([]);
  const [loading, setLoading] = useState(true);
  const [category, setCategory] = useState('ai');

  // Dialog state
  const [dialogOpen, setDialogOpen] = useState(false);
  const [editingKey, setEditingKey] = useState<string | null>(null);
  const [formKey, setFormKey] = useState('');
  const [formValue, setFormValue] = useState('');
  const [formDesc, setFormDesc] = useState('');

  const loadConfigs = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetch(`${API_BASE}/admin/config/${category}`, { headers: getAuthHeaders() });
      if (res.ok) {
        const data = await res.json();
        setConfigs(data.items || []);
      }
    } catch {}
    setLoading(false);
  }, [category]);

  useEffect(() => { loadConfigs(); }, [loadConfigs]);

  function openAddDialog() {
    setEditingKey(null);
    setFormKey('');
    setFormValue('');
    setFormDesc('');
    setDialogOpen(true);
  }

  function openEditDialog(c: Config) {
    setEditingKey(c.key);
    setFormKey(c.key);
    setFormValue(c.value);
    setFormDesc(c.description || '');
    setDialogOpen(true);
  }

  async function handleSave() {
    if (!formKey.trim()) return;
    const key = editingKey || formKey;
    try {
      await fetch(`${API_BASE}/admin/config/${key}`, {
        method: 'PUT',
        headers: getAuthHeaders(),
        body: JSON.stringify({ value: formValue, description: formDesc, category }),
      });
      setDialogOpen(false);
      loadConfigs();
    } catch {}
  }

  async function handleDelete(key: string) {
    if (!window.confirm(`确定删除配置项 "${key}" 吗？`)) return;
    try {
      await fetch(`${API_BASE}/admin/config/${key}`, {
        method: 'DELETE',
        headers: getAuthHeaders(),
      });
      loadConfigs();
    } catch {}
  }

  if (loading) return <div className="p-6">加载中...</div>;

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-foreground">系统配置</h1>
          <p className="text-sm text-muted-foreground">配置站点、AI、会员等设置</p>
        </div>
        <Button onClick={openAddDialog}>+ 新增配置</Button>
      </div>

      <div className="flex gap-4 mb-6">
        {CATEGORIES.map(cat => (
          <button key={cat} onClick={() => setCategory(cat)}
            className={`px-4 py-2 rounded-lg text-sm ${category === cat ? 'bg-brand-600 text-white' : 'bg-muted text-muted-foreground hover:bg-accent'}`}>
            {CATEGORY_NAMES[cat]}
          </button>
        ))}
      </div>

      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <table className="w-full">
          <thead className="bg-muted/50 border-b border-border">
            <tr>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">配置项</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">描述</th>
              <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">值</th>
              <th className="px-6 py-3 text-right text-xs font-medium text-muted-foreground uppercase">操作</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {configs.map(c => (
              <tr key={c.key} className="hover:bg-accent/50">
                <td className="px-6 py-4 text-sm font-medium text-foreground">{c.key}</td>
                <td className="px-6 py-4 text-sm text-muted-foreground">{c.description || '-'}</td>
                <td className="px-6 py-4 text-sm text-foreground max-w-xs truncate">{c.value}</td>
                <td className="px-6 py-4 text-sm text-right whitespace-nowrap">
                  <button onClick={() => openEditDialog(c)} className="text-brand-600 hover:underline text-sm mr-3">编辑</button>
                  <button onClick={() => handleDelete(c.key)} className="text-red-500 hover:underline text-sm">删除</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {configs.length === 0 && (
          <div className="text-center py-12 text-sm text-muted-foreground">暂无配置项</div>
        )}
      </div>

      <Dialog.Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
        <Dialog.DialogContent>
          <Dialog.DialogHeader>
            <Dialog.DialogTitle>{editingKey ? '编辑配置' : '新增配置'}</Dialog.DialogTitle>
            <Dialog.DialogDescription>
              {editingKey ? `修改配置项 "${editingKey}"` : '添加一个新的系统配置项'}
            </Dialog.DialogDescription>
          </Dialog.DialogHeader>
          <div className="space-y-4">
            {!editingKey && (
              <div>
                <label className="block text-sm font-medium text-foreground mb-1">配置键名</label>
                <Input value={formKey} onChange={e => setFormKey(e.target.value)} placeholder="例如：site_name" />
              </div>
            )}
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">配置值</label>
              <Input value={formValue} onChange={e => setFormValue(e.target.value)} placeholder="配置值" />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">描述</label>
              <Input value={formDesc} onChange={e => setFormDesc(e.target.value)} placeholder="配置项描述（可选）" />
            </div>
          </div>
          <Dialog.DialogFooter>
            <Button variant="outline" onClick={() => setDialogOpen(false)}>取消</Button>
            <Button onClick={handleSave}>保存</Button>
          </Dialog.DialogFooter>
        </Dialog.DialogContent>
      </Dialog.Dialog>
    </div>
  );
}
