'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 { useCreateProduct } from "@/feactures/inventory/hooks/use-mutation";
import { createProduct, EditInventory } from '@/feactures/inventory/schemas/inventory';
import { Textarea } from '@repo/shadcn/textarea';
import { STATUS } from '@/constants/status'
import { useState, useEffect } from 'react';
import { sizeFormate } from "@/feactures/inventory/utils/sizeFormate"

interface CreateFormProps {
  onSuccess?: () => void;
  onCancel?: () => void;
}

export function CreateForm({
  onSuccess,
  onCancel,
}: CreateFormProps) {
  const {
    mutate: saveProduct,
    isPending: isSaving,
  } = useCreateProduct();

  const [sizeFile, setSizeFile] = useState('0 bytes');
  const [previewUrls, setPreviewUrls] = useState<string[]>([]);

  useEffect(() => {
    return () => {
      previewUrls.forEach(url => URL.revokeObjectURL(url));
    };
  }, [previewUrls]);

  const defaultformValues: EditInventory = {
    title: '',
    description: '',
    price: '',
    address: '',
    status: 'BORRADOR',
    stock: 0,
    urlImg: undefined,
  };

  const form = useForm<EditInventory>({
    resolver: zodResolver(createProduct),
    defaultValues: defaultformValues,
    mode: 'onChange',
  });

  const onSubmit = async (data: EditInventory) => {
    const formData = new FormData();

    formData.append('title', data.title);
    formData.append('description', data.description);
    formData.append('price', String(data.price));
    formData.append('address', data.address);
    formData.append('status', data.status);
    formData.append('stock', String(data.stock));

    if (data.urlImg) {
      for (let i = 0; i < data.urlImg.length; i++) {
        const file = data.urlImg[i];
        if (file) {
          formData.append('urlImg', file);
        }
      }
    }

    saveProduct(formData as any, {
      onSuccess: () => {
        form.reset();
        onSuccess?.();
      },
      onError: (error) => {
        console.error("Error al guardar el producto:", error);
        form.setError('root', {
          type: 'manual',
          message: error.message || 'Error al guardar el producto',
        });
      },
    });
  };

  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: 5MB / {sizeFile} <span className='text-xs text-destructive'>(Máximo 10 archivos)</span></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);
                          let size = 0;
                          const newPreviewUrls: string[] = [];

                          files.forEach(element => {
                            size += element.size;
                            newPreviewUrls.push(URL.createObjectURL(element));
                          });

                          const tamañoFormateado = sizeFormate(size);
                          setSizeFile(tamañoFormateado);
                          setPreviewUrls(newPreviewUrls);
                          onChange(e.target.files);
                        } else {
                          setPreviewUrls([]);
                        }
                      }}
                    />
                  </FormControl>
                  <FormMessage />
                  {previewUrls.length > 0 && (
                    <div className="mt-2 flex flex-wrap gap-2">
                      {previewUrls.map((url, index) => (
                        <img key={index} src={url} alt={`Preview ${index}`} className="w-24 h-24 object-cover rounded-md" />
                      ))}
                    </div>
                  )}
                </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>
  );
}