/**
 * filekorolheader: 重新部署对话框组件 - 模型服务重新部署
 * 功能：部署确认、版本选择、部署进度监控
 * 路径：/ai-crop-model/model-integration/management
 * 规范：遵循crop-x/docs/开发项目规范.md，使用shadcn语义化样式
 */

'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogFooter
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { RotateCcw, AlertTriangle, CheckCircle, Clock } from 'lucide-react';
import { toast } from 'sonner';

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

export function RedeployDialog({ open, onOpenChange, model, dispatch }: RedeployDialogProps) {
  const [deployVersion, setDeployVersion] = useState(model?.version || 'latest');
  const [isDeploying, setIsDeploying] = useState(false);
  const [deployProgress, setDeployProgress] = useState(0);
  const [deployStatus, setDeployStatus] = useState<'idle' | 'deploying' | 'success' | 'error'>('idle');

  const handleRedeploy = async () => {
    setIsDeploying(true);
    setDeployStatus('deploying');
    setDeployProgress(0);

    try {
      // 模拟部署过程
      const steps = [
        { progress: 20, message: '停止当前服务...' },
        { progress: 40, message: '备份当前版本...' },
        { progress: 60, message: '加载新版本模型...' },
        { progress: 80, message: '运行健康检查...' },
        { progress: 95, message: '重启服务...' },
        { progress: 100, message: '部署完成' }
      ];

      for (const step of steps) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        setDeployProgress(step.progress);
      }

      setDeployStatus('success');
      toast.success('模型重新部署成功！');

      // 更新模型状态
      setTimeout(() => {
        onOpenChange(false);
        setDeployStatus('idle');
        setDeployProgress(0);
      }, 2000);

    } catch (error) {
      setDeployStatus('error');
      toast.error('部署失败，请重试');
      console.error('Deploy error:', error);
    } finally {
      setIsDeploying(false);
    }
  };

  const availableVersions = [
    { version: 'v2.1.1', status: 'stable', date: '2024-03-21' },
    { version: 'v2.1.0', status: 'current', date: '2024-03-20' },
    { version: 'v2.0.9', status: 'stable', date: '2024-03-15' },
    { version: 'v2.1.2-beta', status: 'beta', date: '2024-03-22' }
  ];

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>重新部署</DialogTitle>
          <DialogDescription>
            确认要重新部署模型 <strong>{model?.name}</strong> 吗？
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {deployStatus === 'idle' && (
            <>
              <Alert>
                <AlertTriangle className="h-4 w-4" />
                <AlertDescription>
                  重新部署将会暂时停止服务，更新完成后自动重启。
                </AlertDescription>
              </Alert>

              <div className="space-y-2">
                <Label>选择部署版本</Label>
                <Select value={deployVersion} onValueChange={setDeployVersion}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    {availableVersions.map((version) => (
                      <SelectItem key={version.version} value={version.version}>
                        <div className="flex items-center justify-between w-full">
                          <span>{version.version}</span>
                          <div className="flex items-center gap-2">
                            <Badge
                              variant={
                                version.status === 'current'
                                  ? 'default'
                                  : version.status === 'stable'
                                  ? 'secondary'
                                  : 'outline'
                              }
                              className="text-xs"
                            >
                              {version.status === 'current' ? '当前' :
                               version.status === 'stable' ? '稳定' : '测试'}
                            </Badge>
                            <span className="text-xs text-muted-foreground">
                              {version.date}
                            </span>
                          </div>
                        </div>
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="text-sm text-muted-foreground">
                <div className="font-medium mb-2">部署将执行以下操作：</div>
                <ul className="space-y-1 ml-4">
                  <li>• 停止当前运行的模型服务</li>
                  <li>• 备份当前版本配置</li>
                  <li>• 部署新版本模型</li>
                  <li>• 运行健康检查和测试</li>
                  <li>• 重启服务并恢复调用</li>
                </ul>
              </div>
            </>
          )}

          {deployStatus === 'deploying' && (
            <div className="space-y-4">
              <div className="flex items-center gap-2">
                <RotateCcw className="w-4 h-4 animate-spin text-blue-600" />
                <span className="font-medium">正在部署...</span>
              </div>
              <Progress value={deployProgress} className="w-full" />
              <div className="text-sm text-muted-foreground text-center">
                {deployProgress < 20 && '准备部署环境...'}
                {deployProgress >= 20 && deployProgress < 40 && '停止当前服务...'}
                {deployProgress >= 40 && deployProgress < 60 && '备份当前版本...'}
                {deployProgress >= 60 && deployProgress < 80 && '加载新版本模型...'}
                {deployProgress >= 80 && deployProgress < 95 && '运行健康检查...'}
                {deployProgress >= 95 && '重启服务...'}
              </div>
            </div>
          )}

          {deployStatus === 'success' && (
            <div className="space-y-4">
              <div className="flex items-center gap-2 text-green-600">
                <CheckCircle className="w-5 h-5" />
                <span className="font-medium">部署成功！</span>
              </div>
              <div className="text-sm text-muted-foreground">
                模型已成功重新部署到版本 {deployVersion}，服务正在恢复中...
              </div>
            </div>
          )}

          {deployStatus === 'error' && (
            <div className="space-y-4">
              <div className="flex items-center gap-2 text-red-600">
                <AlertTriangle className="w-5 h-5" />
                <span className="font-medium">部署失败</span>
              </div>
              <div className="text-sm text-muted-foreground">
                部署过程中遇到错误，请检查日志并重试。
              </div>
            </div>
          )}
        </div>

        <DialogFooter>
          <Button
            variant="outline"
            onClick={() => onOpenChange(false)}
            disabled={isDeploying}
          >
            {deployStatus === 'success' ? '完成' : '取消'}
          </Button>
          {deployStatus === 'idle' && (
            <Button onClick={handleRedeploy} disabled={isDeploying}>
              确认部署
            </Button>
          )}
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}