import React from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { Save, X } from 'lucide-react';

import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@d8d/shared-ui-components/components/ui/form';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { AdminUpdateGoodsDto } from '@d8d/goods-module-mt/schemas';
import { UpdateRequest } from '../types/goods';
import { z } from 'zod';

interface ChildGoodsInlineEditFormProps {
  // 子商品数据
  child: {
    id: number;
    name: string;
    price: number;
    costPrice?: number;
    stock: number;
    sort: number;
    state: number;
  };

  // 回调函数
  onSave: (childId: number, updateData: UpdateRequest) => Promise<void>;
  onCancel: () => void;

  // 加载状态
  isLoading?: boolean;
}

// 从AdminUpdateGoodsDto提取我们需要的字段，并设置为必需
const childGoodsUpdateSchema = AdminUpdateGoodsDto.pick({
  name: true,
  price: true,
  costPrice: true,
  stock: true,
  sort: true,
  state: true
}).extend({
  name: z.string().min(1, '商品名称不能为空'),
  price: z.coerce.number<number>().multipleOf(0.01, '价格最多保留两位小数').min(0, '价格不能为负数'),
  costPrice: z.coerce.number<number>().multipleOf(0.01, '成本价最多保留两位小数').min(0, '成本价不能为负数').optional(),
  stock: z.coerce.number<number>().int().nonnegative('库存必须为非负数'),
  sort: z.coerce.number<number>().int().nonnegative('排序值必须为非负数'),
  state: z.number().int().min(1).max(2)
});

// 表单数据类型
type ChildGoodsFormData = z.infer<typeof childGoodsUpdateSchema>;

export const ChildGoodsInlineEditForm: React.FC<ChildGoodsInlineEditFormProps> = ({
  child,
  onSave,
  onCancel,
  isLoading = false
}) => {
  // 初始化表单
  const form = useForm<ChildGoodsFormData>({
    resolver: zodResolver(childGoodsUpdateSchema),
    defaultValues: {
      name: child.name,
      price: child.price,
      costPrice: child.costPrice,
      stock: child.stock,
      sort: child.sort,
      state: child.state
    }
  });

  // 处理表单提交
  const handleSubmit = async () => {
    const isValid = await form.trigger();
    if (!isValid) {
      return;
    }

    const data = form.getValues();
    // 准备更新数据 - 直接使用验证后的数据
    const updateData = {
      name: data.name,
      price: data.price,
      costPrice: data.costPrice,
      stock: data.stock,
      sort: data.sort,
      state: data.state
    };

    await onSave(child.id, updateData);
  };

  return (
    <Form {...form}>
      <form className="space-y-4">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* 商品名称 */}
          <FormField
            control={form.control}
            name="name"
            render={({ field }) => (
              <FormItem>
                <FormLabel>商品名称</FormLabel>
                <FormControl>
                  <Input
                    placeholder="请输入商品名称"
                    {...field}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 价格 */}
          <FormField
            control={form.control}
            name="price"
            render={({ field }) => (
              <FormItem>
                <FormLabel>价格</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    step="0.01"
                    min="0"
                    placeholder="0.00"
                    {...field}
                    value={field.value ?? ''}
                    onChange={(e) => field.onChange(e.target.value === '' ? undefined : parseFloat(e.target.value))}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 成本价 */}
          <FormField
            control={form.control}
            name="costPrice"
            render={({ field }) => (
              <FormItem>
                <FormLabel>成本价</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    step="0.01"
                    min="0"
                    placeholder="0.00"
                    {...field}
                    value={field.value ?? ''}
                    onChange={(e) => field.onChange(e.target.value === '' ? undefined : parseFloat(e.target.value))}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 库存 */}
          <FormField
            control={form.control}
            name="stock"
            render={({ field }) => (
              <FormItem>
                <FormLabel>库存</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    min="0"
                    step="1"
                    placeholder="0"
                    {...field}
                    value={field.value ?? ''}
                    onChange={(e) => field.onChange(e.target.value === '' ? undefined : parseInt(e.target.value))}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 排序 */}
          <FormField
            control={form.control}
            name="sort"
            render={({ field }) => (
              <FormItem>
                <FormLabel>排序</FormLabel>
                <FormControl>
                  <Input
                    type="number"
                    min="0"
                    step="1"
                    placeholder="0"
                    {...field}
                    value={field.value ?? ''}
                    onChange={(e) => field.onChange(e.target.value === '' ? undefined : parseInt(e.target.value))}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          {/* 状态 */}
          <FormField
            control={form.control}
            name="state"
            render={({ field }) => (
              <FormItem>
                <FormLabel>状态</FormLabel>
                <Select
                  value={field.value?.toString()}
                  onValueChange={(value) => field.onChange(parseInt(value))}
                >
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="选择状态" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="1">可用</SelectItem>
                    <SelectItem value="2">不可用</SelectItem>
                  </SelectContent>
                </Select>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>

        {/* 操作按钮 */}
        <div className="flex justify-end gap-2 pt-4">
          <Button
            type="button"
            variant="outline"
            onClick={onCancel}
            disabled={isLoading}
          >
            <X className="h-4 w-4 mr-2" />
            取消
          </Button>
          <Button
            type="button"
            disabled={isLoading}
            onClick={async (e) => {
              e.preventDefault();
              e.stopPropagation();
              await handleSubmit();
            }}
          >
            <Save className="h-4 w-4 mr-2" />
            {isLoading ? '保存中...' : '保存'}
          </Button>
        </div>
      </form>
    </Form>
  );
};