import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { 
  Play, 
  CheckCircle2, 
  XCircle, 
  Clock, 
  AlertTriangle,
  Terminal,
  FileText,
  BarChart3,
  Download,
  Copy,
  ChevronDown,
  ChevronUp,
  Loader2
} from 'lucide-react';
import type { SandboxExecutionResult, SandboxFile, SandboxChart } from '@/types/sandbox';
import { downloadSandboxFile } from '@/utils/sandboxClient';
import { toast } from 'sonner';

interface SandboxResultCardProps {
  result: SandboxExecutionResult;
  onRerun?: () => void;
  onCancel?: () => void;
}

const statusConfig: Record<string, { icon: typeof Loader2; color: string; label: string; iconClass?: string }> = {
  running: { icon: Loader2, color: 'bg-blue-500', label: '执行中', iconClass: 'animate-spin' },
  success: { icon: CheckCircle2, color: 'bg-green-500', label: '成功' },
  error: { icon: XCircle, color: 'bg-red-500', label: '失败' },
  timeout: { icon: Clock, color: 'bg-yellow-500', label: '超时' },
  cancelled: { icon: AlertTriangle, color: 'bg-muted-foreground', label: '已取消' }
};

const agentLabels: Record<string, string> = {
  manager: '总管家',
  marketing: '营销专家',
  product: '产品专家',
  service: '客服专家',
  finance: '财务专家'
};

