import Input from "@/components/Forms/Input";
import { handleSweetAlert } from "@/components/Modal/SweetAlertConfirm";
import { GetForm } from "@/utils";
import { Typography } from "@material-tailwind/react";
import { Check, Link, X } from "lucide-react";
import { useState } from "react";
import { GoTriangleDown } from "react-icons/go";
import { toast } from "react-toastify";

const ItemKitHelte = ({
  componente,
  submitEditItemKit,
  submitDeleteItemKit,
}: any) => {
  const [isOpenDatasheet, setIsOpenDatasheet] = useState(false);
  const [isEditing, setIsEditing] = useState(false);

  const { handleSubmit, ...formItem } = GetForm();

  function submitEdicaoItem(data: any) {
    setIsEditing(false);
    return submitEditItemKit({ id: componente.id, quantity: +data.quantity });
  }

  const classes = "p-4 border-b dark:border-boxdark border-blue-gray-50";
  return (
    <>
      <tr
        onClick={() => setIsOpenDatasheet(!isOpenDatasheet)}
        className="hover:bg-[rgba(0,0,0,0.05)] hover:cursor-pointer z-2"
      >
        <td className={classes}>
          <div className="flex items-center gap-3">
            <div className="flex flex-row items-center">
              <div className={`transition ${isOpenDatasheet && "rotate-180"}`}>
                <GoTriangleDown
                  className={`${!componente?.datasheet ? "text-[rgba(0,0,0,0)]" : componente?.datasheet?.length < 1 && "text-[rgba(0,0,0,0)]"}`}
                />
              </div>
              <Typography
                variant="small"
                color="blue-gray"
                className="font-normal"
              >
                {componente.category.name}
              </Typography>
            </div>
          </div>
        </td>

        <td className={classes}>
          <div className="flex items-center gap-3">
            <div className="flex flex-col">
              <Typography
                variant="small"
                color="blue-gray"
                className="font-normal"
              >
                {componente.name}
                {componente.type == "inverter" &&
                  ` - ${
                    Number(
                      componente.datasheet.find(
                        (e: any) => e.name == "Potência Nominal"
                      )?.value
                    ) / 1000
                  }kW`}
              </Typography>
            </div>
          </div>
        </td>
        <td
          className={classes}
          onClick={(e) => {
            e.stopPropagation();
            if (componente.type == "module") {
              toast.warning(
                "Para mudar a quantidade de módulos é necessário redistribuir os módulos"
              );
            } else {
              setIsEditing(true);
            }
          }}
        >
          <div className="flex flex-row items-center gap-3">
            {isEditing ? (
              <div>
                <Input
                  name="quantity"
                  formulario={formItem}
                  defaultValue={componente.qtd}
                  onKeyDown={(e: any) => {
                    e.stopPropagation();
                    if (e.key.includes("Enter")) {
                      e.preventDefault();
                      handleSubmit(submitEdicaoItem)(e);
                    }
                  }}
                  className={"w-15"}
                  width={"w-fit"}
                  mascara="numerico"
                  required
                  error="Informe a quantidade"
                  prefixWidth="0"
                />
                <div className="flex flex-row flex-nowrap justify-between w-full gap-[1px]">
                  <div
                    onClick={handleSubmit(submitEdicaoItem)}
                    className="bg-success text-white rounded p-1 flex-1 flex flex-col items-center justify-center"
                  >
                    <Check size={15} />
                  </div>
                  <div
                    onClick={(e) => {
                      e.stopPropagation();
                      setIsEditing(false);
                    }}
                    className="bg-error text-white rounded p-1 flex-1 flex flex-col items-center justify-center"
                  >
                    <X size={15} />
                  </div>
                </div>
              </div>
            ) : (
              <div className="flex flex-row justify-between flex-nowrap w-full">
                <Typography
                  variant="small"
                  color="blue-gray"
                  className="font-normal"
                >
                  {componente.qtd}
                </Typography>
                {componente.type != "module" && submitDeleteItemKit && (
                  <div
                    className="hover:bg-error/60 rounded p-[1px] bg-error text-white"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleSweetAlert(
                        {
                          icon: "warning",
                          title: `Excluir item do kit`,
                          html: `
                        <div>
                          <span>
                            Confirmar a remoção do item?
                          </span>
                          <div>${componente.name}</div>
                        </div>
                        `,
                        },
                        async () =>
                          submitDeleteItemKit({
                            id: componente.id,
                          })
                      );
                    }}
                  >
                    <X size={20} />
                  </div>
                )}
              </div>
            )}
          </div>
        </td>
      </tr>
      {isOpenDatasheet && componente?.datasheet?.length > 0 && (
        <tr className="z-1">
          <td colSpan={3} className={classes + "px-3"}>
            {componente.url_inmetro && (
              <div className="font-semibold flex flex-row items-center gap-2">
                <div>Inmetro</div>
                <a
                  href={componente.url_inmetro}
                  target="_blank"
                  className="text-secondaryMenu"
                >
                  <Link size={15} />
                </a>
              </div>
            )}
            <div className="font-semibold flex flex-row items-center gap-2">
              <div>Datasheet</div>
              {componente.url_datasheet && (
                <a
                  href={componente.url_datasheet}
                  target="_blank"
                  className="text-secondaryMenu"
                >
                  <Link size={15} />
                </a>
              )}
            </div>
            <table>
              <thead>
                <tr>
                  <th className="px-2">Nome</th>
                  <th className="px-2">Valor</th>
                </tr>
              </thead>
              <tbody>
                {componente.datasheet.map((item: any, index: number) => (
                  <tr key={index}>
                    <td className="px-2 py-[2px]">{item.name}</td>
                    <td className="px-2">
                      {item.value}
                      {item.si || ""}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </td>
        </tr>
      )}
    </>
  );
};

export default ItemKitHelte;
