/**
 * GenUI Schema 在线调试工具
 * 用于测试和验证 UI Schema 的渲染效果
 */

import { useState, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import { DynamicRenderer } from '@/ai/genui/DynamicRenderer';
import { getSupportedComponentTypes } from '@/ai/genui/registry';
import type { UISchema, RenderContext } from '@/ai/genui/types';
import { 
  Play, 
  AlertCircle, 
  CheckCircle, 
  Copy, 
  RotateCcw,
  FileJson,
  Eye,
  Code,
  Lightbulb
} from 'lucide-react';
import { toast } from 'sonner';

// 示例 Schema 模板
const EXAMPLE_SCHEMAS: Record<string, { name: string; schema: UISchema }> = {
  stats: {
    name: '统计指标',
    schema: {
      layout: 'vertical',
      gap: 'md',
      components: [
        {
          id: 'stats-1',
          type: 'stats_row',
          props: {
            items: [
              { label: '本月营收', value: '¥156,800', color: 'success', trend: '+12.5%', trendDirection: 'up' },
              { label: '订单数', value: '1,234', color: 'info' },
              { label: '待处理', value: '23', color: 'warning' },
              { label: '退款率', value: '2.1%', color: 'error', trend: '-0.3%', trendDirection: 'down' }
            ],
            columns: 4
          }
        }
      ]
    }
  },
  table: {
    name: '数据表格',
    schema: {
      layout: 'vertical',
      gap: 'md',
      components: [
        {
          id: 'table-1',
          type: 'data_table',
          props: {
            title: '低库存商品预警',
            columns: [
              { key: 'name', label: '商品名称', type: 'text' },
              { key: 'stock', label: '当前库存', type: 'number' },
              { key: 'status', label: '状态', type: 'status' }
            ],
            data: [
              { id: '1', name: 'iPhone 15 Pro', stock: 3, status: '紧急' },
              { id: '2', name: 'AirPods Pro 2', stock: 8, status: '警告' },
              { id: '3', name: 'MacBook Air M3', stock: 5, status: '警告' }
            ],
            pagination: true,
            pageSize: 10
          }
        }
      ]
    }
  },
  chart: {
    name: '图表展示',
    schema: {
      layout: 'vertical',
      gap: 'md',
      components: [
        {
          id: 'chart-1',
          type: 'chart',
          props: {
            title: '近7日销售趋势',
            type: 'area',
            data: [
              { label: '周一', value: 4200 },
              { label: '周二', value: 5100 },
              { label: '周三', value: 4800 },
              { label: '周四', value: 6200 },
              { label: '周五', value: 7500 },
              { label: '周六', value: 8900 },
              { label: '周日', value: 6100 }
            ],
            xKey: 'label',
            yKey: 'value',
            height: 250
          }
        }
      ]
    }
  },
  dashboard: {
    name: '综合仪表盘',
    schema: {
      layout: 'vertical',
      gap: 'lg',
      components: [
        {
          id: 'stats',
          type: 'stats_row',
          props: {
            items: [
              { label: '总营收', value: '¥1,258,000', color: 'success' },
              { label: '订单量', value: '3,456', color: 'info' },
              { label: '转化率', value: '4.2%', color: 'default' }
            ]
          }
        },
        {
          id: 'container-1',
          type: 'container',
          props: {
            layout: 'horizontal',
            gap: 'md',
            children: [
              {
                id: 'chart-sales',
                type: 'chart',
                props: {
                  title: '销售趋势',
                  type: 'line',
                  data: [
                    { label: '1月', value: 120000 },
                    { label: '2月', value: 150000 },
                    { label: '3月', value: 180000 }
                  ],
                  height: 200
                }
              },
              {
                id: 'chart-category',
                type: 'chart',
                props: {
                  title: '品类分布',
                  type: 'pie',
                  data: [
                    { label: '手机', value: 45 },
                    { label: '配件', value: 30 },
                    { label: '电脑', value: 25 }
                  ],
                  height: 200
                }
              }
            ]
          }
        },
        {
          id: 'alert-1',
          type: 'alert',
          props: {
            type: 'warning',
            title: '库存预警',
            description: '有 5 件商品库存低于安全线，请及时补货'
          }
        }
      ]
    }
  },
  insights: {
    name: '洞察流',
    schema: {
      layout: 'vertical',
      gap: 'md',
      components: [
        {
          id: 'insight-feed-1',
          type: 'insight_feed',
          props: {
            title: 'AI 智能洞察',
            insights: [
              {
                id: 'i1',
                type: 'opportunity',
                title: '销售增长机会',
                description: '根据历史数据，本周末预计销量将增长 30%，建议提前备货',
                priority: 'high',
                agent: '小营',
                actionLabel: '查看详情'
              },
              {
                id: 'i2',
                type: 'warning',
                title: '库存预警',
                description: 'iPhone 15 Pro 库存仅剩 3 件，低于安全库存线',
                priority: 'urgent',
                agent: '小品',
                actionLabel: '立即补货'
              },
              {
                id: 'i3',
                type: 'auto_executed',
                title: '自动优化完成',
                description: '已自动调整 12 个商品的展示排序，预计提升点击率 15%',
                priority: 'medium',
                agent: '小品'
              }
            ],
            layout: 'list',
            groupBy: 'none'
          }
        }
      ]
    }
  }
};

export default function GenUIDebugPage() {
  const [schemaText, setSchemaText] = useState(
    JSON.stringify(EXAMPLE_SCHEMAS.dashboard.schema, null, 2)
  );
  const [parsedSchema, setParsedSchema] = useState<UISchema | null>(
    EXAMPLE_SCHEMAS.dashboard.schema
  );
  const [parseError, setParseError] = useState<string | null>(null);
  const [activeTab, setActiveTab] = useState('preview');

  // 解析 Schema
  const parseSchema = useCallback(() => {
    try {
      const parsed = JSON.parse(schemaText);
      setParsedSchema(parsed);
      setParseError(null);
      toast.success('Schema 解析成功');
    } catch (err) {
      setParseError(err instanceof Error ? err.message : '解析失败');
      setParsedSchema(null);
      toast.error('Schema 解析失败');
    }
  }, [schemaText]);

  // 加载示例
  const loadExample = useCallback((key: string) => {
    const example = EXAMPLE_SCHEMAS[key];
    if (example) {
      const text = JSON.stringify(example.schema, null, 2);
      setSchemaText(text);
      setParsedSchema(example.schema);
      setParseError(null);
      toast.success(`已加载示例: ${example.name}`);
    }
  }, []);

  // 复制 Schema
  const copySchema = useCallback(() => {
    navigator.clipboard.writeText(schemaText);
    toast.success('已复制到剪贴板');
  }, [schemaText]);

  // 重置
  const resetSchema = useCallback(() => {
    setSchemaText('{\n  "layout": "vertical",\n  "gap": "md",\n  "components": []\n}');
    setParsedSchema({ layout: 'vertical', gap: 'md', components: [] });
    setParseError(null);
  }, []);

  // 渲染上下文
  const renderContext: RenderContext = {
    onAction: (action, params) => {
      toast.info(`Action 触发: ${action}`, {
        description: params ? JSON.stringify(params) : undefined
      });
    },
    theme: 'light',
    agentType: 'manager'
  };

  const supportedTypes = getSupportedComponentTypes();

  return (
    <div className="min-h-screen bg-background p-4 md:p-6">
      <div className="mx-auto max-w-7xl space-y-4">
        {/* 头部 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-foreground">GenUI Schema 调试工具</h1>
            <p className="text-sm text-muted-foreground">
              在线编辑和预览 UI Schema 渲染效果
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="outline" size="sm" onClick={copySchema}>
              <Copy className="mr-1 h-4 w-4" />
              复制
            </Button>
            <Button variant="outline" size="sm" onClick={resetSchema}>
              <RotateCcw className="mr-1 h-4 w-4" />
              重置
            </Button>
            <Button size="sm" onClick={parseSchema}>
              <Play className="mr-1 h-4 w-4" />
              运行
            </Button>
          </div>
        </div>

        {/* 示例模板 */}
        <Card>
          <CardHeader className="py-3">
            <CardTitle className="flex items-center gap-2 text-sm">
              <Lightbulb className="h-4 w-4" />
              快速加载示例
            </CardTitle>
          </CardHeader>
          <CardContent className="py-2">
            <div className="flex flex-wrap gap-2">
              {Object.entries(EXAMPLE_SCHEMAS).map(([key, { name }]) => (
                <Button
                  key={key}
                  variant="secondary"
                  size="sm"
                  onClick={() => loadExample(key)}
                >
                  {name}
                </Button>
              ))}
            </div>
          </CardContent>
        </Card>

        {/* 主内容区 */}
        <div className="grid gap-4 lg:grid-cols-2">
          {/* 左侧：编辑器 */}
          <Card className="flex flex-col">
            <CardHeader className="py-3">
              <CardTitle className="flex items-center gap-2 text-sm">
                <Code className="h-4 w-4" />
                Schema 编辑器
              </CardTitle>
            </CardHeader>
            <CardContent className="flex-1 p-3">
              <Textarea
                value={schemaText}
                onChange={(e) => setSchemaText(e.target.value)}
                className="h-[500px] font-mono text-sm"
                placeholder="输入 UI Schema JSON..."
              />
              {parseError && (
                <Alert variant="destructive" className="mt-3">
                  <AlertCircle className="h-4 w-4" />
                  <AlertTitle>解析错误</AlertTitle>
                  <AlertDescription className="font-mono text-xs">
                    {parseError}
                  </AlertDescription>
                </Alert>
              )}
            </CardContent>
          </Card>

          {/* 右侧：预览区 */}
          <Card className="flex flex-col">
            <CardHeader className="py-3">
              <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
                <TabsList>
                  <TabsTrigger value="preview" className="gap-1">
                    <Eye className="h-3 w-3" />
                    预览
                  </TabsTrigger>
                  <TabsTrigger value="parsed" className="gap-1">
                    <FileJson className="h-3 w-3" />
                    解析结果
                  </TabsTrigger>
                  <TabsTrigger value="components" className="gap-1">
                    <Code className="h-3 w-3" />
                    组件列表
                  </TabsTrigger>
                </TabsList>
              </Tabs>
            </CardHeader>
            <CardContent className="flex-1 p-3">
              <TabsContent value="preview" className="m-0 h-full">
                <ScrollArea className="h-[500px] rounded-md border p-4">
                  {parsedSchema ? (
                    <DynamicRenderer schema={parsedSchema} context={renderContext} />
                  ) : (
                    <div className="flex h-full items-center justify-center text-muted-foreground">
                      <p>请输入有效的 Schema 并点击运行</p>
                    </div>
                  )}
                </ScrollArea>
              </TabsContent>

              <TabsContent value="parsed" className="m-0 h-full">
                <ScrollArea className="h-[500px] rounded-md border bg-muted/30 p-4">
                  {parsedSchema ? (
                    <pre className="font-mono text-xs">
                      {JSON.stringify(parsedSchema, null, 2)}
                    </pre>
                  ) : (
                    <p className="text-muted-foreground">无解析结果</p>
                  )}
                </ScrollArea>
              </TabsContent>

              <TabsContent value="components" className="m-0 h-full">
                <ScrollArea className="h-[500px] rounded-md border p-4">
                  <div className="space-y-4">
                    <div>
                      <h3 className="mb-2 text-sm font-medium">支持的组件类型</h3>
                      <div className="flex flex-wrap gap-2">
                        {supportedTypes.map((type) => (
                          <Badge key={type} variant="secondary">
                            {type}
                          </Badge>
                        ))}
                      </div>
                    </div>
                    <div>
                      <h3 className="mb-2 text-sm font-medium">当前 Schema 组件</h3>
                      {parsedSchema?.components?.length ? (
                        <div className="space-y-2">
                          {parsedSchema.components.map((comp, idx) => (
                            <div
                              key={comp.id || idx}
                              className="flex items-center gap-2 rounded-md border p-2"
                            >
                              <CheckCircle className="h-4 w-4 text-emerald-500 dark:text-emerald-400" />
                              <Badge>{comp.type}</Badge>
                              <span className="text-xs text-muted-foreground">
                                {comp.id || `component-${idx}`}
                              </span>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <p className="text-sm text-muted-foreground">暂无组件</p>
                      )}
                    </div>
                  </div>
                </ScrollArea>
              </TabsContent>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
