import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogBody,
  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 { createExternalSystem, updateExternalSystem } from '../service';
import type { ExternalSystemResponse, ExternalSystemRequest, SystemType, AuthType } from '../types';

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

/**
 * 外部系统编辑对话框
 */
const EditDialog: React.FC<EditDialogProps> = ({
  open,
  record,
  onOpenChange,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [formData, setFormData] = useState<Partial<ExternalSystemRequest>>({
    enabled: true,
    sort: 1,
    authType: 'BASIC' as AuthType,
  });

  // 标记是否有原始密码和Token（用于判断是否需要提交）
  const [hasOriginalPassword, setHasOriginalPassword] = useState(false);
  const [hasOriginalToken, setHasOriginalToken] = useState(false);
  
  // 掩码常量
  const MASK = '********';

  useEffect(() => {
    if (open) {
      if (record) {
        // 判断是否有密码/Token（无论返回什么值，只要不为空就认为有）
        const hasPwd = !!record.password && record.password.trim() !== '';
        const hasTkn = !!record.token && record.token.trim() !== '';
        
        setHasOriginalPassword(hasPwd);
        setHasOriginalToken(hasTkn);
        
        setFormData({
          name: record.name,
          type: record.type,
          url: record.url,
          authType: record.authType,
          username: record.username,
          // 如果有密码，显示掩码；否则显示空
          password: hasPwd ? MASK : '',
          // 如果有Token，显示掩码；否则显示空
          token: hasTkn ? MASK : '',
          sort: record.sort,
          remark: record.remark,
          enabled: record.enabled,
        });
      } else {
        setHasOriginalPassword(false);
        setHasOriginalToken(false);
        setFormData({ enabled: true, sort: 1, authType: 'BASIC' as AuthType });
      }
    }
  }, [open, record]);

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.name?.trim()) {
        toast({ title: '提示', description: '请输入系统名称', variant: 'destructive' });
        return;
      }
      if (!formData.type) {
        toast({ title: '提示', description: '请选择系统类型', variant: 'destructive' });
        return;
      }
      if (!formData.url?.trim()) {
        toast({ title: '提示', description: '请输入系统地址', variant: 'destructive' });
        return;
      }
      // URL 验证
      try {
        new URL(formData.url);
      } catch {
        toast({ title: '提示', description: '请输入有效的URL', variant: 'destructive' });
        return;
      }

      if (formData.authType === 'BASIC') {
        if (!formData.username?.trim()) {
          toast({ title: '提示', description: '请输入用户名', variant: 'destructive' });
          return;
        }
        // 新建时必须输入密码
        if (!record && !formData.password) {
          toast({ title: '提示', description: '请输入密码', variant: 'destructive' });
          return;
        }
        // 编辑时，如果清空了原有密码（掩码），需要提示
        if (record && hasOriginalPassword && !formData.password?.trim()) {
          toast({ title: '提示', description: '密码不能为空，请输入新密码或保持原密码不变', variant: 'destructive' });
          return;
        }
      }

      if (formData.authType === 'TOKEN') {
        // 新建时必须输入Token
        if (!record && !formData.token) {
          toast({ title: '提示', description: '请输入访问令牌', variant: 'destructive' });
          return;
        }
        // 编辑时，如果清空了原有Token（掩码），需要提示
        if (record && hasOriginalToken && !formData.token?.trim()) {
          toast({ title: '提示', description: '令牌不能为空，请输入新令牌或保持原令牌不变', variant: 'destructive' });
          return;
        }
      }

      // 准备提交数据
      const submitData: ExternalSystemRequest = {
        ...formData as ExternalSystemRequest,
      };

      // 处理密码：如果值还是掩码，说明没修改，提交掩码；否则提交新值
      if (formData.authType === 'BASIC') {
        if (record && formData.password === MASK) {
          // 没有修改，保持掩码
          submitData.password = MASK;
        } else {
          // 修改了或新建，提交新密码
          submitData.password = formData.password;
        }
      }

      // 处理Token：如果值还是掩码，说明没修改，提交掩码；否则提交新值
      if (formData.authType === 'TOKEN') {
        if (record && formData.token === MASK) {
          // 没有修改，保持掩码
          submitData.token = MASK;
        } else {
          // 修改了或新建，提交新Token
          submitData.token = formData.token;
        }
      }

      if (record) {
        await updateExternalSystem(record.id, submitData);
        toast({ title: '更新成功', description: `系统 "${formData.name}" 已更新` });
      } else {
        await createExternalSystem(submitData);
        toast({ title: '创建成功', description: `系统 "${formData.name}" 已创建` });
      }

      onSuccess();
      onOpenChange(false);
    } catch (error) {
      // 错误已经在 request 拦截器中显示了，这里只需要记录日志
      console.error('保存失败:', error);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>{record ? '编辑系统' : '新增系统'}</DialogTitle>
        </DialogHeader>
        <DialogBody>
        <div className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="name">系统名称 *</Label>
            <Input
              id="name"
              value={formData.name || ''}
              onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              placeholder="请输入系统名称"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="type">系统类型 *</Label>
            <Select
              value={formData.type}
              onValueChange={(value) => setFormData({ ...formData, type: value as SystemType })}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择系统类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="JENKINS">Jenkins</SelectItem>
                <SelectItem value="GIT">Git</SelectItem>
                <SelectItem value="ZENTAO">禅道</SelectItem>
              </SelectContent>
            </Select>
          </div>

          <div className="grid gap-2">
            <Label htmlFor="url">系统地址 *</Label>
            <Input
              id="url"
              value={formData.url || ''}
              onChange={(e) => setFormData({ ...formData, url: e.target.value })}
              placeholder="请输入系统地址"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="authType">认证方式 *</Label>
            <Select
              value={formData.authType}
              onValueChange={(value) => setFormData({ ...formData, authType: value as AuthType })}
            >
              <SelectTrigger>
                <SelectValue placeholder="请选择认证方式" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="BASIC">用户名密码</SelectItem>
                <SelectItem value="TOKEN">令牌</SelectItem>
                <SelectItem value="OAUTH">OAuth2</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {formData.authType === 'BASIC' && (
            <>
              <div className="grid gap-2">
                <Label htmlFor="username">用户名 *</Label>
                <Input
                  id="username"
                  value={formData.username || ''}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  placeholder="请输入用户名"
                />
              </div>
              <div className="grid gap-2">
                <Label htmlFor="password">
                  密码 {!record && '*'}
                  {record && hasOriginalPassword && (
                    <span className="ml-2 text-xs text-muted-foreground">
                      (已配置，修改请输入新密码)
                    </span>
                  )}
                </Label>
                <Input
                  id="password"
                  type="password"
                  value={formData.password || ''}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  placeholder={record ? (hasOriginalPassword ? '保持不变或输入新密码' : '请输入密码') : '请输入密码'}
                />
              </div>
            </>
          )}

          {formData.authType === 'TOKEN' && (
            <div className="grid gap-2">
              <Label htmlFor="token">
                访问令牌 {!record && '*'}
                {record && hasOriginalToken && (
                  <span className="ml-2 text-xs text-muted-foreground">
                    (已配置，修改请输入新令牌)
                  </span>
                )}
              </Label>
              <Input
                id="token"
                type="password"
                value={formData.token || ''}
                onChange={(e) => setFormData({ ...formData, token: e.target.value })}
                placeholder={record ? (hasOriginalToken ? '保持不变或输入新令牌' : '请输入访问令牌') : '请输入访问令牌'}
              />
            </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="grid gap-2">
            <Label htmlFor="remark">备注</Label>
            <Textarea
              id="remark"
              value={formData.remark || ''}
              onChange={(e) => setFormData({ ...formData, remark: e.target.value })}
              placeholder="请输入备注"
              rows={4}
            />
          </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>
        </DialogBody>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;

