import React, { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import {
  RefreshCw,
  AlertCircle,
  CheckCircle,
  XCircle,
  Clock,
  Timer,
  FileText
} from 'lucide-react';

import {
  FeieConfig,
  ConfigKey,
  ConfigType,
  UpdateConfigRequest,
  ConfigListResponse
} from '../types/feiePrinter';
import { createFeiePrinterClient } from '../api/feiePrinterClient';
import {
  Button,
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
  Badge,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  Input,
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
  Switch,
  Textarea
} from '@d8d/shared-ui-components';

// 配置分组
enum ConfigGroup {
  PRINT_POLICY = 'print_policy',
  TEMPLATE = 'template'
}

// 配置项定义
interface ConfigItemDefinition {
  key: ConfigKey;
  label: string;
  description: string;
  type: ConfigType;
  defaultValue: string;
  group: ConfigGroup;
  validation?: z.ZodType<any>;
  component?: 'input' | 'textarea' | 'switch' | 'select' | 'number';
  options?: { value: string; label: string }[];
  min?: number;
  max?: number;
  step?: number;
  hidden?: boolean; // 是否隐藏该配置项
}

// 配置项定义映射
const configDefinitions: ConfigItemDefinition[] = [
  {
    key: ConfigKey.ANTI_REFUND_DELAY,
    label: '防退款延迟时间（秒）',
    description: '支付成功后等待确认无退款的时间，默认120秒（2分钟）',
    type: ConfigType.NUMBER,
    defaultValue: '120',
    group: ConfigGroup.PRINT_POLICY,
    component: 'number',
    min: 0,
    max: 600,
    step: 10
  },
  {
    key: ConfigKey.RECEIPT_TEMPLATE,
    label: '小票模板',
    description: '小票打印的模板内容，支持变量替换',
    type: ConfigType.STRING,
    defaultValue: `订单号: {orderNo}
时间: {orderTime}
商品: {goodsList}
合计: {totalAmount}
地址: {address}
联系电话: {phone}`,
    group: ConfigGroup.TEMPLATE,
    component: 'textarea'
  },
  {
    key: ConfigKey.SHIPPING_TEMPLATE,
    label: '发货单模板',
    description: '发货单打印的模板内容，支持变量替换',
    type: ConfigType.STRING,
    defaultValue: `发货单
订单号: {orderNo}
发货时间: {shippingTime}
收货人: {receiver}
地址: {address}
联系电话: {phone}
商品列表:
{goodsList}`,
    group: ConfigGroup.TEMPLATE,
    component: 'textarea',
    hidden: true // 隐藏发货单模板配置项
  }
];


// 配置类型标签映射
const typeLabelMap: Record<ConfigType, string> = {
  [ConfigType.STRING]: '字符串',
  [ConfigType.JSON]: 'JSON',
  [ConfigType.BOOLEAN]: '布尔值',
  [ConfigType.NUMBER]: '数字'
};

// 从JWT token中解析租户ID
const parseTenantIdFromToken = (token: string | null | undefined): number | undefined => {
  if (!token) return undefined;

  try {
    // JWT token格式: header.payload.signature
    const parts = token.split('.');
    if (parts.length !== 3) return undefined;

    // 解码payload部分
    const payload = JSON.parse(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')));

    // 从payload中获取tenantId
    // 可能是tenantId、tenant_id或tenant
    return payload.tenantId || payload.tenant_id || payload.tenant;
  } catch (error) {
    console.error('解析token失败:', error);
    return undefined;
  }
};

// 配置类型颜色映射
const typeColorMap: Record<ConfigType, string> = {
  [ConfigType.STRING]: 'bg-blue-100 text-blue-800 border-blue-200',
  [ConfigType.JSON]: 'bg-purple-100 text-purple-800 border-purple-200',
  [ConfigType.BOOLEAN]: 'bg-green-100 text-green-800 border-green-200',
  [ConfigType.NUMBER]: 'bg-orange-100 text-orange-800 border-orange-200'
};

// 更新配置表单验证模式
const updateConfigSchema = z.object({
  configValue: z.string().min(1, '配置值不能为空')
});

type UpdateConfigFormValues = z.infer<typeof updateConfigSchema>;

export interface PrintConfigManagementProps {
  /**
   * API基础URL
   * @default '/api'
   */
  baseURL?: string;
  /**
   * 租户ID
   */
  tenantId?: number;
  /**
   * 认证token
   */
  authToken?: string;
}

/**
 * 打印配置管理组件
 * 提供打印配置的查询、编辑和管理功能
 */
export const PrintConfigManagement: React.FC<PrintConfigManagementProps> = ({
  baseURL = '/api/v1/feie',
  tenantId: propTenantId,
  authToken: propAuthToken
}) => {
  // 从token中解析租户ID
  const token = propAuthToken || localStorage.getItem('token');
  const parsedTenantId = parseTenantIdFromToken(token);
  const tenantId = propTenantId || parsedTenantId;
  const authToken = propAuthToken || token;

  const [activeGroup, setActiveGroup] = useState<ConfigGroup>(ConfigGroup.PRINT_POLICY);
  const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
  const [selectedConfig, setSelectedConfig] = useState<FeieConfig | null>(null);
  const [configMap, setConfigMap] = useState<Record<string, FeieConfig>>({});
  const [groupEdits, setGroupEdits] = useState<Record<string, string>>({});

  const queryClient = useQueryClient();
  const feieClient = createFeiePrinterClient(baseURL);

  // 设置认证和租户信息
  useEffect(() => {
    if (authToken) {
      feieClient.setAuthToken(authToken);
    }
    if (tenantId) {
      feieClient.setTenantId(tenantId);
    }
  }, [authToken, tenantId, feieClient]);

  // 当租户ID变化时，重新获取配置数据
  useEffect(() => {
    if (tenantId) {
      queryClient.invalidateQueries({ queryKey: ['printConfigs', tenantId] });
    }
  }, [tenantId, queryClient]);

  // 查询配置列表
  const {
    data: configList,
    isLoading,
    isError,
    refetch
  } = useQuery<ConfigListResponse>({
    queryKey: ['printConfigs', tenantId],
    queryFn: async () => {
      // 确保认证信息已设置
      if (authToken) {
        feieClient.setAuthToken(authToken);
      }
      if (tenantId) {
        feieClient.setTenantId(tenantId);
      }
      return feieClient.getPrintConfigs();
    },
    enabled: !!tenantId,
    staleTime: 0, // 设置为0，每次重新进入页面都重新获取
    gcTime: 0, // 设置为0，不缓存数据
    refetchOnMount: true, // 组件挂载时重新获取
    refetchOnWindowFocus: true, // 窗口获得焦点时重新获取
    onError: (error: Error) => {
      toast.error(`获取配置列表失败: ${error.message}`);
    }
  });

  // 当租户ID准备好时，立即重新获取数据
  useEffect(() => {
    if (tenantId) {
      // 使用 setTimeout 确保在下一个事件循环中执行，避免渲染阻塞
      const timer = setTimeout(() => {
        refetch();
      }, 0);
      return () => clearTimeout(timer);
    }
  }, [tenantId, refetch]);

  // 当配置数据加载成功后，更新配置映射
  useEffect(() => {
    console.debug('configList 数据:', configList);

    // 处理 configList 数据：可能是 ConfigListResponse 或直接是 FeieConfig[]
    let configArray: FeieConfig[] = [];

    if (configList) {
      // 检查是否是 ConfigListResponse 类型（有 data 属性）
      if ('data' in configList && Array.isArray(configList.data)) {
        console.debug('configList 是 ConfigListResponse 类型');
        configArray = configList.data;
      } else if (Array.isArray(configList)) {
        // 直接是 FeieConfig[] 数组
        console.debug('configList 是 FeieConfig[] 数组类型');
        configArray = configList;
      }
    }

    console.debug('configArray:', configArray);

    if (configArray.length > 0) {
      const map: Record<string, FeieConfig> = {};
      configArray.forEach((config: FeieConfig) => {
        console.debug(`映射配置: key=${config.configKey}, value=${config.configValue}`);
        map[config.configKey] = config;
      });
      console.debug('生成的 configMap:', map);
      setConfigMap(map);
    } else {
      console.debug('没有配置数据');
    }
  }, [configList]);

  // 当切换分组时，清空分组编辑记录
  useEffect(() => {
    setGroupEdits({});
  }, [activeGroup]);

  // 更新配置表单
  const updateForm = useForm<UpdateConfigFormValues>({
    resolver: zodResolver(updateConfigSchema),
    defaultValues: {
      configValue: ''
    }
  });

  // 更新配置Mutation（用于编辑对话框）
  const updateConfigMutation = useMutation({
    mutationFn: ({ configKey, data }: { configKey: string; data: UpdateConfigRequest }) =>
      feieClient.updatePrintConfig(configKey, data),
    onSuccess: (savedConfig) => {
      toast.success('配置更新成功');
      setIsEditDialogOpen(false);
      setSelectedConfig(null);

      // 立即更新本地配置映射
      if (savedConfig && savedConfig.configKey) {
        setConfigMap(prev => ({
          ...prev,
          [savedConfig.configKey]: savedConfig
        }));
      }

      // 强制重新获取数据并等待完成
      refetch().then(() => {
        console.debug('配置更新后数据重新获取完成');
      }).catch(error => {
        console.error('配置更新后重新获取数据失败:', error);
      });
    },
    onError: (error: Error) => {
      toast.error(`更新配置失败: ${error.message}`);
    }
  });



  // 重置配置Mutation
  const resetConfigMutation = useMutation({
    mutationFn: async (configKey: string) => {
      const definition = configDefinitions.find(def => def.key === configKey);
      if (!definition) throw new Error('配置定义不存在');

      return feieClient.updatePrintConfig(configKey, {
        configValue: definition.defaultValue
      });
    },
    onSuccess: (savedConfig) => {
      toast.success('配置重置成功');

      // 立即更新本地配置映射
      if (savedConfig && savedConfig.configKey) {
        setConfigMap(prev => ({
          ...prev,
          [savedConfig.configKey]: savedConfig
        }));
      }

      // 强制重新获取数据并等待完成
      refetch().then(() => {
        console.debug('配置重置后数据重新获取完成');
      }).catch(error => {
        console.error('配置重置后重新获取数据失败:', error);
      });
    },
    onError: (error: Error) => {
      toast.error(`重置配置失败: ${error.message}`);
    }
  });

  // 处理更新配置
  const handleUpdateConfig = (data: UpdateConfigFormValues) => {
    if (!selectedConfig) return;
    updateConfigMutation.mutate({
      configKey: selectedConfig.configKey,
      data
    });
  };

  // 打开编辑对话框（暂时注释掉未使用的函数）
  // const openEditDialog = (config: FeieConfig) => {
  //   setSelectedConfig(config);
  //   updateForm.reset({
  //     configValue: config.configValue
  //   });
  //   setIsEditDialogOpen(true);
  // };

  // 批量保存配置Mutation
  const batchSaveConfigMutation = useMutation({
    mutationFn: async (edits: Record<string, string>) => {
      const promises = Object.entries(edits).map(([configKey, configValue]) =>
        feieClient.updatePrintConfig(configKey, { configValue })
      );
      return Promise.all(promises);
    },
    onSuccess: (savedConfigs) => {
      toast.success('批量保存成功');
      // 清空编辑记录
      setGroupEdits({});

      // 立即更新本地配置映射
      if (savedConfigs && Array.isArray(savedConfigs)) {
        const updatedMap = { ...configMap };
        savedConfigs.forEach((config: FeieConfig) => {
          if (config && config.configKey) {
            updatedMap[config.configKey] = config;
          }
        });
        setConfigMap(updatedMap);
      }

      // 强制重新获取数据并等待完成
      refetch().then(() => {
        console.debug('批量保存后数据重新获取完成');
      }).catch(error => {
        console.error('批量保存后重新获取数据失败:', error);
      });
    },
    onError: (error: Error) => {
      toast.error(`批量保存失败: ${error.message}`);
    }
  });


  // 处理分组批量保存
  const handleGroupBatchSave = () => {
    const editsToSave = Object.entries(groupEdits).filter(([key, value]) => {
      const currentValue = getConfigValue(key);
      return value !== currentValue;
    });

    if (editsToSave.length === 0) {
      toast.info('没有需要保存的修改');
      return;
    }

    const editsObject = Object.fromEntries(editsToSave);
    batchSaveConfigMutation.mutate(editsObject);
  };

  // 处理重置配置
  const handleResetConfig = (configKey: string) => {
    resetConfigMutation.mutate(configKey);
  };

  // 获取配置值
  const getConfigValue = (configKey: string): string => {
    const config = configMap[configKey];
    console.debug(`getConfigValue: key=${configKey}, config=`, config);

    // 如果配置存在且有值，返回配置值
    if (config && config.configValue !== undefined && config.configValue !== null) {
      console.debug(`返回数据库值: ${config.configValue}`);
      return config.configValue;
    }

    // 如果配置不存在且数据正在加载中，返回空字符串
    if (isLoading) {
      console.debug('数据加载中，返回空字符串');
      return '';
    }

    // 如果配置不存在且数据加载完成，返回默认值
    const definition = configDefinitions.find(def => def.key === configKey);
    const defaultValue = definition?.defaultValue || '';
    console.debug(`配置不存在，返回默认值: ${defaultValue}`);
    return defaultValue;
  };

  // 渲染配置项组件（批量保存模式）
  const renderBatchConfigItem = (definition: ConfigItemDefinition) => {
    const value = getConfigValue(definition.key);
    const editedValue = groupEdits[definition.key];
    console.debug(`renderBatchConfigItem: key=${definition.key}, value=${value}, editedValue=${editedValue}`);

    return (
      <div key={definition.key} className="space-y-2">
        <div className="flex items-center justify-between">
          <div>
            <h4 className="font-medium">{definition.label}</h4>
            <p className="text-sm text-muted-foreground">{definition.description}</p>
          </div>
          <div className="flex items-center space-x-2">
            <Badge variant="outline" className={typeColorMap[definition.type]}>
              {typeLabelMap[definition.type]}
            </Badge>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => handleResetConfig(definition.key)}
              disabled={resetConfigMutation.isPending}
              title="重置为默认值"
            >
              <RefreshCw className="h-4 w-4" />
            </Button>
          </div>
        </div>

        {definition.component === 'switch' ? (
          <div className="flex items-center space-x-2">
            <Switch
              checked={editedValue !== undefined ? editedValue === 'true' : value === 'true'}
              onCheckedChange={(checked) => {
                const newValue = checked.toString();
                setGroupEdits(prev => ({ ...prev, [definition.key]: newValue }));
              }}
            />
            <span className="text-sm">
              {editedValue !== undefined
                ? (editedValue === 'true' ? '已启用' : '已禁用')
                : (value === 'true' ? '已启用' : '已禁用')}
            </span>
            {editedValue !== undefined && editedValue !== value && (
              <div className="h-2 w-2 rounded-full bg-blue-500 animate-pulse" title="有未保存的修改" />
            )}
          </div>
        ) : definition.component === 'textarea' ? (
          <div className="relative">
            <Textarea
              value={editedValue !== undefined ? editedValue : value}
              onChange={(e) => {
                const newValue = e.target.value;
                setGroupEdits(prev => ({ ...prev, [definition.key]: newValue }));
              }}
              rows={6}
              className="font-mono text-sm"
            />
            {editedValue !== undefined && editedValue !== value && (
              <div className="absolute right-2 top-2">
                <div className="h-2 w-2 rounded-full bg-blue-500 animate-pulse" title="有未保存的修改" />
              </div>
            )}
          </div>
        ) : definition.component === 'number' ? (
          <div className="flex items-center space-x-2">
            <div className="relative">
              <Input
                type="number"
                value={editedValue !== undefined ? editedValue : value}
                onChange={(e) => {
                  const newValue = e.target.value;
                  setGroupEdits(prev => ({ ...prev, [definition.key]: newValue }));
                }}
                min={definition.min}
                max={definition.max}
                step={definition.step}
                className="w-32"
              />
              {editedValue !== undefined && editedValue !== value && (
                <div className="absolute -right-6 top-1/2 transform -translate-y-1/2">
                  <div className="h-2 w-2 rounded-full bg-blue-500 animate-pulse" title="有未保存的修改" />
                </div>
              )}
            </div>
            {definition.key === ConfigKey.ANTI_REFUND_DELAY && (
              <span className="text-sm text-muted-foreground">
                ({Math.floor(parseInt(editedValue !== undefined ? editedValue : value) / 60)}分{parseInt(editedValue !== undefined ? editedValue : value) % 60}秒)
              </span>
            )}
          </div>
        ) : (
          <div className="relative">
            <Input
              value={editedValue !== undefined ? editedValue : value}
              onChange={(e) => {
                const newValue = e.target.value;
                setGroupEdits(prev => ({ ...prev, [definition.key]: newValue }));
              }}
              placeholder={`请输入${definition.label}`}
            />
            {editedValue !== undefined && editedValue !== value && (
              <div className="absolute -right-6 top-1/2 transform -translate-y-1/2">
                <div className="h-2 w-2 rounded-full bg-blue-500 animate-pulse" title="有未保存的修改" />
              </div>
            )}
          </div>
        )}
      </div>
    );
  };


  return (
    <div className="space-y-6">
      {/* 标题和操作栏 */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">打印配置管理</h2>
          <p className="text-muted-foreground">
            管理飞鹅打印的配置项，包括基础配置、打印策略和模板配置
          </p>
        </div>
        <div className="flex items-center space-x-2">
          <Button
            variant="outline"
            onClick={() => refetch()}
            disabled={isLoading}
          >
            <RefreshCw className={`mr-2 h-4 w-4 ${isLoading ? 'animate-spin' : ''}`} />
            刷新
          </Button>
        </div>
      </div>

      {/* 配置分组按钮 */}
      <div className="flex space-x-2 mb-4">
        <Button
          variant={activeGroup === ConfigGroup.PRINT_POLICY ? "default" : "outline"}
          onClick={() => setActiveGroup(ConfigGroup.PRINT_POLICY)}
          className="flex items-center"
        >
          <Timer className="mr-2 h-4 w-4" />
          打印策略
        </Button>
        <Button
          variant={activeGroup === ConfigGroup.TEMPLATE ? "default" : "outline"}
          onClick={() => setActiveGroup(ConfigGroup.TEMPLATE)}
          className="flex items-center"
        >
          <FileText className="mr-2 h-4 w-4" />
          模板配置
        </Button>
      </div>

      {/* 加载状态 */}
      {isLoading ? (
        <Card className="mt-4">
          <CardContent className="pt-6">
            <div className="flex items-center justify-center py-8">
              <div className="text-center">
                <RefreshCw className="h-8 w-8 animate-spin mx-auto text-muted-foreground" />
                <p className="mt-2 text-sm text-muted-foreground">加载配置中...</p>
              </div>
            </div>
          </CardContent>
        </Card>
      ) : isError ? (
        <Card className="mt-4">
          <CardContent className="pt-6">
            <div className="flex items-center justify-center py-8">
              <div className="text-center">
                <AlertCircle className="h-8 w-8 mx-auto text-red-500" />
                <p className="mt-2 text-sm text-red-600">加载配置失败</p>
                <Button
                  variant="outline"
                  size="sm"
                  className="mt-4"
                  onClick={() => refetch()}
                >
                  重试
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      ) : (
        <>

          {/* 打印策略 */}
          {activeGroup === ConfigGroup.PRINT_POLICY && (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>打印策略</CardTitle>
                    <CardDescription>
                      配置打印任务的触发条件、重试策略和超时设置
                    </CardDescription>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Button
                      onClick={handleGroupBatchSave}
                      disabled={isLoading || batchSaveConfigMutation.isPending || Object.keys(groupEdits).length === 0}
                      size="sm"
                    >
                      {batchSaveConfigMutation.isPending ? (
                        <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                      ) : (
                        <CheckCircle className="mr-2 h-4 w-4" />
                      )}
                      批量保存
                      {Object.keys(groupEdits).length > 0 && (
                        <span className="ml-2 h-2 w-2 rounded-full bg-blue-500 animate-pulse" />
                      )}
                    </Button>
                    {Object.keys(groupEdits).length > 0 && (
                      <Button
                        onClick={() => setGroupEdits({})}
                        variant="outline"
                        size="sm"
                        disabled={batchSaveConfigMutation.isPending}
                      >
                        <XCircle className="mr-2 h-4 w-4" />
                        取消编辑
                      </Button>
                    )}
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                {configDefinitions
                  .filter(def => def.group === ConfigGroup.PRINT_POLICY && !def.hidden)
                  .map(renderBatchConfigItem)}

                {/* 策略说明 */}
                <div className="rounded-lg border bg-muted/50 p-4">
                  <h4 className="font-medium mb-2">策略说明</h4>
                  <ul className="text-sm text-muted-foreground space-y-1">
                    <li className="flex items-start">
                      <Clock className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
                      <span>
                        <strong>防退款延迟</strong>: 支付成功后等待指定时间确认无退款再打印，避免无效打印
                      </span>
                    </li>
                  </ul>
                </div>
              </CardContent>
            </Card>
          )}

          {/* 模板配置 */}
          {activeGroup === ConfigGroup.TEMPLATE && (
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>模板配置</CardTitle>
                    <CardDescription>
                      配置小票和发货单的打印模板，支持变量替换
                    </CardDescription>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Button
                      onClick={handleGroupBatchSave}
                      disabled={isLoading || batchSaveConfigMutation.isPending || Object.keys(groupEdits).length === 0}
                      size="sm"
                    >
                      {batchSaveConfigMutation.isPending ? (
                        <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
                      ) : (
                        <CheckCircle className="mr-2 h-4 w-4" />
                      )}
                      批量保存
                      {Object.keys(groupEdits).length > 0 && (
                        <span className="ml-2 h-2 w-2 rounded-full bg-blue-500 animate-pulse" />
                      )}
                    </Button>
                    {Object.keys(groupEdits).length > 0 && (
                      <Button
                        onClick={() => setGroupEdits({})}
                        variant="outline"
                        size="sm"
                        disabled={batchSaveConfigMutation.isPending}
                      >
                        <XCircle className="mr-2 h-4 w-4" />
                        取消编辑
                      </Button>
                    )}
                  </div>
                </div>
              </CardHeader>
              <CardContent className="space-y-6">
                {configDefinitions
                  .filter(def => def.group === ConfigGroup.TEMPLATE && !def.hidden)
                  .map(renderBatchConfigItem)}

                {/* 模板变量说明 */}
                <div className="rounded-lg border bg-muted/50 p-4">
                  <h4 className="font-medium mb-2">可用变量</h4>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <h5 className="text-sm font-medium mb-1">订单信息</h5>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li><code>{'{orderNo}'}</code> - 订单号</li>
                        <li><code>{'{orderTime}'}</code> - 订单时间</li>
                        <li><code>{'{totalAmount}'}</code> - 订单总金额</li>
                        <li><code>{'{paymentMethod}'}</code> - 支付方式</li>
                      </ul>
                    </div>
                    <div>
                      <h5 className="text-sm font-medium mb-1">收货信息</h5>
                      <ul className="text-sm text-muted-foreground space-y-1">
                        <li><code>{'{receiverName}'}</code> - 收货人姓名</li>
                        <li><code>{'{phone}'}</code> - 联系电话</li>
                        <li><code>{'{address}'}</code> - 收货地址</li>
                        <li><code>{'{shippingTime}'}</code> - 发货时间</li>
                      </ul>
                    </div>
                  </div>
                  <div className="mt-4">
                    <h5 className="text-sm font-medium mb-1">商品信息</h5>
                    <ul className="text-sm text-muted-foreground space-y-1">
                      <li><code>{'{goodsList}'}</code> - 商品列表（自动格式化）</li>
                      <li><code>{'{goodsName}'}</code> - 商品名称</li>
                      <li><code>{'{goodsPrice}'}</code> - 商品价格</li>
                      <li><code>{'{goodsQuantity}'}</code> - 商品数量</li>
                    </ul>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}
        </>
      )}


      {/* 编辑配置对话框 */}
      <Dialog open={isEditDialogOpen} onOpenChange={setIsEditDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>编辑配置</DialogTitle>
            <DialogDescription>
              修改配置项 "{selectedConfig?.configKey}" 的值
            </DialogDescription>
          </DialogHeader>
          <Form {...updateForm}>
            <form onSubmit={updateForm.handleSubmit(handleUpdateConfig)} className="space-y-4">
              {selectedConfig && (
                <>
                  <div className="rounded-lg border p-4">
                    <div className="space-y-2">
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">配置键</span>
                        <span className="font-mono text-sm">{selectedConfig.configKey}</span>
                      </div>
                      <div className="flex items-center justify-between">
                        <span className="text-sm font-medium">类型</span>
                        <Badge variant="outline" className={typeColorMap[selectedConfig.configType]}>
                          {typeLabelMap[selectedConfig.configType]}
                        </Badge>
                      </div>
                      {selectedConfig.description && (
                        <div>
                          <span className="text-sm font-medium">描述</span>
                          <p className="text-sm text-muted-foreground mt-1">
                            {selectedConfig.description}
                          </p>
                        </div>
                      )}
                    </div>
                  </div>

                  <FormField
                    control={updateForm.control}
                    name="configValue"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>配置值</FormLabel>
                        {selectedConfig.configType === ConfigType.BOOLEAN ? (
                          <Select onValueChange={field.onChange} defaultValue={field.value}>
                            <FormControl>
                              <SelectTrigger>
                                <SelectValue placeholder="选择配置值" />
                              </SelectTrigger>
                            </FormControl>
                            <SelectContent>
                              <SelectItem value="true">是（启用）</SelectItem>
                              <SelectItem value="false">否（禁用）</SelectItem>
                            </SelectContent>
                          </Select>
                        ) : selectedConfig.configType === ConfigType.JSON ? (
                          <FormControl>
                            <Textarea
                              placeholder="请输入JSON格式的配置值"
                              className="font-mono text-sm"
                              rows={6}
                              {...field}
                            />
                          </FormControl>
                        ) : (
                          <FormControl>
                            <Input placeholder="请输入配置值" {...field} />
                          </FormControl>
                        )}
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </>
              )}
              <DialogFooter>
                <Button
                  type="button"
                  variant="outline"
                  onClick={() => setIsEditDialogOpen(false)}
                  disabled={updateConfigMutation.isPending}
                >
                  取消
                </Button>
                <Button type="submit" disabled={updateConfigMutation.isPending}>
                  {updateConfigMutation.isPending ? '更新中...' : '更新配置'}
                </Button>
              </DialogFooter>
            </form>
          </Form>
        </DialogContent>
      </Dialog>
    </div>
  );
};