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 { useToast } from '@/components/ui/use-toast';
import { createRole, updateRole } from '../service';
import type { RoleResponse, RoleRequest } from '../types';

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

/**
 * 角色编辑对话框
 */
const EditDialog: React.FC<EditDialogProps> = ({
  open,
  record,
  onOpenChange,
  onSuccess,
}) => {
  const { toast } = useToast();
  const [formData, setFormData] = useState<Partial<RoleRequest>>({
    sort: 0,
  });

  useEffect(() => {
    if (open) {
      if (record) {
        setFormData({
          code: record.code,
          name: record.name,
          description: record.description,
          sort: record.sort,
        });
      } else {
        setFormData({ sort: 0 });
      }
    }
  }, [open, record]);

  const handleSubmit = async () => {
    try {
      // 验证
      if (!formData.code?.trim()) {
        toast({
          title: '提示',
          description: '请输入角色编码',
          variant: 'destructive'
        });
        return;
      }

      if (!formData.name?.trim()) {
        toast({
          title: '提示',
          description: '请输入角色名称',
          variant: 'destructive'
        });
        return;
      }

      if (record) {
        await updateRole(record.id, formData as RoleRequest);
        toast({
          title: '更新成功',
          description: `角色 "${formData.name}" 已更新`,
        });
      } else {
        await createRole(formData as RoleRequest);
        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-[500px]">
        <DialogHeader>
          <DialogTitle>{record ? '编辑角色' : '新建角色'}</DialogTitle>
        </DialogHeader>
        <div className="grid gap-4 py-4">
          <div className="grid gap-2">
            <Label htmlFor="code">角色编码 *</Label>
            <Input
              id="code"
              value={formData.code || ''}
              onChange={(e) => setFormData({ ...formData, code: e.target.value })}
              placeholder="请输入角色编码"
              disabled={!!record}
            />
          </div>

          <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="sort">排序</Label>
            <Input
              id="sort"
              type="number"
              value={formData.sort || 0}
              onChange={(e) => setFormData({ ...formData, sort: Number(e.target.value) })}
              placeholder="请输入排序值"
            />
          </div>

          <div className="grid gap-2">
            <Label htmlFor="description">描述</Label>
            <Textarea
              id="description"
              value={formData.description || ''}
              onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              placeholder="请输入描述"
              rows={4}
            />
          </div>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>
            取消
          </Button>
          <Button onClick={handleSubmit}>确定</Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
};

export default EditDialog;

