import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Switch } from '@/components/ui/switch';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useToast } from '@/components/ui/use-toast';
import { createEnvironment, updateEnvironment } from '../service';
import type { Environment, CreateEnvironmentRequest, BuildTypeEnum, DeployTypeEnum } from '../types';

interface EditDialogProps {
  open: boolean;
  record?: Environment;
  onOpenChange: (open: boolean) => void;
  onSuccess: () => void;
}

/**
 * 环境编辑对话框
 */
const EditDialog: React.FC<EditDialogProps> = ({
  open,
  record,
  onOpenChange,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [formData, setFormData] = useState<Partial<CreateEnvironmentRequest>>({
    enabled: true,
    sort: 1,
  });

  useEffect(() => {
    if (open) {
      if (record) {
        setFormData({
          tenantCode: record.tenantCode,
          envCode: record.envCode,
          envName: record.envName,
          envDesc: record.envDesc,
          buildType: record.buildType,
          deployType: record.deployType,
          sort: record.sort,
          enabled: record.enabled,
        });
      } else {
        setFormData({ enabled: true, sort: 1 });
      }
    }
  }, [open, record]);

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.tenantCode?.trim()) {
        toast({ title: '提示', description: '请输入租户代码', variant: 'destructive' });
        return;
      }
      if (!formData.envCode?.trim()) {
        toast({ title: '提示', description: '请输入环境编码', variant: 'destructive' });
        return;
      }
      if (!formData.envName?.trim()) {
        toast({ title: '提示', description: '请输入环境名称', variant: 'destructive' });
        return;
      }
      if (!formData.buildType) {
        toast({ title: '提示', description: '请选择构建类型', variant: 'destructive' });
        return;
      }
      if (!formData.deployType) {
        toast({ title: '提示', description: '请选择部署类型', variant: 'destructive' });
        return;
      }

      if (record) {
        await updateEnvironment({ ...formData, id: record.id } as any);
        toast({ title: '更新成功', description: `环境 "${formData.envName}" 已更新` });
      } else {
        await createEnvironment(formData as CreateEnvironmentRequest);
        toast({ title: '创建成功', description: `环境 "${formData.envName}" 已创建` });
      }

      onSuccess();
      onOpenChange(false);
    } catch (error) {
      console.error('保存失败:', error);
      toast({
        title: '保存失败',
        description: error instanceof Error ? error.message : '未知错误',
        variant: 'destructive'
      });
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{record ? '编辑环境' : '新建环境'}</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="tenantCode">租户代码 *</Label>
            <Input
              id="tenantCode"
              value={formData.tenantCode || ''}
              onChange={(e) => setFormData({ ...formData, tenantCode: e.target.value })}
              placeholder="请输入租户代码"
              disabled={!!record}
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="envCode">环境编码 *</Label>
            <Input
              id="envCode"
              value={formData.envCode || ''}
              onChange={(e) => setFormData({ ...formData, envCode: e.target.value })}
              placeholder="请输入环境编码"
              disabled={!!record}
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="envName">环境名称 *</Label>
            <Input
              id="envName"
              value={formData.envName || ''}
              onChange={(e) => setFormData({ ...formData, envName: e.target.value })}
              placeholder="请输入环境名称"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="envDesc">环境描述</Label>
            <Textarea
              id="envDesc"
              value={formData.envDesc || ''}
              onChange={(e) => setFormData({ ...formData, envDesc: e.target.value })}
              placeholder="请输入环境描述"
              rows={3}
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="buildType">构建类型 *</Label>
            <Select
              value={formData.buildType}
              onValueChange={(value) => setFormData({ ...formData, buildType: value as BuildTypeEnum })}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择构建类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="JENKINS">Jenkins构建</SelectItem>
                <SelectItem value="GITLAB_RUNNER">GitLab Runner构建</SelectItem>
                <SelectItem value="GITHUB_ACTION">GitHub Action构建</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="deployType">部署类型 *</Label>
            <Select
              value={formData.deployType}
              onValueChange={(value) => setFormData({ ...formData, deployType: value as DeployTypeEnum })}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择部署类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="K8S">Kubernetes集群部署</SelectItem>
                <SelectItem value="DOCKER">Docker容器部署</SelectItem>
                <SelectItem value="VM">虚拟机部署</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="sort">显示排序 *</Label>
            <Input
              id="sort"
              type="number"
              value={formData.sort || 1}
              onChange={(e) => setFormData({ ...formData, sort: Number(e.target.value) })}
              placeholder="请输入显示排序"
            />
          </div>

          <div className="flex items-center justify-between">
            <Label htmlFor="enabled">启用状态</Label>
            <Switch
              id="enabled"
              checked={formData.enabled}
              onCheckedChange={(checked) => setFormData({ ...formData, enabled: checked })}
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;

