'use client';

import { useState, useEffect, useRef } from 'react';
import { 
  Plus,
  Loader2,
  Edit,
  Trash2,
  Save,
  X,
  Eye,
  EyeOff,
  GripVertical,
  Truck,
  Car,
  Route,
  Train,
  Ship,
  Building2,
  CheckCircle2,
  Package,
  Wrench,
  Sparkles,
  ArrowLeftRight,
  FileText,
  Globe,
  Upload,
  Image,
  File,
  PlusCircle,
  MinusCircle,
  ArrowLeft,
  Shield,
  AlertTriangle
} from 'lucide-react';
import Link from 'next/link';

// 图标映射
const iconMap: Record<string, typeof Truck> = {
  Truck, Car, Route, Train, Ship, Building2, CheckCircle2, 
  Package, Wrench, Sparkles, ArrowLeftRight, FileText, Globe
};

interface ServiceContent {
  features: string[];
  process: { step: number; title: string; desc: string }[];
  policies: { title: string; content: string; icon: string }[];
  requirements: string[];
}

interface ContentItem {
  id: string;
  content_type: string;
  title: string;
  description: string | null;
  content: string | null;
  icon: string | null;
  category: string | null;
  sort_order: number;
  is_active: boolean;
  cover_image: string | null;
  attachments: string | null;
  created_at: string;
  updated_at: string;
}

interface Attachment {
  name: string;
  url: string;
  type: 'image' | 'document';
}

const categories = ['公路运输', '铁路运输', '口岸服务', '特殊物流', '其他服务'];
const icons = ['Truck', 'Car', 'Route', 'Train', 'Ship', 'Building2', 'CheckCircle2', 'Package', 'Wrench', 'Sparkles', 'ArrowLeftRight', 'FileText', 'Globe'];
const policyIcons = ['FileCheck', 'Shield', 'AlertTriangle'];

