/**
 * filekorolheader: 模型服务列表组件 - 模型服务展示与管理
 * 功能：模型列表展示、状态切换、多操作按钮、分页功能
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */

'use client';

import { ModelService } from '../types';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow
} from '@/components/ui/table';
import {
  Eye,
  Edit,
  Settings,
  Users,
  Zap,
  RotateCcw,
  Power,
  Trash2
} from 'lucide-react';
import { ExternalLink } from 'lucide-react';

interface ModelServiceListProps {
  models: ModelService[];
  onEdit: (model: ModelService) => void;
  onView: (model: ModelService) => void;
  onDelete: (model: ModelService) => void;
  onToggle: (modelId: string) => void;
  onPermission: (model: ModelService) => void;
  onPerformance: (model: ModelService) => void;
  onRedeploy: (model: ModelService) => void;
  loading: boolean;
}

export function ModelServiceList({
  models,
  onEdit,
  onView,
  onDelete,
  onToggle,
  onPermission,
  onPerformance,
  onRedeploy,
  loading
}: ModelServiceListProps) {
  const getModelTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      'pest_identification': '病虫害识别',
      'growth_status': '生长状态',
      'yield_prediction': '产量预测'
    };
    return labels[type] || type;
  };

  const getStatusBadge = (status: string) => {
    const statusConfig = {
      active: {
        label: '运行中',
        className: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
      },
      inactive: {
        label: '已停止',
        className: 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200'
      },
      testing: {
        label: '测试中',
        className: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
      },
      error: {
        label: '错误',
        className: 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
      }
    };

    const config = statusConfig[status as keyof typeof statusConfig];
    return (
      <Badge className={config.className}>
        {config.label}
      </Badge>
    );
  };

  const getVisibilityBadge = (visibility: string) => {
    const visibilityConfig = {
      public: {
        label: '公开',
        className: 'bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300'
      },
      private: {
        label: '私有',
        className: 'bg-red-50 text-red-700 dark:bg-red-900 dark:text-red-300'
      },
      team: {
        label: '团队',
        className: 'bg-blue-50 text-blue-700 dark:bg-blue-900 dark:text-blue-300'
      }
    };

    const config = visibilityConfig[visibility as keyof typeof visibilityConfig];
    return (
      <Badge variant="outline" className={config.className}>
        {config.label}
      </Badge>
    );
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / (1000 * 60));
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));

    if (diffMins < 60) {
      return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
      return `${diffHours}小时前`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  };

  if (loading) {
    return (
      <Card className="p-8">
        <div className="flex items-center justify-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
          <span className="ml-3 text-muted-foreground">加载模型服务...</span>
        </div>
      </Card>
    );
  }

  if (models.length === 0) {
    return (
      <Card className="p-8">
        <div className="text-center py-12">
          <div className="text-6xl mb-4">🤖</div>
          <h3 className="text-lg font-medium text-muted-foreground mb-2">
            暂无模型服务
          </h3>
          <p className="text-sm text-muted-foreground">
            点击"新增模型"按钮添加您的第一个AI模型服务
          </p>
        </div>
      </Card>
    );
  }

  return (
    <Card className="bg-card">
      <div className="p-6 border-b border-border">
        <h3 className="text-lg font-semibold text-foreground">模型服务列表</h3>
        <p className="text-sm text-muted-foreground mt-1">
          管理和监控所有AI模型服务的运行状态
        </p>
      </div>

      <div className="overflow-x-auto">
        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>模型名称</TableHead>
              <TableHead>类型/格式</TableHead>
              <TableHead>版本</TableHead>
              <TableHead>性能指标</TableHead>
              <TableHead>调用统计</TableHead>
              <TableHead>访问权限</TableHead>
              <TableHead>服务端点</TableHead>
              <TableHead>状态</TableHead>
              <TableHead className="text-right">操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {models.map((model) => (
              <TableRow key={model.id} className="hover:bg-muted/50">
                <TableCell>
                  <div className="flex items-center space-x-3">
                    <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-white font-semibold">
                      {model.name.charAt(0).toUpperCase()}
                    </div>
                    <div>
                      <div className="font-medium text-foreground">
                        {model.name}
                      </div>
                      {model.tags.length > 0 && (
                        <div className="flex gap-1 mt-1">
                          {model.tags.slice(0, 2).map((tag, index) => (
                            <Badge key={index} variant="outline" className="text-xs">
                              {tag}
                            </Badge>
                          ))}
                          {model.tags.length > 2 && (
                            <Badge variant="outline" className="text-xs">
                              +{model.tags.length - 2}
                            </Badge>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  <div className="text-sm">
                    <div className="font-medium">{getModelTypeLabel(model.type)}</div>
                    <div className="text-muted-foreground">TensorFlow</div>
                  </div>
                </TableCell>
                <TableCell>
                  <Badge variant="outline">
                    {model.version}
                  </Badge>
                </TableCell>
                <TableCell>
                  <div className="text-sm space-y-1">
                    <div className="flex items-center">
                      <span className="text-muted-foreground w-12">准确率:</span>
                      <span className={`font-medium ${
                        model.metrics.accuracy >= 95 ? 'text-green-600 dark:text-green-400' :
                        model.metrics.accuracy >= 85 ? 'text-yellow-600 dark:text-yellow-400' :
                        'text-red-600 dark:text-red-400'
                      }`}>
                        {model.metrics.accuracy.toFixed(1)}%
                      </span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-muted-foreground w-12">响应:</span>
                      <span className="text-muted-foreground">{model.metrics.avg_response_time}ms</span>
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  <div className="text-sm space-y-1">
                    <div className="flex items-center">
                      <span className="text-muted-foreground w-12">QPS:</span>
                      <span className="font-medium">{model.metrics.qps.toFixed(1)}</span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-muted-foreground w-12">调用:</span>
                      <span className="text-muted-foreground">{model.metrics.total_calls.toLocaleString()}</span>
                    </div>
                  </div>
                </TableCell>
                <TableCell>
                  {getVisibilityBadge(model.visibility)}
                </TableCell>
                <TableCell>
                  <div className="max-w-32">
                    <div className="text-xs font-mono truncate">
                      {model.apiEndpoint}
                    </div>
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => window.open(model.apiEndpoint, '_blank')}
                      title="访问API"
                      className="h-6 px-2 mt-1"
                    >
                      <ExternalLink className="h-3 w-3" />
                    </Button>
                  </div>
                </TableCell>
                <TableCell>
                  {getStatusBadge(model.status)}
                </TableCell>
                <TableCell className="text-right">
                  <div className="flex justify-end gap-2">
                    {/* 停止/启动 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onToggle(model.id)}
                      title={model.status === 'active' ? '停止服务' : '启动服务'}
                      className="h-8 w-8 p-0"
                    >
                      <Power className={`h-4 w-4 ${
                        model.status === 'active' ? 'text-orange-500' : 'text-green-500'
                      }`} />
                    </Button>

                    {/* 查看详情 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onView(model)}
                      title="查看详情"
                      className="h-8 w-8 p-0"
                    >
                      <Eye className="h-4 w-4 text-blue-500" />
                    </Button>

                    {/* 编辑 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onEdit(model)}
                      title="编辑模型"
                      className="h-8 w-8 p-0"
                    >
                      <Edit className="h-4 w-4 text-yellow-500" />
                    </Button>

                    {/* 权限管理 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onPermission(model)}
                      title="权限管理"
                      className="h-8 w-8 p-0"
                    >
                      <Users className="h-4 w-4 text-purple-500" />
                    </Button>

                    {/* 性能调优 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onPerformance(model)}
                      title="性能调优"
                      className="h-8 w-8 p-0"
                    >
                      <Zap className="h-4 w-4 text-cyan-500" />
                    </Button>

                    {/* 重新部署 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onRedeploy(model)}
                      title="重新部署"
                      className="h-8 w-8 p-0"
                    >
                      <RotateCcw className="h-4 w-4 text-indigo-500" />
                    </Button>

                    {/* 删除 */}
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => onDelete(model)}
                      title="删除模型"
                      className="h-8 w-8 p-0"
                    >
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </div>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </div>

      <div className="p-4 border-t border-border bg-muted/30">
        <div className="flex items-center justify-between text-sm text-muted-foreground">
          <span>
            共 {models.length} 个模型服务 |
            运行中: {models.filter(m => m.status === 'active').length} |
            测试中: {models.filter(m => m.status === 'testing').length}
          </span>
          <span>
            总调用次数: {models.reduce((sum, m) => sum + m.metrics.total_calls, 0).toLocaleString()}
          </span>
        </div>
      </div>
    </Card>
  );
}