import * as React from "react";

import { cn } from "@/lib/utils";
import { FormControl, FormDescription, FormField, FormItem, InputProps } from "@/ui";
import { Quantity, QuantityObject } from "@shared/contexts";
import { cva, type VariantProps } from "class-variance-authority";
import CurrencyInput, { CurrencyInputOnChangeValues } from "react-currency-input-field";
import { FieldPath, FieldValues, UseControllerProps, useFormContext } from "react-hook-form";
import { FormErrorMessage } from "./FormErrorMessage";
import { FormLabel, FormLabelProps } from "./FormLabel";
import { FormInputProps, FormInputWithIconProps } from "./FormProps";

const formQuantityFieldVariants = cva(
  "flex h-10 w-full rounded-md bg-background px-3 py-2 text-sm placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",
  {
    variants: {
      variant: {
        default:
          "border border-input ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ",
        outline: "focus-visible:border focus-visible:border-input",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
);

export type FormQuantityFieldProps<
  TFieldValues extends FieldValues = FieldValues,
  TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
  button?: (props?: React.PropsWithChildren) => React.ReactNode;
  defaultValue?: any;
} & InputProps &
  FormInputProps &
  Partial<FormLabelProps> &
  FormInputWithIconProps &
  UseControllerProps<TFieldValues, TName> &
  VariantProps<typeof formQuantityFieldVariants> & {
    scale: number;
  };

export const FormQuantityField = React.forwardRef<HTMLInputElement, FormQuantityFieldProps>(
  (props, ref) => {
    const {
      name,
      label,
      hint,
      description,
      placeholder,
      className,
      disabled,
      defaultValue,
      rules,
      readOnly,
      scale,
      variant,
    } = props;

    const { control } = useFormContext();

    const [inputValue, setInputValue] = React.useState<string>("");

    const transform = {
      input: (value: QuantityObject) => {
        if (typeof value !== "object") {
          return value;
        }

        const quantityOrError = Quantity.create(value);
        if (quantityOrError.isFailure) {
          throw quantityOrError.error;
        }

        const result = quantityOrError.object.toString();
        return inputValue.endsWith(",") ? result.replace(/.0$/, ",") : result;
      },
      output: (
        _value: string | undefined,
        _name?: string,
        values?: CurrencyInputOnChangeValues
      ) => {
        const { value: amount } = values ?? { value: null };

        setInputValue(amount ?? "");

        const quantityOrError = Quantity.createFromFormattedValue(amount);
        if (quantityOrError.isFailure) {
          throw quantityOrError.error;
        }

        return quantityOrError.object.toObject();
      },
    };

    return (
      <FormField
        defaultValue={defaultValue}
        control={control}
        name={name}
        disabled={disabled}
        rules={rules}
        render={({ field }) => {
          return (
            <FormItem ref={ref} className={cn(className, "space-y-3")}>
              {label && (
                <FormLabel label={label} hint={hint} required={Boolean(rules?.required ?? false)} />
              )}
              <FormControl>
                <CurrencyInput
                  name={field.name}
                  //ref={field.ref} //<-- no activar que hace cosas raras
                  onBlur={field.onBlur}
                  disabled={field.disabled}
                  readOnly={readOnly}
                  className={cn(formQuantityFieldVariants({ variant, className }))}
                  groupSeparator='.'
                  decimalSeparator=','
                  placeholder={placeholder}
                  allowDecimals={scale !== 0}
                  decimalsLimit={scale}
                  decimalScale={scale}
                  step={1}
                  //{...field}
                  value={transform.input(field.value)}
                  //onChange={() => {}}
                  onValueChange={(value, name, values) =>
                    field.onChange(transform.output(value, name, values))
                  }
                />
              </FormControl>
              {description && <FormDescription>{description}</FormDescription>}
              <FormErrorMessage />
            </FormItem>
          );
        }}
      />
    );
  }
);
