import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { FileSelector } from '@d8d/file-management-ui-mt';
import { CreateGoodsCategoryDto, UpdateGoodsCategoryDto } from '@d8d/goods-module-mt/schemas';
import type { CreateGoodsCategoryDto as CreateGoodsCategoryInput, UpdateGoodsCategoryDto as UpdateGoodsCategoryInput } from '@d8d/goods-module-mt/schemas';

// 状态枚举
enum CategoryState {
  ENABLED = 1,
  DISABLED = 2
}

interface GoodsCategoryFormProps {
  category?: UpdateGoodsCategoryInput & { id?: number };
  onSubmit: (data: CreateGoodsCategoryInput | UpdateGoodsCategoryInput) => Promise<void>;
  onCancel: () => void;
  isLoading?: boolean;
  /** 智能预填的层级 */
  smartLevel?: number;
  /** 智能预填的父级ID */
  smartParentId?: number;
}

// 辅助函数：根据层级值获取显示名称
const getLevelDisplayName = (level: number | undefined): string => {
  switch (level) {
    case 0:
      return '顶级分类';
    case 1:
      return '一级分类';
    case 2:
      return '二级分类';
    case 3:
      return '三级分类';
    case 4:
      return '四级分类';
    default:
      return `${level}级分类`;
  }
};

export const GoodsCategoryForm: React.FC<GoodsCategoryFormProps> = ({
  category,
  onSubmit,
  onCancel,
  isLoading = false,
  smartLevel,
  smartParentId
}) => {
  const isEditing = !!category;

  const form = useForm<CreateGoodsCategoryInput | UpdateGoodsCategoryInput>({
    resolver: zodResolver(isEditing ? UpdateGoodsCategoryDto : CreateGoodsCategoryDto),
    defaultValues: category ? {
      tenantId: category.tenantId,
      parentId: category.parentId,
      name: category.name,
      level: category.level,
      state: category.state,
      imageFileId: category.imageFileId,
    } : {
      tenantId: 1, // 测试环境使用默认tenantId
      parentId: smartParentId || 0,
      name: '',
      level: smartLevel ?? 0,
      state: CategoryState.ENABLED,
      imageFileId: null,
    },
  });

  const handleSubmit = async (data: CreateGoodsCategoryInput | UpdateGoodsCategoryInput) => {
    await onSubmit(data);
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(handleSubmit)} className="space-y-6">
        <div className="grid grid-cols-1 gap-6">
          {/* 层级显示（只读） */}
          <FormField
            control={form.control}
            name="level"
            render={({ field }) => (
              <FormItem>
                <FormLabel>层级</FormLabel>
                <FormControl>
                  <Input
                    value={getLevelDisplayName(field.value)}
                    disabled
                    className="bg-muted"
                  />
                </FormControl>
                <FormDescription>
                  根据操作上下文自动设置的层级
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 父级分类显示（只读） */}
          <FormField
            control={form.control}
            name="parentId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>父级分类</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    value={field.value || ''}
                    disabled
                    className="bg-muted"
                    placeholder="顶级分类（无父级）"
                  />
                </FormControl>
                <FormDescription>
                  根据操作上下文自动设置的父级分类ID
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 分类名称 */}
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>分类名称</FormLabel>
                <FormControl>
                  <Input
                    placeholder="输入分类名称"
                    {...field}
                  />
                </FormControl>
                <FormDescription>
                  输入商品分类名称，如：电子产品、服装、食品等
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 状态选择 */}
          <FormField
            control={form.control}
            name="state"
            render={({ field }) => (
              <FormItem>
                <FormLabel>状态</FormLabel>
                <Select onValueChange={(value) => field.onChange(Number(value))} defaultValue={field.value?.toString()}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value={CategoryState.ENABLED.toString()}>
                      启用
                    </SelectItem>
                    <SelectItem value={CategoryState.DISABLED.toString()}>
                      禁用
                    </SelectItem>
                  </SelectContent>
                </Select>
                <FormDescription>
                  选择商品分类状态
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 分类图片 */}
          <FormField
            control={form.control}
            name="imageFileId"
            render={({ field }) => (
              <FormItem>
                <FormLabel>分类图片</FormLabel>
                <FormControl>
                  <FileSelector
                    value={field.value || undefined}
                    onChange={(value) => field.onChange(value)}
                    maxSize={2}
                    uploadPath="/goods-categories"
                    previewSize="medium"
                    placeholder="选择分类图片"
                    filterType="image"
                  />
                </FormControl>
                <FormDescription>
                  上传商品分类的展示图片
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* 表单操作按钮 */}
        <div className="flex justify-end gap-4">
          <Button
            type="button"
            variant="outline"
            onClick={onCancel}
            disabled={isLoading}
          >
            取消
          </Button>
          <Button
            type="submit"
            disabled={isLoading}
          >
            {isLoading ? '提交中...' : isEditing ? '更新' : '创建'}
          </Button>
        </div>
      </form>
    </Form>
  );
};