import { createContext, useState, useContext, ReactNode, FC, useCallback } from 'react';

interface LocaleContextType {
  locale: string;
  setLocale: (locale: string) => void;
  t: (key: string, options?: Record<string, any>) => string;
}

const zhCN = {
  'app.name': 'Crawlful Hub',
  'app.title': '跨境电商管理平台',
  'nav.home': '首页',
  'nav.dashboard': '控制台',
  'nav.products': '商品管理',
  'nav.orders': '订单管理',
  'nav.inventory': '库存管理',
  'nav.logistics': '物流管理',
  'nav.finance': '财务管理',
  'nav.marketing': '营销管理',
  'nav.analytics': '数据分析',
  'nav.settings': '系统设置',
  'login.title': '欢迎回来',
  'login.subtitle': '登录您的账户',
  'login.username': '用户名或邮箱',
  'login.password': '密码',
  'login.remember': '记住我',
  'login.forgot': '忘记密码？',
  'login.submit': '登录',
  'login.noAccount': '还没有账户？',
  'login.signup': '立即注册',
  'login.verificationCode': '验证码',
  'login.loginSuccess': '登录成功，正在跳转...',
  'login.loginFailed': '登录失败，请检查您的凭证',
  'login.invalidCaptcha': '验证码错误',
  'login.orContinueWith': '或使用以下方式登录',
  'login.welcomeBack': '欢迎回来',
  'dashboard.title': '控制台',
  'dashboard.totalSales': '总销售额',
  'dashboard.orders': '订单数',
  'dashboard.conversion': '转化率',
  'dashboard.avgOrderValue': '平均订单价值',
  'dashboard.salesTrend': '销售与订单趋势',
  'dashboard.topProducts': '热销商品',
  'dashboard.recentOrders': '最近订单',
  'dashboard.refresh': '刷新',
  'dashboard.export': '导出',
  'dashboard.customize': '自定义',
  'dashboard.allShops': '所有店铺',
  'common.search': '搜索',
  'common.reset': '重置',
  'common.confirm': '确认',
  'common.cancel': '取消',
  'common.save': '保存',
  'common.delete': '删除',
  'common.edit': '编辑',
  'common.add': '添加',
  'common.view': '查看',
  'common.submit': '提交',
  'common.loading': '加载中...',
  'common.noData': '暂无数据',
  'common.success': '操作成功',
  'common.error': '操作失败',
  'common.warning': '警告',
  'common.info': '提示',
  'common.yes': '是',
  'common.no': '否',
  'common.all': '全部',
  'common.select': '请选择',
  'common.required': '必填',
  'common.optional': '选填',
  'common.up': '上升',
  'common.down': '下降',
  'product.list': '商品列表',
  'product.add': '添加商品',
  'product.edit': '编辑商品',
  'product.delete': '删除商品',
  'product.name': '商品名称',
  'product.price': '价格',
  'product.stock': '库存',
  'product.status': '状态',
  'product.category': '分类',
  'order.list': '订单列表',
  'order.detail': '订单详情',
  'order.status': '订单状态',
  'order.amount': '订单金额',
  'order.date': '下单日期',
  'order.customer': '客户信息',
  'settings.title': '系统设置',
  'settings.profile': '个人资料',
  'settings.system': '系统配置',
  'settings.users': '用户管理',
  'settings.language': '语言设置',
  'settings.theme': '主题设置',
  // Menu translations
  'menu.dashboard': '数据概览',
  'menu.aiOperations': 'AI运营中心',
  'menu.operationAgent': '运营Agent',
  'menu.autoPilot': '自动驾驶',
  'menu.taskCenter': '任务中心',
  'menu.taskManager': '任务管理',
  'menu.aiSuggestion': 'AI建议',
  'menu.humanApproval': '人工确认',
  'menu.clientManagement': '客户端管理',
  'menu.executionResults': '执行结果',
  'menu.aiDecisionLog': 'AI决策日志',
  'menu.strategyMarketplace': '策略市场',
  'menu.autoProductSelection': '自动选品',
  'menu.autoExecution': '自动执行',
  'menu.productCycle': '商品闭环',
  'menu.productManagement': '商品管理',
  'menu.productPublish': '商品发布',
  'menu.inventoryManagement': '库存管理',
  'menu.warehouseManagement': '仓库管理',
  'menu.aiPricing': 'AI定价',
  'menu.profitMonitor': '利润监控',
  'menu.orderCycle': '订单闭环',
  'menu.orderManagement': '订单管理',
  'menu.exceptionOrders': '异常订单',
  'menu.afterSales': '售后服务',
  'menu.refundProcessing': '退款处理',
  'menu.logisticsCycle': '物流闭环',
  'menu.logisticsQuery': '物流查询',
  'menu.freightCalculation': '运费计算',
  'menu.financeCycle': '财务闭环',
  'menu.financeOverview': '财务概览',
  'menu.transactionRecords': '交易记录',
  'menu.financeReconciliation': '财务对账',
  'menu.userAssets': '用户资产',
  'menu.marketingCycle': '营销闭环',
  'menu.adManagement': '广告管理',
  'menu.competitorAnalysis': '竞品分析',
  'menu.dynamicPricing': '动态定价',
  'menu.abTest': 'AB测试',
  'menu.analytics': '数据分析',
  'menu.dataAnalysis': '数据分析',
  'menu.reportCenter': '报表中心',
  'menu.multiShopReport': '多店报表',
  'menu.leaderboard': '收益排行',
  'menu.b2bTrade': 'B2B贸易',
  'menu.merchantManagement': '商户管理',
  'menu.b2bTradeManagement': 'B2B贸易',
  'menu.batchOrder': '批量订单',
  'menu.enterpriseQuote': '企业报价',
  'menu.contractManagement': '合同管理',
  'menu.procurementManagement': '采购管理',
  'menu.suppliers': '供应商',
  'menu.warehouseInventory': '仓库库存',
  'menu.independentSite': '独立站',
  'menu.siteManagement': '站点管理',
  'menu.createSite': '创建站点',
  'menu.siteTemplates': '站点模板',
  'menu.siteAnalytics': '站点分析',
  'menu.independentSiteOrders': '独立站订单',
  'menu.independentSiteProducts': '独立站商品',
  'menu.domainManagement': '域名管理',
  'menu.riskCompliance': '风控合规',
  'menu.riskMonitoring': '风险监控',
  'menu.complianceCheck': '合规检查',
  'menu.auditLogs': '审计日志',
  'menu.operationLogs': '操作日志',
  'menu.governanceCenter': '治理中心',
  'menu.sovereigntyManagement': '主权管理',
  'menu.certificateManagement': '证书管理',
  'menu.settings': '系统设置',
  'menu.settingsOverview': '设置概览',
  'menu.platformAuth': '平台授权',
  'menu.serviceManager': '服务管理',
  'menu.userManagement': '用户管理',
  'menu.rolePermissions': '角色权限',
  // Product publish form translations
  'product.publish.title': '商品发布',
  'product.publish.basicInfo': '基本信息',
  'product.publish.variants': '商品变体',
  'product.publish.images': '商品图片',
  'product.publish.materialProcessing': 'AI素材处理',
  'product.publish.materialProcessingDesc': '上传图片后，可使用AI进行图生图、图生视频等处理。点击已上传图片上的AI按钮开始处理。',
  'product.publish.selectImage': '请先选择要处理的图片',
  'product.publish.taskCreated': '任务已创建: {id}',
  'product.publish.processingComplete': '素材处理完成！',
  'product.publish.videoGenerated': '视频已生成，可在素材库中查看',
  'product.publish.processFailed': '处理失败',
  'product.publish.saveLocal': 'Step 1: 先保存到本地系统',
  'product.publish.pendingSync': '待同步状态',
  'product.publish.saveToDatabase': '模拟保存到本地数据库',
  'product.publish.complianceCheck': 'Step 2: 合规检查（本地进行）',
  'product.publish.submitReview': 'Step 3: 提交审核（本地状态变更）',
  'product.publish.resetForm': '重置表单',
  'product.publish.processingTasks': '处理中的任务',
  'product.publish.imageToImage': '图生图',
  'product.publish.imageToVideo': '图生视频',
  'product.publish.originalPreview': '原图预览：',
  'product.publish.prompt': '提示词',
  'product.publish.promptPlaceholder': '描述你想要生成的图片效果...',
  'product.publish.style': '风格',
  'product.publish.strength': '转换强度',
  'product.publish.motion': '运动类型',
  'product.publish.motionZoom': '缩放',
  'product.publish.motionPan': '平移',
  'product.publish.motionRotate': '旋转',
  'product.publish.motionDynamic': '动态',
  'product.publish.duration': '时长(秒)',
  'product.publish.fps': '帧率',
  'product.publish.startProcessing': '开始处理',
  'product.publish.cancel': '取消',
  // Product publish form additional translations
  'product.publish.productImages': '商品图片',
  'product.publish.images': '图片',
  'product.publish.upload': '上传',
  'product.publish.pricing': '定价',
  'product.publish.profitMarginValidation': '利润率验证',
  'product.publish.profitMarginDesc': 'B2B商品必须保持至少15%的利润率。B2C商品要求最低20%。',
  'product.publish.sellingPrice': '销售价格',
  'product.publish.enterPrice': '请输入价格',
  'product.publish.costPrice': '成本价格',
  'product.publish.enterCostPrice': '请输入成本价格',
  'product.publish.currency': '货币',
  'product.publish.draftSaved': '草稿保存成功',
  'product.publish.fillRequiredFields': '请填写必填字段',
};

