import type { FormData } from "@/lib/schemas/NewOrderForm.schema";
import {
  useWatch,
  type Control,
  type UseFormRegister,
  type UseFormSetValue,
} from "react-hook-form";

import Image from "next/image";

import CloseSVG from "@/assets/icons/close.svg";

import Button from "@/components/Button/Button";

import type { PopulatedProduct } from "@/services/models/Product";
import clsx from "clsx";
import Input from "../Input/Input";
import { Select } from "../Select";
import styles from "./OrderItem.module.scss";

export default function OrderItem({
  index,
  control,
  register,
  setValue,
  product,
  isRemovable,
  onRemove,
}: {
  index: number;
  control: Control<FormData>;
  register: UseFormRegister<FormData>;
  setValue: UseFormSetValue<FormData>;
  product: PopulatedProduct;
  isRemovable: boolean;
  onRemove: () => void;
}) {
  /* eslint-disable-next-line @typescript-eslint/restrict-template-expressions
     -- RHF caviat */
  const idBase = `items.${index}` as const;
  const sku = useWatch({
    control,
    name: `${idBase}.sku`,
  });
  const quantity = useWatch({
    control,
    name: `${idBase}.quantity`,
  });
  const variant = product.variants.find((variant) => variant.sku === sku);

  if (!variant) return;

  const finalPrice = variant.discount?.value
    ? variant.discount.type === "percent"
      ? variant.price - (variant.discount.value / 100) * variant.price
      : variant.price - variant.discount.value
    : variant.price;

  function formatToCurrency(num: number) {
    return new Intl.NumberFormat("ru-RU", {
      style: "currency",
      currency: "RUB",
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(num);
  }

  return (
    <tr className={styles["order-item"]}>
      <th>
        {isRemovable && (
          <Button variant="plain" icon={CloseSVG} onClick={onRemove} />
        )}
      </th>
      <td>
        <div className={styles["order-item__name-container"]}>
          <div className={styles["order-item__cover-wrapper"]}>
            <Image
              src={variant.cover}
              alt=""
              fill
              className={styles["order-item__cover"]}
            />
          </div>

          <span>{product.name}</span>
        </div>
      </td>
      <td>{variant.sku}</td>
      <td>
        <Select.Root
          value={variant.colorId.name}
          onChange={(value) => {
            const newSku = product.variants.find(
              (variant) => variant.colorId.name === value,
            )?.sku;

            if (!newSku) return;

            setValue(`${idBase}.sku`, newSku, { shouldValidate: true });
          }}
        >
          {product.variants
            .map((variant) => variant.colorId)
            .map((color) => (
              <Select.Option
                key={color.name}
                imageURL={color.image.url}
                value={color.name}
              />
            ))}
        </Select.Root>
      </td>
      <td
        className={clsx(
          styles["order-item__input"],
          styles["order-item__price-input"],
        )}
      >
        {formatToCurrency(finalPrice)}
      </td>
      <td>
        <Input
          type="number"
          min={1}
          {...register(`${idBase}.quantity`, {
            required: true,
            valueAsNumber: true,
            min: 1,
          })}
          className={clsx(
            styles["order-item__input"],
            styles["order-item__quantity-input"],
          )}
        />
      </td>
      <td
        className={clsx(
          styles["order-item__input"],
          styles["order-item__subtotal"],
        )}
      >
        {formatToCurrency(finalPrice * quantity)}
      </td>
    </tr>
  );
}
