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 { 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,
  });

  useEffect(() => {
    if (open) {
      if (record) {
        setFormData({
          name: record.name,
          type: record.type,
          url: record.url,
          authType: record.authType,
          username: record.username,
          password: undefined, // 不显示密码
          token: undefined,
          sort: record.sort,
          remark: record.remark,
          enabled: record.enabled,
        });
      } else {
        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 (formData.authType === 'TOKEN') {
        if (!record && !formData.token) {
          toast({ title: '提示', description: '请输入访问令牌', variant: 'destructive' });
          return;
        }
      }

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

      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="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 && '*'}</Label>
                <Input
                  id="password"
                  type="password"
                  value={formData.password || ''}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  placeholder={record ? '不修改请留空' : '请输入密码'}
                />
              </div>
            </>
          )}

          {formData.authType === 'TOKEN' && (
            <div className="grid gap-2">
              <Label htmlFor="token">访问令牌 {!record && '*'}</Label>
              <Input
                id="token"
                type="password"
                value={formData.token || ''}
                onChange={(e) => setFormData({ ...formData, token: e.target.value })}
                placeholder={record ? '不修改请留空' : '请输入访问令牌'}
              />
            </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>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;

