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 { useToast } from '@/components/ui/use-toast';
import { createEnvironment, updateEnvironment } from '../service';
import type { Environment, CreateEnvironmentRequest } 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({
          envCode: record.envCode,
          envName: record.envName,
          envDesc: record.envDesc,
          sort: record.sort,
          enabled: record.enabled,
        });
      } else {
        setFormData({ enabled: true, sort: 1 });
      }
    }
  }, [open, record]);

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.envCode?.trim()) {
        toast({ title: '提示', description: '请输入环境编码', variant: 'destructive' });
        return;
      }
      if (!formData.envName?.trim()) {
        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]">
        <DialogHeader>
          <DialogTitle>{record ? '编辑环境' : '新建环境'}</DialogTitle>
        </DialogHeader>
        <DialogBody>
        <div className="grid gap-4">
          <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="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>
        </DialogBody>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;

