'use client';

import { useState, useEffect } from 'react';
import { 
  Globe, 
  Loader2, 
  Save, 
  RefreshCw,
  ChevronDown,
  ChevronRight,
  AlertCircle,
  CheckCircle
} from 'lucide-react';

interface I18nItem {
  id: string;
  groupName: string;
  keyName: string;
  contentZh: string | null;
  contentRu: string | null;
  description: string | null;
  sortOrder: number;
}

// 分组名称映射
const groupNames: Record<string, string> = {
  home: '首页',
  about: '关于我们',
  services: '服务内容',
  contact: '联系我们',
};

export default function I18nManagementPage() {
  const [content, setContent] = useState<I18nItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [isInitializing, setIsInitializing] = useState(false);
  const [expandedGroups, setExpandedGroups] = useState<Set<string>>(new Set(['home']));
  const [editedContent, setEditedContent] = useState<Record<string, { zh: string; ru: string }>>({});
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);

  // 获取内容
  useEffect(() => {
    fetchContent();
  }, []);

  const fetchContent = async () => {
    try {
      const response = await fetch('/api/admin/i18n');
      const data = await response.json();
      if (response.ok) {
        setContent(data.content || []);
        // 初始化编辑状态
        const edited: Record<string, { zh: string; ru: string }> = {};
        (data.content || []).forEach((item: I18nItem) => {
          edited[item.id] = {
            zh: item.contentZh || '',
            ru: item.contentRu || '',
          };
        });
        setEditedContent(edited);
      } else if (response.status === 401) {
        // 未授权，应该重定向到登录页面
        window.location.href = '/admin/login';
      } else {
        console.error('Error fetching i18n content:', data.error);
      }
    } catch (error) {
      console.error('Error fetching i18n content:', error);
    } finally {
      setIsLoading(false);
    }
  };

  // 初始化默认内容
  const handleInitialize = async () => {
    setIsInitializing(true);
    setMessage(null);
    try {
      const response = await fetch('/api/admin/i18n', { method: 'POST' });
      const data = await response.json();
      if (response.ok) {
        setMessage({ 
          type: 'success', 
          text: `初始化完成：新增 ${data.inserted} 条，已存在 ${data.updated} 条` 
        });
        fetchContent();
      } else {
        setMessage({ type: 'error', text: data.error || '初始化失败' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: '初始化失败' });
    } finally {
      setIsInitializing(false);
    }
  };

  // 保存修改
  const handleSave = async () => {
    setIsSaving(true);
    setMessage(null);
    try {
      // 只提交有变化的内容
      const changes = content
        .filter(item => {
          const edited = editedContent[item.id];
          return edited && (
            edited.zh !== (item.contentZh || '') ||
            edited.ru !== (item.contentRu || '')
          );
        })
        .map(item => ({
          id: item.id,
          contentZh: editedContent[item.id]?.zh || '',
          contentRu: editedContent[item.id]?.ru || '',
        }));

      if (changes.length === 0) {
        setMessage({ type: 'error', text: '没有需要保存的修改' });
        setIsSaving(false);
        return;
      }

      const response = await fetch('/api/admin/i18n', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(changes),
      });

      const data = await response.json();
      if (response.ok) {
        setMessage({ type: 'success', text: `成功保存 ${changes.length} 条修改` });
        fetchContent();
      } else {
        setMessage({ type: 'error', text: data.error || '保存失败' });
      }
    } catch (error) {
      setMessage({ type: 'error', text: '保存失败' });
    } finally {
      setIsSaving(false);
    }
  };

  // 切换分组展开状态
  const toggleGroup = (group: string) => {
    setExpandedGroups(prev => {
      const newSet = new Set(prev);
      if (newSet.has(group)) {
        newSet.delete(group);
      } else {
        newSet.add(group);
      }
      return newSet;
    });
  };

  // 更新编辑内容
  const updateContent = (id: string, lang: 'zh' | 'ru', value: string) => {
    setEditedContent(prev => ({
      ...prev,
      [id]: {
        ...prev[id],
        [lang]: value,
      },
    }));
  };

  // 按分组整理内容
  const groupedContent = content.reduce((acc, item) => {
    const group = item.groupName;
    if (!acc[group]) acc[group] = [];
    acc[group].push(item);
    return acc;
  }, {} as Record<string, I18nItem[]>);

  // 检查是否有未保存的修改
  const hasChanges = content.some(item => {
    const edited = editedContent[item.id];
    return edited && (
      edited.zh !== (item.contentZh || '') ||
      edited.ru !== (item.contentRu || '')
    );
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-20">
        <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
      </div>
    );
  }

  return (
    <div className="max-w-5xl mx-auto">
      {/* 页面标题 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
            <Globe className="w-7 h-7 text-blue-600" />
            多语言内容管理
          </h1>
          <p className="text-gray-500 mt-1">编辑网站各页面的中俄双语内容</p>
        </div>
        <div className="flex gap-3">
          <button
            onClick={handleInitialize}
            disabled={isInitializing}
            className="flex items-center gap-2 px-4 py-2 text-gray-600 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 disabled:opacity-50 transition-colors"
          >
            {isInitializing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCw className="w-4 h-4" />
            )}
            初始化内容
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving || !hasChanges}
            className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isSaving ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <Save className="w-4 h-4" />
            )}
            保存修改
          </button>
        </div>
      </div>

      {/* 提示消息 */}
      {message && (
        <div className={`mb-6 p-4 rounded-lg flex items-center gap-2 ${
          message.type === 'success' 
            ? 'bg-green-50 text-green-700 border border-green-200' 
            : 'bg-red-50 text-red-700 border border-red-200'
        }`}>
          {message.type === 'success' ? (
            <CheckCircle className="w-5 h-5" />
          ) : (
            <AlertCircle className="w-5 h-5" />
          )}
          {message.text}
        </div>
      )}

      {/* 内容列表为空 */}
      {content.length === 0 ? (
        <div className="bg-white rounded-xl border border-gray-200 p-8 text-center">
          <Globe className="w-12 h-12 text-gray-300 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">暂无内容</h3>
          <p className="text-gray-500 mb-4">点击"初始化内容"按钮创建默认内容</p>
          <button
            onClick={handleInitialize}
            disabled={isInitializing}
            className="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 transition-colors"
          >
            {isInitializing ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : (
              <RefreshCw className="w-4 h-4" />
            )}
            初始化内容
          </button>
        </div>
      ) : (
        <div className="space-y-4">
          {Object.entries(groupedContent).map(([group, items]) => {
            const isExpanded = expandedGroups.has(group);
            const groupLabel = groupNames[group] || group;
            
            return (
              <div key={group} className="bg-white rounded-xl border border-gray-200 overflow-hidden">
                {/* 分组标题 */}
                <button
                  onClick={() => toggleGroup(group)}
                  className="w-full flex items-center justify-between px-5 py-4 bg-gray-50 hover:bg-gray-100 transition-colors"
                >
                  <div className="flex items-center gap-3">
                    {isExpanded ? (
                      <ChevronDown className="w-5 h-5 text-gray-400" />
                    ) : (
                      <ChevronRight className="w-5 h-5 text-gray-400" />
                    )}
                    <span className="font-semibold text-gray-900">{groupLabel}</span>
                    <span className="text-sm text-gray-500">({items.length} 项)</span>
                  </div>
                </button>

                {/* 分组内容 */}
                {isExpanded && (
                  <div className="divide-y divide-gray-100">
                    {items.map((item) => {
                      const edited = editedContent[item.id] || { zh: '', ru: '' };
                      const isChanged = 
                        edited.zh !== (item.contentZh || '') ||
                        edited.ru !== (item.contentRu || '');
                      
                      return (
                        <div key={item.id} className={`p-5 ${isChanged ? 'bg-blue-50/30' : ''}`}>
                          <div className="flex items-start justify-between gap-4 mb-3">
                            <div className="flex-1">
                              <div className="flex items-center gap-2">
                                <code className="text-xs bg-gray-100 px-2 py-0.5 rounded text-gray-600">
                                  {item.keyName}
                                </code>
                                {isChanged && (
                                  <span className="text-xs bg-blue-100 text-blue-600 px-2 py-0.5 rounded">
                                    已修改
                                  </span>
                                )}
                              </div>
                              {item.description && (
                                <p className="text-sm text-gray-500 mt-1">{item.description}</p>
                              )}
                            </div>
                          </div>
                          
                          <div className="grid md:grid-cols-2 gap-4">
                            {/* 中文内容 */}
                            <div>
                              <label className="block text-sm font-medium text-gray-700 mb-1.5">
                                中文
                              </label>
                              <textarea
                                value={edited.zh}
                                onChange={(e) => updateContent(item.id, 'zh', e.target.value)}
                                rows={3}
                                className="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none text-sm"
                                placeholder="请输入中文内容"
                              />
                            </div>
                            
                            {/* 俄语内容 */}
                            <div>
                              <label className="block text-sm font-medium text-gray-700 mb-1.5">
                                Русский
                              </label>
                              <textarea
                                value={edited.ru}
                                onChange={(e) => updateContent(item.id, 'ru', e.target.value)}
                                rows={3}
                                className="w-full px-3 py-2 bg-gray-50 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none text-sm"
                                placeholder="Введите текст на русском"
                              />
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* 底部统计 */}
      {content.length > 0 && (
        <div className="mt-6 text-center text-sm text-gray-400">
          共 <span className="font-semibold text-gray-600">{content.length}</span> 条内容
          {hasChanges && (
            <span className="ml-4 text-blue-600">有未保存的修改</span>
          )}
        </div>
      )}
    </div>
  );
}