const enUS = {
  'app.name': 'Crawlful Hub',
  'app.title': 'Cross-Border E-commerce Management Platform',
  'nav.home': 'Home',
  'nav.dashboard': 'Dashboard',
  'nav.products': 'Products',
  'nav.orders': 'Orders',
  'nav.inventory': 'Inventory',
  'nav.logistics': 'Logistics',
  'nav.finance': 'Finance',
  'nav.marketing': 'Marketing',
  'nav.analytics': 'Analytics',
  'nav.settings': 'Settings',
  'login.title': 'Welcome Back',
  'login.subtitle': 'Sign in to your account',
  'login.username': 'Username or Email',
  'login.password': 'Password',
  'login.remember': 'Remember me',
  'login.forgot': 'Forgot password?',
  'login.submit': 'Sign In',
  'login.noAccount': "Don't have an account?",
  'login.signup': 'Sign up',
  'login.verificationCode': 'Verification Code',
  'login.loginSuccess': 'Login successful! Redirecting...',
  'login.loginFailed': 'Login failed. Please check your credentials.',
  'login.invalidCaptcha': 'Invalid verification code',
  'login.orContinueWith': 'Or continue with',
  'login.welcomeBack': 'Welcome Back',
  'dashboard.title': 'Dashboard',
  'dashboard.totalSales': 'Total Sales',
  'dashboard.orders': 'Orders',
  'dashboard.conversion': 'Conversion Rate',
  'dashboard.avgOrderValue': 'Avg Order Value',
  'dashboard.salesTrend': 'Sales and Orders Trend',
  'dashboard.topProducts': 'Top Performing Products',
  'dashboard.recentOrders': 'Recent Orders',
  'dashboard.refresh': 'Refresh',
  'dashboard.export': 'Export',
  'dashboard.customize': 'Customize',
  'dashboard.allShops': 'All Shops',
  'common.search': 'Search',
  'common.reset': 'Reset',
  'common.confirm': 'Confirm',
  'common.cancel': 'Cancel',
  'common.save': 'Save',
  'common.delete': 'Delete',
  'common.edit': 'Edit',
  'common.add': 'Add',
  'common.view': 'View',
  'common.submit': 'Submit',
  'common.loading': 'Loading...',
  'common.noData': 'No Data',
  'common.success': 'Success',
  'common.error': 'Error',
  'common.warning': 'Warning',
  'common.info': 'Info',
  'common.yes': 'Yes',
  'common.no': 'No',
  'common.all': 'All',
  'common.select': 'Please select',
  'common.required': 'Required',
  'common.optional': 'Optional',
  'common.up': 'Up',
  'common.down': 'Down',
  'product.list': 'Product List',
  'product.add': 'Add Product',
  'product.edit': 'Edit Product',
  'product.delete': 'Delete Product',
  'product.name': 'Product Name',
  'product.price': 'Price',
  'product.stock': 'Stock',
  'product.status': 'Status',
  'product.category': 'Category',
  'order.list': 'Order List',
  'order.detail': 'Order Detail',
  'order.status': 'Order Status',
  'order.amount': 'Order Amount',
  'order.date': 'Order Date',
  'order.customer': 'Customer Info',
  'settings.title': 'Settings',
  'settings.profile': 'Profile',
  'settings.system': 'System',
  'settings.users': 'User Management',
  'settings.language': 'Language',
  'settings.theme': 'Theme',
  // Menu translations
  'menu.dashboard': 'Dashboard',
  'menu.aiOperations': 'AI Operations',
  'menu.operationAgent': 'Operation Agent',
  'menu.autoPilot': 'Auto Pilot',
  'menu.taskCenter': 'Task Center',
  'menu.taskManager': 'Task Manager',
  'menu.aiSuggestion': 'AI Suggestions',
  'menu.humanApproval': 'Human Approval',
  'menu.clientManagement': 'Client Management',
  'menu.executionResults': 'Execution Results',
  'menu.aiDecisionLog': 'AI Decision Log',
  'menu.strategyMarketplace': 'Strategy Marketplace',
  'menu.autoProductSelection': 'Auto Product Selection',
  'menu.autoExecution': 'Auto Execution',
  'menu.productCycle': 'Product Cycle',
  'menu.productManagement': 'Product Management',
  'menu.productPublish': 'Product Publish',
  'menu.inventoryManagement': 'Inventory Management',
  'menu.warehouseManagement': 'Warehouse Management',
  'menu.aiPricing': 'AI Pricing',
  'menu.profitMonitor': 'Profit Monitor',
  'menu.orderCycle': 'Order Cycle',
  'menu.orderManagement': 'Order Management',
  'menu.exceptionOrders': 'Exception Orders',
  'menu.afterSales': 'After Sales',
  'menu.refundProcessing': 'Refund Processing',
  'menu.logisticsCycle': 'Logistics Cycle',
  'menu.logisticsQuery': 'Logistics Query',
  'menu.freightCalculation': 'Freight Calculation',
  'menu.financeCycle': 'Finance Cycle',
  'menu.financeOverview': 'Finance Overview',
  'menu.transactionRecords': 'Transaction Records',
  'menu.financeReconciliation': 'Finance Reconciliation',
  'menu.userAssets': 'User Assets',
  'menu.marketingCycle': 'Marketing Cycle',
  'menu.adManagement': 'Ad Management',
  'menu.competitorAnalysis': 'Competitor Analysis',
  'menu.dynamicPricing': 'Dynamic Pricing',
  'menu.abTest': 'A/B Test',
  'menu.analytics': 'Analytics',
  'menu.dataAnalysis': 'Data Analysis',
  'menu.reportCenter': 'Report Center',
  'menu.multiShopReport': 'Multi-Shop Report',
  'menu.leaderboard': 'Leaderboard',
  'menu.b2bTrade': 'B2B Trade',
  'menu.merchantManagement': 'Merchant Management',
  'menu.b2bTradeManagement': 'B2B Trade',
  'menu.batchOrder': 'Batch Order',
  'menu.enterpriseQuote': 'Enterprise Quote',
  'menu.contractManagement': 'Contract Management',
  'menu.procurementManagement': 'Procurement Management',
  'menu.suppliers': 'Suppliers',
  'menu.warehouseInventory': 'Warehouse Inventory',
  'menu.independentSite': 'Independent Site',
  'menu.siteManagement': 'Site Management',
  'menu.createSite': 'Create Site',
  'menu.siteTemplates': 'Site Templates',
  'menu.siteAnalytics': 'Site Analytics',
  'menu.independentSiteOrders': 'Independent Site Orders',
  'menu.independentSiteProducts': 'Independent Site Products',
  'menu.domainManagement': 'Domain Management',
  'menu.riskCompliance': 'Risk & Compliance',
  'menu.riskMonitoring': 'Risk Monitoring',
  'menu.complianceCheck': 'Compliance Check',
  'menu.auditLogs': 'Audit Logs',
  'menu.operationLogs': 'Operation Logs',
  'menu.governanceCenter': 'Governance Center',
  'menu.sovereigntyManagement': 'Sovereignty Management',
  'menu.certificateManagement': 'Certificate Management',
  'menu.settings': 'System Settings',
  'menu.settingsOverview': 'Settings Overview',
  'menu.platformAuth': 'Platform Authorization',
  'menu.serviceManager': 'Service Manager',
  'menu.userManagement': 'User Management',
  'menu.rolePermissions': 'Role Permissions',
  // Product publish form translations
  'product.publish.title': 'Product Publish',
  'product.publish.basicInfo': 'Basic Information',
  'product.publish.variants': 'Product Variants',
  'product.publish.images': 'Product Images',
  'product.publish.materialProcessing': 'AI Material Processing',
  'product.publish.materialProcessingDesc': 'After uploading images, you can use AI for image-to-image, image-to-video processing. Click the AI button on uploaded images to start processing.',
  'product.publish.selectImage': 'Please select an image to process first',
  'product.publish.taskCreated': 'Task created: {id}',
  'product.publish.processingComplete': 'Material processing completed!',
  'product.publish.videoGenerated': 'Video has been generated, you can view it in the material library',
  'product.publish.processFailed': 'Processing failed',
  'product.publish.saveLocal': 'Step 1: Save to local system first',
  'product.publish.pendingSync': 'Pending sync status',
  'product.publish.saveToDatabase': 'Simulate saving to local database',
  'product.publish.complianceCheck': 'Step 2: Compliance check (locally)',
  'product.publish.submitReview': 'Step 3: Submit for review (local status change)',
  'product.publish.resetForm': 'Reset form',
  'product.publish.processingTasks': 'Processing tasks',
  'product.publish.imageToImage': 'Image to Image',
  'product.publish.imageToVideo': 'Image to Video',
  'product.publish.originalPreview': 'Original preview:',
  'product.publish.prompt': 'Prompt',
  'product.publish.promptPlaceholder': 'Describe the image effect you want to generate...',
  'product.publish.style': 'Style',
  'product.publish.strength': 'Conversion strength',
  'product.publish.motion': 'Motion type',
  'product.publish.motionZoom': 'Zoom',
  'product.publish.motionPan': 'Pan',
  'product.publish.motionRotate': 'Rotate',
  'product.publish.motionDynamic': 'Dynamic',
  'product.publish.duration': 'Duration (seconds)',
  'product.publish.fps': 'FPS',
  'product.publish.startProcessing': 'Start processing',
  'product.publish.cancel': 'Cancel',
  // Product publish form additional translations
  'product.publish.productImages': 'Product Images',
  'product.publish.images': 'Images',
  'product.publish.upload': 'Upload',
  'product.publish.pricing': 'Pricing',
  'product.publish.profitMarginValidation': 'Profit Margin Validation',
  'product.publish.profitMarginDesc': 'B2B products must maintain at least 15% profit margin. B2C products require 20% minimum.',
  'product.publish.sellingPrice': 'Selling Price',
  'product.publish.enterPrice': 'Please enter price',
  'product.publish.costPrice': 'Cost Price',
  'product.publish.enterCostPrice': 'Please enter cost price',
  'product.publish.currency': 'Currency',
  'product.publish.draftSaved': 'Draft saved successfully',
  'product.publish.fillRequiredFields': 'Please fill in required fields',
};

