import React, { useEffect } 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import * as z from 'zod';
import type { PermissionResponse } from '@/pages/System/Permission/List/types';

interface PermissionEditDialogProps {
  open: boolean;
  record?: PermissionResponse;
  menuId: number;
  menuName: string;
  onOpenChange: (open: boolean) => void;
  onSubmit: (data: FormValues) => void;
}

const formSchema = z.object({
  code: z.string().min(1, '请输入权限编码'),
  name: z.string().min(1, '请输入权限名称'),
  type: z.string().min(1, '请选择权限类型'),
  sort: z.number().min(0, '排序必须大于等于0'),
});

export type FormValues = z.infer<typeof formSchema>;

const PermissionEditDialog: React.FC<PermissionEditDialogProps> = ({
  open,
  record,
  menuId,
  menuName,
  onOpenChange,
  onSubmit,
}) => {
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
    setValue,
    watch,
  } = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      code: '',
      name: '',
      type: 'BUTTON',
      sort: 0,
    },
  });

  const selectedType = watch('type');

  useEffect(() => {
    if (open) {
      if (record) {
        // 编辑模式
        reset({
          code: record.code,
          name: record.name,
          type: record.type,
          sort: record.sort,
        });
      } else {
        // 新建模式
        reset({
          code: '',
          name: '',
          type: 'BUTTON',
          sort: 0,
        });
      }
    }
  }, [open, record, reset]);

  const handleFormSubmit = (data: FormValues) => {
    onSubmit(data);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[500px]">
        <DialogHeader>
          <DialogTitle>{record ? '编辑权限' : '新建权限'}</DialogTitle>
          <p className="text-sm text-muted-foreground mt-1">
            菜单：{menuName}
          </p>
        </DialogHeader>
        <form onSubmit={handleSubmit(handleFormSubmit)}>
          <div className="grid gap-4 px-6 py-4">
            <div className="grid gap-2">
              <Label htmlFor="code">权限编码 *</Label>
              <Input
                id="code"
                placeholder="例如: user:create"
                {...register('code')}
              />
              {errors.code && (
                <p className="text-sm text-destructive">{errors.code.message}</p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="name">权限名称 *</Label>
              <Input
                id="name"
                placeholder="例如: 创建用户"
                {...register('name')}
              />
              {errors.name && (
                <p className="text-sm text-destructive">{errors.name.message}</p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="type">权限类型 *</Label>
              <Select
                value={selectedType}
                onValueChange={(value) => setValue('type', value)}
              >
                <SelectTrigger id="type">
                  <SelectValue placeholder="选择权限类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="MENU">菜单权限</SelectItem>
                  <SelectItem value="BUTTON">按钮权限</SelectItem>
                  <SelectItem value="API">接口权限</SelectItem>
                </SelectContent>
              </Select>
              {errors.type && (
                <p className="text-sm text-destructive">{errors.type.message}</p>
              )}
            </div>

            <div className="grid gap-2">
              <Label htmlFor="sort">排序 *</Label>
              <Input
                id="sort"
                type="number"
                placeholder="0"
                {...register('sort', { valueAsNumber: true })}
              />
              {errors.sort && (
                <p className="text-sm text-destructive">{errors.sort.message}</p>
              )}
            </div>
          </div>

          <DialogFooter>
            <Button variant="outline" type="button" onClick={() => onOpenChange(false)}>
              取消
            </Button>
            <Button type="submit">确定</Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
};

export default PermissionEditDialog;

