import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  editarEtiqueta,
  excluirEtiquetas,
  listarEtiquetas,
} from "@/requests/CRM/kanban";
import { GetForm } from "@/utils";
import { Pen, Plus, Trash2 } from "lucide-react";
import { Fragment, useState } from "react";
import Swal from "sweetalert2";
import * as yup from "yup";
import Input from "../Forms/Input";
import { Button } from "../ui/button";

interface Etiqueta {
  id_etiqueta_kanban: string;
  titulo_etiqueta_kanban: string;
  cor_etiqueta_kanban: string;
}

const PopoverEtiqueta = ({
  dados,
  allTags,
  dadosEtiqueta: etiquetas,
  etiquetasSelecionadas,
  setUrgencia,
  cadastrarEtiquetas,
}: any) => {
  const [corEtiqueta, setCorEtiqueta] = useState("#d71295");
  const [tituloEtiqueta, setTituloEtiqueta] = useState("");
  const [openPopOverContent, setOpenPopOverContent] = useState(false);
  const [openPopOverEdit, setOpenPopOverEdit] = useState(false);
  const [etiquetaAtual, setEtiquetaAtual] = useState<Etiqueta | null>(null);

  const [yupSchema, setYupSchema] = useState<
    yup.ObjectSchema<{}, yup.AnyObject, {}, "">
  >(yup.object().shape({}));
  const { handleSubmit, ...form } = GetForm(yupSchema, setYupSchema);

  const cores = [
    "#d71295",
    "#ed678d",
    "#6c7395",
    "#87896b",
    "#0a913b",
    "#3d4e81",
    "#ac0214",
    "#1415be",
    "#e3f43b",
    "#00e403",
  ];

  const handleTituloChange = (e: any) => {
    setTituloEtiqueta(e.target.value);
  };
  const handleSave = () => {
    const data = form.control._formValues;

    if (!data["corEtiqueta"]) {
      data["corEtiqueta"] = "#d71295";
      return;
    }
    setOpenPopOverContent(false);
    cadastrarEtiquetas(data);
  };

  const handleEdit = () => {
    if (!etiquetaAtual) {
      console.error("Etiqueta atual não está definida.");
      return;
    }

    setOpenPopOverEdit(false);
    editarEtiqueta(etiquetaAtual);
    listarEtiquetas();
  };

  const handleChangeCor = (cor: string) => {
    setCorEtiqueta(cor);
    const setValue = form.setValue;
    setValue("corEtiqueta" as never, cor as never);
  };
  const calculateContrastColor = (backgroundColor: any) => {
    // Convert hex color to RGB
    const r = parseInt(backgroundColor.slice(1, 3), 16);
    const g = parseInt(backgroundColor.slice(3, 5), 16);
    const b = parseInt(backgroundColor.slice(5, 7), 16);

    // Calculate relative luminance
    const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;

    return luminance > 0.5 ? "black" : "white";
  };
  const truncateText = (text: any, maxLength: any) => {
    if (text.length > maxLength) {
      return text.substring(0, maxLength) + "...";
    }
    return text;
  };
  const handleSetTag = (
    id_etiqueta_kanban: any,
    titulo_etiqueta_kanban: any,
    cor_etiqueta_kanban: any
  ) => {
    allTags({
      id_etiqueta_kanban,
      titulo_etiqueta_kanban,
      cor_etiqueta_kanban,
    });
  };

  const handleEditTag = (
    id_etiqueta_kanban: any,
    titulo_etiqueta_kanban: any,
    cor_etiqueta_kanban: any
  ) => {
    // Setando a etiqueta atual e abrindo o popover
    setEtiquetaAtual({
      id_etiqueta_kanban,
      titulo_etiqueta_kanban,
      cor_etiqueta_kanban,
    });
    setOpenPopOverEdit(true); // Abre o popover
  };

  const handleDeleteTag = (
    id_etiqueta_kanban: any,
    titulo_etiqueta_kanban: any,
    cor_etiqueta_kanban: any
  ) => {
    Swal.fire({
      title: `Excluira etiqueta a baixo?`,
      text: ` ${titulo_etiqueta_kanban}`,
      icon: "warning",
      showCancelButton: true,
      confirmButtonColor: "#d33",
      cancelButtonColor: "#3085d6",
      confirmButtonText: "excluir",
      cancelButtonText: "cancelar",
    }).then((result) => {
      if (result.isConfirmed) {
        excluirEtiquetas(id_etiqueta_kanban);
        listarEtiquetas();
      }
    });
  };
  const urgencias = [
    { title: "Sem urgência", cor: "" },
    { title: "Alta", cor: "danger" },
    { title: "Média", cor: "warning" },
    { title: "Baixa", cor: "primary" },
  ];

  const truncatedTituloEtiqueta = truncateText(tituloEtiqueta, 25);
  const textColor = calculateContrastColor(corEtiqueta);

  const classUrgenciaItens =
    "flex items-center hover:opacity-95 p-1 cursor-pointer rounded  text-sm";

  return (
    <Fragment>
      <div className="bg-white rounded-lg shadow-lg w-full p-4 text-white">
        {dados.name === "Urgência" ? (
          urgencias.map((urgencia, index) => (
            <div
              key={index}
              onClick={() =>
                setUrgencia({
                  name: urgencia.title,
                  color: urgencia.cor,
                })
              }
              className={`w-full text-black my-1 bg-${urgencia.cor} ${classUrgenciaItens}`}
            >
              {urgencia.title}
            </div>
          ))
        ) : etiquetas && etiquetas.length > 0 ? (
          etiquetas.map((etiqueta: any) => (
            <div
              key={etiqueta.id_etiqueta_kanban}
              className="flex items-center gap-1 my-1 text-white"
            >
              <input
                className="h-5 w-5 checked:bg-primary"
                type="checkbox"
                onChange={() =>
                  handleSetTag(
                    etiqueta.id_etiqueta_kanban,
                    etiqueta.titulo_etiqueta_kanban,
                    etiqueta.cor_etiqueta_kanban
                  )
                }
                checked={etiquetasSelecionadas.some(
                  (selected: any) =>
                    selected.id_etiqueta_kanban === etiqueta.id_etiqueta_kanban
                )}
              />
              <span
                style={{ backgroundColor: etiqueta.cor_etiqueta_kanban }}
                onClick={() =>
                  handleSetTag(
                    etiqueta.id_etiqueta_kanban,
                    etiqueta.titulo_etiqueta_kanban,
                    etiqueta.cor_etiqueta_kanban
                  )
                }
                className={`w-full ${classUrgenciaItens}`}
              >
                {etiqueta.titulo_etiqueta_kanban}
              </span>
              <span
                onClick={() =>
                  handleEditTag(
                    etiqueta.id_etiqueta_kanban,
                    etiqueta.titulo_etiqueta_kanban,
                    etiqueta.cor_etiqueta_kanban
                  )
                }
              >
                <Pen size={18} className="cursor-pointer  text-warning ml-1" />
              </span>

              <span
                onClick={() =>
                  handleDeleteTag(
                    etiqueta.id_etiqueta_kanban,
                    etiqueta.titulo_etiqueta_kanban,
                    etiqueta.cor_etiqueta_kanban
                  )
                }
              >
                <Trash2
                  size={18}
                  className="cursor-pointer  text-danger ml-1"
                />
              </span>
            </div>
          ))
        ) : (
          <p className="text-graydark text-sm">Nenhuma etiqueta disponível.</p>
        )}
      </div>

      {etiquetaAtual && (
        <PopoverContent className="z-99999 dark:bg-black translate-y-50 w-75  -mt-39 px-0">
          <div className="grid ">
            <header className="text-center mb-3">Editar {dados.name}</header>
            <div className="px-4 grid gap-3 mt-3">
              <label>Título</label>
              <Input
                formulario={form}
                name="tituloNovoItem"
                value={etiquetaAtual.titulo_etiqueta_kanban}
                className="border-2 w-full dark:bg-form-input border-stroke rounded"
                type="text"
                onChange={(e) =>
                  setEtiquetaAtual({
                    ...etiquetaAtual,
                    titulo_etiqueta_kanban: e.target.value,
                  })
                }
              />
              <label>Cor</label>
              <div className="grid grid-cols-5 gap-2 px-4">
                {cores.map((cor, index) => (
                  <div
                    key={index}
                    onClick={() => handleChangeCor(cor)}
                    className={`h-6 w-10 rounded-sm  cursor-pointer`}
                    style={{ backgroundColor: cor }}
                  ></div>
                ))}
              </div>
              <Button
                onClick={handleEdit}
                type="button"
                className="h-8 mt-4 bg-success"
              >
                Editar
              </Button>
            </div>
          </div>
        </PopoverContent>
      )}

      <Popover>
        <PopoverTrigger asChild onClick={() => setOpenPopOverContent(true)}>
          {dados.name === "Etiquetas" && (
            <div className="flex mt-1  items-center   cursor-pointer  hover:bg-stroke justify-center text-sm  bg-white rounded-lg shadow-lg w-full p-4 ">
              <Plus size={15} />
              Adicionar {dados.name}
            </div>
          )}
        </PopoverTrigger>
        {openPopOverContent && (
          <PopoverContent
            id="popover-content"
            className="  dark:bg-black  w-75 px-0"
          >
            <div className="grid ">
              <header className="text-center mb-3">Criar {dados.name}</header>
              <div className="bg-stroke dark:bg-form-strokedark  w-full justify-center items-center h-20 flex">
                <span
                  style={{
                    backgroundColor: corEtiqueta,
                    color: textColor,
                  }}
                  className={`w-10/12 rounded-md text-sm items-center pt-1 text-center font-medium h-7`}
                >
                  {truncatedTituloEtiqueta}
                </span>
              </div>
              <div className="px-4 grid gap-3 mt-3">
                <label>Título</label>
                <Input
                  formulario={form}
                  name="tituloNovoItem"
                  className="border-2 w-full dark:bg-form-input border-stroke rounded"
                  type="text"
                  onChange={handleTituloChange}
                />
                <label>Cor</label>
                <div className="grid grid-cols-5 gap-2 px-4">
                  {cores.map((cor, index) => (
                    <div
                      key={index}
                      onClick={() => handleChangeCor(cor)}
                      className={`h-6 w-10 rounded-sm  cursor-pointer`}
                      style={{ backgroundColor: cor }}
                    ></div>
                  ))}
                </div>
                <Button
                  onClick={handleSave}
                  type="button"
                  className="h-8 mt-4 bg-success"
                >
                  Criar
                </Button>
              </div>
            </div>
          </PopoverContent>
        )}
      </Popover>
    </Fragment>
  );
};

export default PopoverEtiqueta;