const translations: Record<string, Record<string, string>> = {
  'zh-CN': zhCN,
  'en-US': enUS,
};

const LocaleContext = createContext<LocaleContextType | undefined>(undefined);

export const LocaleProvider: FC<{ children: ReactNode }> = ({ children }) => {
  const [locale, setLocale] = useState<string>('zh-CN');

  const t = useCallback((key: string, options?: Record<string, any>): string => {
    const translation = translations[locale]?.[key] || translations['en-US']?.[key] || key;
    if (options) {
      return Object.entries(options).reduce((result, [placeholder, value]) => {
        return result.replace(new RegExp(`\{${placeholder}\}`, 'g'), String(value));
      }, translation);
    }
    return translation;
  }, [locale]);

  return (
    <LocaleContext.Provider value={{ locale, setLocale, t }}>
      {children}
    </LocaleContext.Provider>
  );
};

const defaultContext: LocaleContextType = {
  locale: 'zh-CN',
  setLocale: () => {},
  t: (key: string, options?: Record<string, any>): string => {
    const translation = zhCN[key] || enUS[key] || key;
    if (options) {
      return Object.entries(options).reduce((result, [placeholder, value]) => {
        return result.replace(new RegExp(`\{${placeholder}\}`, 'g'), String(value));
      }, translation);
    }
    return translation;
  },
};

export const useLocale = (): LocaleContextType => {
  const context = useContext(LocaleContext);
  if (!context) {
    console.warn('useLocale is used outside LocaleProvider, using default context');
    return defaultContext;
  }
  return context;
};

export default LocaleContext;
