/**
 * filekorolheader: 删除模型确认对话框 - 模型服务删除确认界面
 * 功能：删除确认、模型信息展示、风险提示、删除处理
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用AlertDialog组件，安全删除确认
 */

'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle
} from '@/components/ui/alert-dialog';
import { Badge } from '@/components/ui/badge';
import { Card } from '@/components/ui/card';
import { ModelService } from '../types';
import { AlertTriangle, Trash2, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';

interface DeleteModelDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  model: ModelService | null;
  dispatch: React.Dispatch<any>;
}

const getModelTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    'image_classification': '图像分类',
    'object_detection': '目标检测',
    'regression': '回归预测',
    'multiclass_classification': '多类分类',
    'optimization': '优化算法',
    'time_series': '时序分析',
    'nlp': '自然语言处理',
    'anomaly_detection': '异常检测'
  };
  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>
  );
};

export function DeleteModelDialog({ open, onOpenChange, model, dispatch }: DeleteModelDialogProps) {
  const [isDeleting, setIsDeleting] = useState(false);

  const handleDelete = async () => {
    if (!model) return;

    setIsDeleting(true);

    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1500));

      // 删除模型
      dispatch({ type: 'DELETE_MODEL', payload: model.id });
      dispatch({ type: 'SET_DELETE_DIALOG', payload: false });

      toast.success(`模型 "${model.name}" 已成功删除`);
    } catch (error) {
      toast.error('删除模型失败，请重试');
      console.error('Delete model error:', error);
    } finally {
      setIsDeleting(false);
    }
  };

  if (!model) return null;

  return (
    <AlertDialog open={open} onOpenChange={onOpenChange}>
      <AlertDialogContent className="max-w-lg">
        <AlertDialogHeader>
          <div className="flex items-center space-x-3">
            <div className="flex-shrink-0">
              <div className="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-red-100 dark:bg-red-900">
                <Trash2 className="h-6 w-6 text-red-600 dark:text-red-400" />
              </div>
            </div>
            <div className="flex-1">
              <AlertDialogTitle className="text-red-600 dark:text-red-400">
                删除模型确认
              </AlertDialogTitle>
              <AlertDialogDescription className="text-left mt-2">
                您确定要删除这个AI模型服务吗？此操作不可撤销。
              </AlertDialogDescription>
            </div>
          </div>
        </AlertDialogHeader>

        <div className="my-6">
          {/* 模型信息卡片 */}
          <Card className="p-4 bg-muted/30 border-red-200 dark:border-red-800">
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <h4 className="font-medium text-foreground">模型信息</h4>
                {getStatusBadge(model.status)}
              </div>

              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-muted-foreground">模型名称:</span>
                  <span className="font-medium text-foreground">{model.name}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">模型类型:</span>
                  <span className="font-medium text-foreground">{getModelTypeLabel(model.type)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">版本:</span>
                  <span className="font-mono text-foreground">{model.version}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-muted-foreground">API端点:</span>
                  <div className="flex items-center space-x-1">
                    <span className="font-mono text-xs text-foreground max-w-xs truncate">
                      {model.apiEndpoint}
                    </span>
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-5 w-5 p-0"
                      onClick={() => window.open(model.apiEndpoint, '_blank')}
                      title="访问API"
                    >
                      <ExternalLink className="h-3 w-3" />
                    </Button>
                  </div>
                </div>
              </div>

              <div className="pt-3 border-t border-border">
                <div className="grid grid-cols-3 gap-3 text-center">
                  <div>
                    <div className="text-lg font-bold text-blue-600 dark:text-blue-400">
                      {model.metrics.total_calls.toLocaleString()}
                    </div>
                    <div className="text-xs text-muted-foreground">总调用次数</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold text-green-600 dark:text-green-400">
                      {model.metrics.accuracy.toFixed(1)}%
                    </div>
                    <div className="text-xs text-muted-foreground">准确率</div>
                  </div>
                  <div>
                    <div className="text-lg font-bold text-orange-600 dark:text-orange-400">
                      {model.metrics.qps.toFixed(1)}
                    </div>
                    <div className="text-xs text-muted-foreground">QPS</div>
                  </div>
                </div>
              </div>
            </div>
          </Card>

          {/* 删除影响提示 */}
          <div className="mt-4 p-3 bg-red-50 dark:bg-red-950 border border-red-200 dark:border-red-800 rounded-lg">
            <div className="flex items-start space-x-2">
              <AlertTriangle className="h-4 w-4 text-red-600 dark:text-red-400 mt-0.5 flex-shrink-0" />
              <div className="text-sm text-red-800 dark:text-red-200">
                <p className="font-medium mb-1">删除后将会：</p>
                <ul className="space-y-1 text-xs">
                  <li>• 永久删除模型配置和参数设置</li>
                  <li>• 停止所有相关的API调用服务</li>
                  <li>• 清除该模型的运行统计数据</li>
                  <li>• 影响依赖此模型的业务功能</li>
                </ul>
              </div>
            </div>
          </div>

          {/* 创建时间信息 */}
          <div className="mt-3 text-xs text-muted-foreground">
            <p>
              创建时间: {new Date(model.createdAt).toLocaleString('zh-CN')}
              {model.updatedAt !== model.createdAt && (
                <span className="ml-2">
                  | 最后更新: {new Date(model.updatedAt).toLocaleString('zh-CN')}
                </span>
              )}
            </p>
          </div>
        </div>

        <AlertDialogFooter>
          <AlertDialogCancel disabled={isDeleting}>
            取消
          </AlertDialogCancel>
          <AlertDialogAction
            onClick={handleDelete}
            disabled={isDeleting}
            className="bg-red-600 hover:bg-red-700 text-white"
          >
            {isDeleting ? (
              <>
                <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2" />
                删除中...
              </>
            ) : (
              <>
                <Trash2 className="h-4 w-4 mr-2" />
                确认删除
              </>
            )}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  );
}