export default function AdminServicesPage() {
  const [services, setServices] = useState<ContentItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editForm, setEditForm] = useState<{
    title: string;
    description: string;
    category: string;
    icon: string;
    content: ServiceContent;
    coverImage: string;
    attachments: Attachment[];
    is_active: boolean;
  } | null>(null);
  const [saving, setSaving] = useState(false);
  const [uploading, setUploading] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const coverInputRef = useRef<HTMLInputElement>(null);

  // 获取服务列表
  const fetchServices = async () => {
    setIsLoading(true);
    try {
      const response = await fetch('/api/admin/content?type=service');
      const data = await response.json();
      if (response.ok) {
        setServices(data.content || []);
      }
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsLoading(false);
    }
  };

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

  // 解析服务内容
  const parseContent = (content: string | null): ServiceContent => {
    if (!content) {
      return {
        features: [],
        process: [],
        policies: [],
        requirements: []
      };
    }
    try {
      const parsed = JSON.parse(content);
      return {
        features: parsed.features || [],
        process: parsed.process || [],
        policies: parsed.policies || [],
        requirements: parsed.requirements || []
      };
    } catch {
      return {
        features: [],
        process: [],
        policies: [],
        requirements: []
      };
    }
  };

  // 解析附件
  const parseAttachments = (attachments: string | null): Attachment[] => {
    if (!attachments) return [];
    try {
      return JSON.parse(attachments);
    } catch {
      return [];
    }
  };

  // 开始编辑
  const handleEdit = (service: ContentItem) => {
    setEditingId(service.id);
    setEditForm({
      title: service.title,
      description: service.description || '',
      category: service.category || '公路运输',
      icon: service.icon || 'Truck',
      content: parseContent(service.content),
      coverImage: service.cover_image || '',
      attachments: parseAttachments(service.attachments),
      is_active: service.is_active,
    });
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditingId(null);
    setEditForm(null);
  };

  // 上传封面图片
  const handleCoverUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const formData = new FormData();
      formData.append('file', file);
      formData.append('type', 'image');

      const response = await fetch('/api/admin/upload', {
        method: 'POST',
        body: formData,
      });

      const data = await response.json();
      if (response.ok && data.success) {
        setEditForm(prev => prev ? { ...prev, coverImage: data.fileUrl } : null);
      } else {
        alert(data.error || '上传失败');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('上传失败');
    } finally {
      setUploading(false);
    }
  };

  // 上传附件
  const handleAttachmentUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    if (!files || files.length === 0) return;

    setUploading(true);
    try {
      for (const file of Array.from(files)) {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('type', file.type.startsWith('image/') ? 'image' : 'document');

        const response = await fetch('/api/admin/upload', {
          method: 'POST',
          body: formData,
        });

        const data = await response.json();
        if (response.ok && data.success) {
          setEditForm(prev => prev ? {
            ...prev,
            attachments: [...prev.attachments, {
              name: data.fileName,
              url: data.fileUrl,
              type: data.fileType
            }]
          } : null);
        }
      }
    } catch (error) {
      console.error('Error:', error);
      alert('上传失败');
    } finally {
      setUploading(false);
    }
  };

  // 删除附件
  const handleRemoveAttachment = (index: number) => {
    setEditForm(prev => prev ? {
      ...prev,
      attachments: prev.attachments.filter((_, i) => i !== index)
    } : null);
  };

  // 更新服务内容字段
  const updateContent = (field: keyof ServiceContent, value: unknown) => {
    setEditForm(prev => prev ? {
      ...prev,
      content: { ...prev.content, [field]: value }
    } : null);
  };

  // 添加特点
  const addFeature = () => {
    updateContent('features', [...(editForm?.content.features || []), '']);
  };

  // 更新特点
  const updateFeature = (index: number, value: string) => {
    const newFeatures = [...(editForm?.content.features || [])];
    newFeatures[index] = value;
    updateContent('features', newFeatures);
  };

  // 删除特点
  const removeFeature = (index: number) => {
    updateContent('features', editForm?.content.features.filter((_, i) => i !== index));
  };

  // 添加流程步骤
  const addProcessStep = () => {
    const process = editForm?.content.process || [];
    updateContent('process', [...process, { step: process.length + 1, title: '', desc: '' }]);
  };

  // 更新流程步骤
  const updateProcessStep = (index: number, field: 'title' | 'desc', value: string) => {
    const newProcess = [...(editForm?.content.process || [])];
    newProcess[index] = { ...newProcess[index], [field]: value };
    updateContent('process', newProcess);
  };

  // 删除流程步骤
  const removeProcessStep = (index: number) => {
    const newProcess = editForm?.content.process
      .filter((_, i) => i !== index)
      .map((p, i) => ({ ...p, step: i + 1 })) || [];
    updateContent('process', newProcess);
  };

  // 添加政策
  const addPolicy = () => {
    updateContent('policies', [...(editForm?.content.policies || []), { title: '', content: '', icon: 'FileCheck' }]);
  };

  // 更新政策
  const updatePolicy = (index: number, field: 'title' | 'content' | 'icon', value: string) => {
    const newPolicies = [...(editForm?.content.policies || [])];
    newPolicies[index] = { ...newPolicies[index], [field]: value };
    updateContent('policies', newPolicies);
  };

  // 删除政策
  const removePolicy = (index: number) => {
    updateContent('policies', editForm?.content.policies.filter((_, i) => i !== index));
  };

  // 添加所需资料
  const addRequirement = () => {
    updateContent('requirements', [...(editForm?.content.requirements || []), '']);
  };

  // 更新所需资料
  const updateRequirement = (index: number, value: string) => {
    const newRequirements = [...(editForm?.content.requirements || [])];
    newRequirements[index] = value;
    updateContent('requirements', newRequirements);
  };

  // 删除所需资料
  const removeRequirement = (index: number) => {
    updateContent('requirements', editForm?.content.requirements.filter((_, i) => i !== index));
  };

  // 保存编辑
  const handleSave = async (id: string) => {
    if (!editForm) return;
    
    setSaving(true);
    try {
      const response = await fetch(`/api/admin/content/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          title: editForm.title,
          description: editForm.description,
          category: editForm.category,
          icon: editForm.icon,
          content: JSON.stringify(editForm.content),
          coverImage: editForm.coverImage,
          attachments: JSON.stringify(editForm.attachments),
          isActive: editForm.is_active,
        }),
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        setServices(prev => prev.map(s => 
          s.id === id ? { 
            ...s, 
            title: editForm.title,
            description: editForm.description,
            category: editForm.category,
            icon: editForm.icon,
            content: JSON.stringify(editForm.content),
            cover_image: editForm.coverImage,
            attachments: JSON.stringify(editForm.attachments),
            is_active: editForm.is_active
          } : s
        ));
        setEditingId(null);
        setEditForm(null);
      } else {
        alert(data.error || '保存失败');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('保存失败');
    } finally {
      setSaving(false);
    }
  };

  // 删除服务
  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这个服务吗？此操作不可恢复。')) return;
    
    try {
      const response = await fetch(`/api/admin/content/${id}`, {
        method: 'DELETE',
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        setServices(prev => prev.filter(s => s.id !== id));
      } else {
        alert(data.error || '删除失败');
      }
    } catch (error) {
      console.error('Error:', error);
      alert('删除失败');
    }
  };

  // 切换显示状态
  const handleToggleActive = async (id: string, currentStatus: boolean) => {
    try {
      const response = await fetch(`/api/admin/content/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ isActive: !currentStatus }),
      });
      
      const data = await response.json();
      if (response.ok && data.success) {
        setServices(prev => prev.map(s => 
          s.id === id ? { ...s, is_active: !currentStatus } : s
        ));
      }
    } catch (error) {
      console.error('Error:', error);
    }
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div className="flex items-center gap-4">
          <Link href="/admin" className="text-gray-400 hover:text-gray-600">
            <ArrowLeft className="w-5 h-5" />
          </Link>
          <div>
            <h1 className="text-2xl font-bold text-gray-900">服务内容管理</h1>
            <p className="text-gray-500 mt-1">编辑网站展示的服务项目，支持上传图片和文档</p>
          </div>
        </div>
      </div>

      {/* 服务列表 */}
      {isLoading ? (
        <div className="flex items-center justify-center py-20">
          <Loader2 className="w-8 h-8 text-blue-600 animate-spin" />
        </div>
      ) : (
        <div className="space-y-4">
          {services.map((service) => {
            const isEditing = editingId === service.id;
            const IconComponent = iconMap[service.icon || 'Truck'] || Truck;
            
            if (isEditing && editForm) {
              // 编辑模式 - 完整编辑表单
              return (
                <div key={service.id} className="bg-white rounded-2xl border border-blue-200 shadow-lg overflow-hidden">
                  {/* 编辑头部 */}
                  <div className="bg-gradient-to-r from-blue-600 to-indigo-600 px-6 py-4 flex items-center justify-between">
                    <div className="flex items-center gap-3 text-white">
                      <div className="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                        <IconComponent className="w-5 h-5" />
                      </div>
                      <div>
                        <div className="font-semibold">编辑服务：{service.id}</div>
                        <div className="text-blue-100 text-sm">修改后点击保存生效</div>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <button
                        onClick={() => handleSave(service.id)}
                        disabled={saving}
                        className="inline-flex items-center gap-2 px-4 py-2 bg-white text-blue-600 font-medium rounded-xl hover:bg-blue-50 disabled:opacity-50 transition-colors"
                      >
                        {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
                        保存
                      </button>
                      <button
                        onClick={handleCancelEdit}
                        className="inline-flex items-center gap-2 px-4 py-2 bg-white/20 text-white font-medium rounded-xl hover:bg-white/30 transition-colors"
                      >
                        <X className="w-4 h-4" />
                        取消
                      </button>
                    </div>
                  </div>

                  {/* 编辑内容 */}
                  <div className="p-6 space-y-6">
                    {/* 基本信息 */}
                    <div className="grid md:grid-cols-2 gap-4">
                      <div>
                        <label className="block text-sm font-medium text-gray-700 mb-1">服务标题</label>
                        <input
                          type="text"
                          value={editForm.title}
                          onChange={(e) => setEditForm(prev => prev ? { ...prev, title: e.target.value } : null)}
                          className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                        />
                      </div>
                      <div className="grid grid-cols-2 gap-4">
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">分类</label>
                          <select
                            value={editForm.category}
                            onChange={(e) => setEditForm(prev => prev ? { ...prev, category: e.target.value } : null)}
                            className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                          >
                            {categories.map(cat => (
                              <option key={cat} value={cat}>{cat}</option>
                            ))}
                          </select>
                        </div>
                        <div>
                          <label className="block text-sm font-medium text-gray-700 mb-1">图标</label>
                          <select
                            value={editForm.icon}
                            onChange={(e) => setEditForm(prev => prev ? { ...prev, icon: e.target.value } : null)}
                            className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                          >
                            {icons.map(icon => (
                              <option key={icon} value={icon}>{icon}</option>
                            ))}
                          </select>
                        </div>
                      </div>
                    </div>

                    {/* 服务描述 */}
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-1">服务描述</label>
                      <textarea
                        value={editForm.description}
                        onChange={(e) => setEditForm(prev => prev ? { ...prev, description: e.target.value } : null)}
                        rows={3}
                        className="w-full px-4 py-2 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                    </div>

                    {/* 封面图片 */}
                    <div>
                      <label className="block text-sm font-medium text-gray-700 mb-2">封面图片</label>
                      <div className="flex items-start gap-4">
                        {editForm.coverImage && (
                          <div className="relative w-40 h-24 rounded-xl overflow-hidden border border-gray-200">
                            <img src={editForm.coverImage} alt="封面" className="w-full h-full object-cover" />
                            <button
                              onClick={() => setEditForm(prev => prev ? { ...prev, coverImage: '' } : null)}
                              className="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center hover:bg-red-600"
                            >
                              <X className="w-4 h-4" />
                            </button>
                          </div>
                        )}
                        <button
                          onClick={() => coverInputRef.current?.click()}
                          disabled={uploading}
                          className="flex-1 h-24 border-2 border-dashed border-gray-300 rounded-xl flex flex-col items-center justify-center gap-1 hover:border-blue-400 hover:bg-blue-50 transition-colors"
                        >
                          {uploading ? (
                            <Loader2 className="w-6 h-6 text-blue-500 animate-spin" />
                          ) : (
                            <>
                              <Upload className="w-6 h-6 text-gray-400" />
                              <span className="text-sm text-gray-500">点击上传封面图片</span>
                            </>
                          )}
                        </button>
                        <input
                          ref={coverInputRef}
                          type="file"
                          accept="image/*"
                          className="hidden"
                          onChange={handleCoverUpload}
                        />
                      </div>
                    </div>

                    {/* 服务特点 */}
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium text-gray-700">服务特点</label>
                        <button
                          onClick={addFeature}
                          className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
                        >
                          <PlusCircle className="w-4 h-4" />
                          添加特点
                        </button>
                      </div>
                      <div className="space-y-2">
                        {editForm.content.features.map((feature, index) => (
                          <div key={index} className="flex items-center gap-2">
                            <input
                              type="text"
                              value={feature}
                              onChange={(e) => updateFeature(index, e.target.value)}
                              placeholder="输入服务特点"
                              className="flex-1 px-4 py-2 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                            />
                            <button
                              onClick={() => removeFeature(index)}
                              className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                            >
                              <MinusCircle className="w-5 h-5" />
                            </button>
                          </div>
                        ))}
                        {editForm.content.features.length === 0 && (
                          <div className="text-sm text-gray-400 py-4 text-center border border-dashed border-gray-200 rounded-xl">
                            暂无服务特点，点击上方按钮添加
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 服务流程 */}
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium text-gray-700">服务流程</label>
                        <button
                          onClick={addProcessStep}
                          className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
                        >
                          <PlusCircle className="w-4 h-4" />
                          添加步骤
                        </button>
                      </div>
                      <div className="space-y-3">
                        {editForm.content.process.map((step, index) => (
                          <div key={index} className="flex items-start gap-2 p-3 bg-gray-50 rounded-xl">
                            <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center text-white font-semibold flex-shrink-0">
                              {step.step}
                            </div>
                            <div className="flex-1 space-y-2">
                              <input
                                type="text"
                                value={step.title}
                                onChange={(e) => updateProcessStep(index, 'title', e.target.value)}
                                placeholder="步骤标题"
                                className="w-full px-3 py-1.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                              />
                              <input
                                type="text"
                                value={step.desc}
                                onChange={(e) => updateProcessStep(index, 'desc', e.target.value)}
                                placeholder="步骤描述"
                                className="w-full px-3 py-1.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                              />
                            </div>
                            <button
                              onClick={() => removeProcessStep(index)}
                              className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                            >
                              <MinusCircle className="w-5 h-5" />
                            </button>
                          </div>
                        ))}
                        {editForm.content.process.length === 0 && (
                          <div className="text-sm text-gray-400 py-4 text-center border border-dashed border-gray-200 rounded-xl">
                            暂无服务流程，点击上方按钮添加
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 进出口监管政策 */}
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium text-gray-700">进出口监管政策</label>
                        <button
                          onClick={addPolicy}
                          className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
                        >
                          <PlusCircle className="w-4 h-4" />
                          添加政策
                        </button>
                      </div>
                      <div className="space-y-3">
                        {editForm.content.policies.map((policy, index) => (
                          <div key={index} className="p-4 bg-amber-50 rounded-xl border border-amber-100">
                            <div className="flex items-start gap-3">
                              <select
                                value={policy.icon}
                                onChange={(e) => updatePolicy(index, 'icon', e.target.value)}
                                className="px-2 py-1 border border-amber-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-blue-500"
                              >
                                <option value="FileCheck">📄 文件</option>
                                <option value="Shield">🛡️ 盾牌</option>
                                <option value="AlertTriangle">⚠️ 警告</option>
                              </select>
                              <div className="flex-1 space-y-2">
                                <input
                                  type="text"
                                  value={policy.title}
                                  onChange={(e) => updatePolicy(index, 'title', e.target.value)}
                                  placeholder="政策标题"
                                  className="w-full px-3 py-1.5 border border-amber-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                />
                                <textarea
                                  value={policy.content}
                                  onChange={(e) => updatePolicy(index, 'content', e.target.value)}
                                  placeholder="政策内容"
                                  rows={2}
                                  className="w-full px-3 py-1.5 border border-amber-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                                />
                              </div>
                              <button
                                onClick={() => removePolicy(index)}
                                className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                              >
                                <MinusCircle className="w-5 h-5" />
                              </button>
                            </div>
                          </div>
                        ))}
                        {editForm.content.policies.length === 0 && (
                          <div className="text-sm text-gray-400 py-4 text-center border border-dashed border-gray-200 rounded-xl">
                            暂无监管政策，点击上方按钮添加
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 所需资料 */}
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium text-gray-700">所需资料</label>
                        <button
                          onClick={addRequirement}
                          className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
                        >
                          <PlusCircle className="w-4 h-4" />
                          添加资料
                        </button>
                      </div>
                      <div className="grid md:grid-cols-2 gap-2">
                        {editForm.content.requirements.map((req, index) => (
                          <div key={index} className="flex items-center gap-2">
                            <input
                              type="text"
                              value={req}
                              onChange={(e) => updateRequirement(index, e.target.value)}
                              placeholder="输入所需资料"
                              className="flex-1 px-4 py-2 border border-gray-200 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"
                            />
                            <button
                              onClick={() => removeRequirement(index)}
                              className="p-2 text-red-500 hover:bg-red-50 rounded-lg"
                            >
                              <MinusCircle className="w-5 h-5" />
                            </button>
                          </div>
                        ))}
                        {editForm.content.requirements.length === 0 && (
                          <div className="md:col-span-2 text-sm text-gray-400 py-4 text-center border border-dashed border-gray-200 rounded-xl">
                            暂无所需资料，点击上方按钮添加
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 附件上传 */}
                    <div>
                      <div className="flex items-center justify-between mb-2">
                        <label className="text-sm font-medium text-gray-700">相关文档/图片</label>
                        <button
                          onClick={() => fileInputRef.current?.click()}
                          disabled={uploading}
                          className="inline-flex items-center gap-1 text-sm text-blue-600 hover:text-blue-700"
                        >
                          {uploading ? <Loader2 className="w-4 h-4 animate-spin" /> : <PlusCircle className="w-4 h-4" />}
                          上传附件
                        </button>
                        <input
                          ref={fileInputRef}
                          type="file"
                          multiple
                          accept="image/*,.pdf,.doc,.docx,.xls,.xlsx,.txt"
                          className="hidden"
                          onChange={handleAttachmentUpload}
                        />
                      </div>
                      <div className="grid md:grid-cols-3 gap-3">
                        {editForm.attachments.map((att, index) => (
                          <div key={index} className="relative p-3 bg-gray-50 rounded-xl border border-gray-200 flex items-center gap-3">
                            {att.type === 'image' ? (
                              <img src={att.url} alt={att.name} className="w-12 h-12 object-cover rounded-lg" />
                            ) : (
                              <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                                <File className="w-6 h-6 text-blue-600" />
                              </div>
                            )}
                            <div className="flex-1 min-w-0">
                              <div className="text-sm font-medium text-gray-700 truncate">{att.name}</div>
                              <a 
                                href={att.url} 
                                target="_blank" 
                                rel="noopener noreferrer"
                                className="text-xs text-blue-600 hover:underline"
                              >
                                查看文件
                              </a>
                            </div>
                            <button
                              onClick={() => handleRemoveAttachment(index)}
                              className="p-1 text-red-500 hover:bg-red-50 rounded"
                            >
                              <X className="w-4 h-4" />
                            </button>
                          </div>
                        ))}
                        {editForm.attachments.length === 0 && (
                          <div className="md:col-span-3 text-sm text-gray-400 py-4 text-center border border-dashed border-gray-200 rounded-xl">
                            暂无附件，点击上方按钮上传
                          </div>
                        )}
                      </div>
                    </div>

                    {/* 显示状态 */}
                    <div className="flex items-center gap-3 p-4 bg-gray-50 rounded-xl">
                      <input
                        type="checkbox"
                        id="is_active"
                        checked={editForm.is_active}
                        onChange={(e) => setEditForm(prev => prev ? { ...prev, is_active: e.target.checked } : null)}
                        className="w-4 h-4 text-blue-600 rounded focus:ring-blue-500"
                      />
                      <label htmlFor="is_active" className="text-sm font-medium text-gray-700">
                        在前台显示此服务
                      </label>
                    </div>
                  </div>
                </div>
              );
            }

            // 列表模式 - 卡片显示
            return (
              <div key={service.id} className={`bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden ${!service.is_active ? 'opacity-50' : ''}`}>
                <div className="p-4 flex items-center justify-between">
                  <div className="flex items-center gap-4">
                    <div className="w-12 h-12 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-xl flex items-center justify-center">
                      <IconComponent className="w-6 h-6 text-blue-600" />
                    </div>
                    <div>
                      <div className="font-semibold text-gray-900">{service.title}</div>
                      <div className="text-sm text-gray-500">{service.category} • ID: {service.id}</div>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => handleToggleActive(service.id, service.is_active)}
                      className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                        service.is_active
                          ? 'bg-green-100 text-green-700 hover:bg-green-200'
                          : 'bg-gray-100 text-gray-500 hover:bg-gray-200'
                      }`}
                    >
                      {service.is_active ? <Eye className="w-4 h-4" /> : <EyeOff className="w-4 h-4" />}
                      {service.is_active ? '显示' : '隐藏'}
                    </button>
                    <button
                      onClick={() => handleEdit(service)}
                      className="inline-flex items-center gap-1 px-3 py-1.5 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors"
                    >
                      <Edit className="w-4 h-4" />
                      编辑
                    </button>
                    <button
                      onClick={() => handleDelete(service.id)}
                      className="inline-flex items-center gap-1 px-3 py-1.5 text-red-600 hover:bg-red-50 text-sm font-medium rounded-lg transition-colors"
                    >
                      <Trash2 className="w-4 h-4" />
                      删除
                    </button>
                  </div>
                </div>
                {service.description && (
                  <div className="px-4 pb-4 text-sm text-gray-500">
                    {service.description}
                  </div>
                )}
                {(service.cover_image || parseAttachments(service.attachments).length > 0) && (
                  <div className="px-4 pb-4 flex items-center gap-2 text-xs text-gray-400">
                    {service.cover_image && (
                      <span className="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 rounded">
                        <Image className="w-3 h-3" />
                        有封面
                      </span>
                    )}
                    {parseAttachments(service.attachments).length > 0 && (
                      <span className="inline-flex items-center gap-1 px-2 py-1 bg-gray-100 rounded">
                        <File className="w-3 h-3" />
                        {parseAttachments(service.attachments).length}个附件
                      </span>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* 操作说明 */}
      <div className="bg-gray-50 rounded-2xl p-6 border border-gray-100">
        <h3 className="text-sm font-semibold text-gray-900 mb-3">操作说明</h3>
        <ul className="space-y-2 text-sm text-gray-600">
          <li className="flex items-start gap-2">
            <span className="text-blue-600">•</span>
            点击「编辑」按钮可编辑完整的服务内容，包括流程、政策、所需资料等
          </li>
          <li className="flex items-start gap-2">
            <span className="text-blue-600">•</span>
            支持上传封面图片和相关文档（如PDF、Word、Excel等）
          </li>
          <li className="flex items-start gap-2">
            <span className="text-blue-600">•</span>
            编辑内容后，前台页面将实时更新显示
          </li>
          <li className="flex items-start gap-2">
            <span className="text-blue-600">•</span>
            隐藏的服务不会在前台显示，但数据仍保留
          </li>
        </ul>
      </div>
    </div>
  );
}