export const SandboxResultCard: React.FC<SandboxResultCardProps> = ({
  result,
  onRerun,
  onCancel
}) => {
  const [showCode, setShowCode] = useState(false);
  const [downloading, setDownloading] = useState<string | null>(null);

  const status = statusConfig[result.status];
  const StatusIcon = status.icon;

  const handleCopyOutput = () => {
    const output = result.stdout || result.stderr || '';
    navigator.clipboard.writeText(output);
    toast.success('已复制到剪贴板');
  };

  const handleDownloadFile = async (file: SandboxFile) => {
    try {
      setDownloading(file.id);
      const blob = await downloadSandboxFile(result.executionId, file.id);
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = file.name;
      a.click();
      URL.revokeObjectURL(url);
      toast.success(`已下载: ${file.name}`);
    } catch (error) {
      toast.error('下载失败');
    } finally {
      setDownloading(null);
    }
  };

  const formatDuration = (ms?: number) => {
    if (!ms) return '-';
    if (ms < 1000) return `${ms}ms`;
    return `${(ms / 1000).toFixed(2)}s`;
  };

  const formatSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes}B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
    return `${(bytes / 1024 / 1024).toFixed(1)}MB`;
  };

  return (
    <Card className="border-border/50 bg-card/50 backdrop-blur-sm">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className={`p-2 rounded-lg ${status.color}/10`}>
              <StatusIcon className={`h-5 w-5 ${status.color.replace('bg-', 'text-')} ${status.iconClass || ''}`} />
            </div>
            <div>
              <CardTitle className="text-base">
                {result.taskDescription}
              </CardTitle>
              <div className="flex items-center gap-2 mt-1">
                <Badge variant="outline" className="text-xs">
                  {agentLabels[result.agentType] || result.agentType}
                </Badge>
                {result.codeType && (
                  <Badge variant="secondary" className="text-xs">
                    {result.codeType.toUpperCase()}
                  </Badge>
                )}
                <span className="text-xs text-muted-foreground">
                  {formatDuration(result.stats?.durationMs)}
                </span>
              </div>
            </div>
          </div>
          <div className="flex items-center gap-2">
            {result.status === 'running' && onCancel && (
              <Button size="sm" variant="outline" onClick={onCancel}>
                取消
              </Button>
            )}
            {(result.status === 'success' || result.status === 'error') && onRerun && (
              <Button size="sm" variant="outline" onClick={onRerun}>
                <Play className="h-3 w-3 mr-1" />
                重新执行
              </Button>
            )}
          </div>
        </div>
      </CardHeader>

      <CardContent className="space-y-4">
        {/* 错误信息 */}
        {result.error && (
          <div className="p-3 rounded-lg bg-destructive/10 border border-destructive/20">
            <div className="flex items-center gap-2 text-destructive font-medium mb-1">
              <XCircle className="h-4 w-4" />
              {result.error.type}
            </div>
            <p className="text-sm text-destructive/80">{result.error.message}</p>
            {result.error.traceback && (
              <pre className="mt-2 text-xs text-destructive/60 overflow-x-auto">
                {result.error.traceback}
              </pre>
            )}
          </div>
        )}

        {/* 输出和文件标签页 */}
        <Tabs defaultValue="output" className="w-full">
          <TabsList className="grid w-full grid-cols-3">
            <TabsTrigger value="output" className="text-xs">
              <Terminal className="h-3 w-3 mr-1" />
              输出
            </TabsTrigger>
            <TabsTrigger value="files" className="text-xs">
              <FileText className="h-3 w-3 mr-1" />
              文件 ({result.files?.length || 0})
            </TabsTrigger>
            <TabsTrigger value="charts" className="text-xs">
              <BarChart3 className="h-3 w-3 mr-1" />
              图表 ({result.charts?.length || 0})
            </TabsTrigger>
          </TabsList>

          <TabsContent value="output" className="mt-3">
            {(result.stdout || result.stderr) ? (
              <div className="relative">
                <ScrollArea className="h-48 rounded-lg bg-muted/50 p-3">
                  <pre className="text-xs font-mono whitespace-pre-wrap">
                    {result.stdout}
                    {result.stderr && (
                      <span className="text-destructive">{result.stderr}</span>
                    )}
                  </pre>
                </ScrollArea>
                <Button
                  size="icon"
                  variant="ghost"
                  className="absolute top-2 right-2 h-6 w-6"
                  onClick={handleCopyOutput}
                >
                  <Copy className="h-3 w-3" />
                </Button>
              </div>
            ) : (
              <div className="h-24 flex items-center justify-center text-muted-foreground text-sm">
                暂无输出
              </div>
            )}
          </TabsContent>

          <TabsContent value="files" className="mt-3">
            {result.files && result.files.length > 0 ? (
              <div className="space-y-2">
                {result.files.map((file) => (
                  <div
                    key={file.id}
                    className="flex items-center justify-between p-2 rounded-lg bg-muted/50"
                  >
                    <div className="flex items-center gap-2">
                      <FileText className="h-4 w-4 text-muted-foreground" />
                      <div>
                        <p className="text-sm font-medium">{file.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {file.type.toUpperCase()} · {formatSize(file.size)}
                        </p>
                      </div>
                    </div>
                    <Button
                      size="sm"
                      variant="ghost"
                      onClick={() => handleDownloadFile(file)}
                      disabled={downloading === file.id}
                    >
                      {downloading === file.id ? (
                        <Loader2 className="h-4 w-4 animate-spin" />
                      ) : (
                        <Download className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                ))}
              </div>
            ) : (
              <div className="h-24 flex items-center justify-center text-muted-foreground text-sm">
                暂无生成文件
              </div>
            )}
          </TabsContent>

          <TabsContent value="charts" className="mt-3">
            {result.charts && result.charts.length > 0 ? (
              <div className="space-y-3">
                {result.charts.map((chart) => (
                  <div key={chart.id} className="rounded-lg bg-muted/50 p-3">
                    <p className="text-sm font-medium mb-2">{chart.title}</p>
                    {chart.imageUrl && (
                      <img 
                        src={chart.imageUrl} 
                        alt={chart.title}
                        className="w-full rounded-lg"
                      />
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <div className="h-24 flex items-center justify-center text-muted-foreground text-sm">
                暂无图表
              </div>
            )}
          </TabsContent>
        </Tabs>

        {/* 代码展示 */}
        {result.code && (
          <div>
            <Button
              variant="ghost"
              size="sm"
              className="w-full justify-between"
              onClick={() => setShowCode(!showCode)}
            >
              <span className="text-xs text-muted-foreground">
                查看执行代码
              </span>
              {showCode ? (
                <ChevronUp className="h-4 w-4" />
              ) : (
                <ChevronDown className="h-4 w-4" />
              )}
            </Button>
            {showCode && (
              <ScrollArea className="h-32 mt-2 rounded-lg bg-muted/50 p-3">
                <pre className="text-xs font-mono">{result.code}</pre>
              </ScrollArea>
            )}
          </div>
        )}

        {/* 执行统计 */}
        {result.stats && (
          <div className="flex items-center gap-4 text-xs text-muted-foreground pt-2 border-t">
            {result.stats.startTime && (
              <span>
                开始: {new Date(result.stats.startTime).toLocaleTimeString()}
              </span>
            )}
            {result.stats.memoryUsedMb && (
              <span>内存: {result.stats.memoryUsedMb.toFixed(1)}MB</span>
            )}
            {result.stats.cpuTimeMs && (
              <span>CPU: {result.stats.cpuTimeMs}ms</span>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default SandboxResultCard;
