'use client';
import { zodResolver } from '@hookform/resolvers/zod';
import { Button } from '@repo/shadcn/button';
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@repo/shadcn/form';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@repo/shadcn/select';
import { Input } from '@repo/shadcn/input';
import { useForm } from 'react-hook-form';
import { useUpdateUser } from "@/feactures/inventory/hooks/use-mutation";
import { editInventory, EditInventory } from '@/feactures/inventory/schemas/inventory'; // Renombrado EditInventory para claridad
import { Textarea } from '@repo/shadcn/components/ui/textarea';
import {STATUS} from '@/constants/status'
import { useState } from 'react';
import {sizeFormate} from "@/feactures/inventory/utils/sizeFormate"

interface UpdateFormProps {
  onSuccess?: () => void;
  onCancel?: () => void;
  defaultValues?: Partial<EditInventory>;
}

export function UpdateForm({
  onSuccess,
  onCancel,
  defaultValues,
}: UpdateFormProps) {
  const {
    mutate: saveAccountingAccounts,
    isPending: isSaving,
    isError, // isError no se usa en el template, podrías usarlo para mostrar un mensaje global
  } = useUpdateUser();

  const [sizeFile, setSizeFile] = useState('0 bytes'); 

  const defaultformValues: EditInventory = {
    id: defaultValues?.id, 
    title: defaultValues?.title || '',
    description: defaultValues?.description || '',
    price: defaultValues?.price || '',
    address: defaultValues?.address || '',
    status: defaultValues?.status || 'BORRADOR',
    stock: defaultValues?.stock ?? 0,
    urlImg: [], 
    userId: defaultValues?.userId 
  };

  const form = useForm<EditInventory>({ 
    resolver: zodResolver(editInventory),
    defaultValues: defaultformValues,
    mode: 'onChange', // Enable real-time validation
  });

  const onSubmit = async (data: EditInventory) => {
    // console.log(data);
    
    saveAccountingAccounts(data, {
      onSuccess: () => {
        form.reset();
        onSuccess?.();
      },
      onError: (error) => { // Captura el error para mostrar un mensaje más específico si es posible
        console.error("Error al guardar el producto:", error);
        form.setError('root', {
          type: 'manual',
          message: error.message || 'Error al guardar el producto', // Mejor mensaje de error
        });
      },
    });
  };

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        {form.formState.errors.root && (
          <div className="text-destructive text-sm">
            {form.formState.errors.root.message}
          </div>
        )}
        <div className="grid grid-cols-2 gap-4">
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Nombre/Título</FormLabel>
                <FormControl>
                  <Input {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="price"
            render={({ field }) => (
              <FormItem >
                <FormLabel>Precio</FormLabel>
                <FormControl>
                  <Input {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="address"
            render={({ field }) => (
              <FormItem className='col-span-2'>
                <FormLabel>Dirección</FormLabel>
                <FormControl>
                  <Input {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="description"
            render={({ field }) => (
              <FormItem className='col-span-2'>
                <FormLabel>Descripción</FormLabel>
                <FormControl>
                  <Textarea {...field} className="resize-none"/>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="stock"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Cantidad/Stock</FormLabel>
                <FormControl>
                  <Input {...field} type="number" onChange={(e) => field.onChange(Number(e.target.value))}/>
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />

          <FormField
            control={form.control}
            name="status"
            render={({ field }) => (
              <FormItem className="w-full">
                <FormLabel>Estatus</FormLabel>
                <Select value={field.value} onValueChange={(value) => field.onChange(value)}>
                  <SelectTrigger className="w-full">
                    <SelectValue placeholder="Seleccione un estatus" />
                  </SelectTrigger>
                  <SelectContent>
                    {Object.entries(STATUS).map(([value, label]) => (
                      <SelectItem key={value} value={value}>
                        {label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <FormMessage />
              </FormItem>
            )}
          />

          <div className="col-span-2">
            <FormField
              control={form.control}
              name="urlImg"
              render={({ field: { onChange, onBlur, name, ref } }) => (
                <FormItem>
                  <FormLabel>Imagen</FormLabel>
                  <p>Peso máximo: 2MB / {sizeFile}</p>
                  <FormControl>
                    <Input
                      type="file"
                      multiple
                      onBlur={onBlur}
                      name={name}
                      ref={ref}
                      onChange={(e) => {
                        if (e.target.files) {
                          const files = Array.from(e.target.files);
                          // Calcular el tamaño total de los archivos
                          let size = 0;
                          files.forEach(element => size += element.size)
                          const tamañoFormateado = sizeFormate(size)
                          setSizeFile(tamañoFormateado);
                        }
                        onChange(e.target.files);
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />
          </div>
        </div>

        <div className="flex justify-end gap-4">
          <Button variant="outline" type="button" onClick={onCancel}>
            Cancelar
          </Button>
          <Button type="submit" disabled={isSaving}>
            {isSaving ? 'Guardando...' : 'Guardar'}
          </Button>
        </div>
      </form>
    </Form>
  );
}