import { Add, AddCircle, CloseCircle } from "iconsax-react";
import { useRef, useState, type FC } from "react";
import { useTranslation } from "react-i18next";
import { toast } from '../../../components/Toast';
import ColorsImage from "../../../assets/images/colors.png";
import { ErrorType } from "../../../helpers/types";
import { clx } from "../../../helpers/utils";
import { useCreateTaskPhase } from "../task-phase/hooks/useTaskPhaseData";
import type { TaskPhaseItemType } from "../task-phase/types/TaskPhaseTypes";
import { LABEL_COLOR_OPTIONS } from "./task-detail/labels/constants";

const DEFAULT_COLUMN_COLOR = "#4F46E5";

type Props = {
  projectId: string;
  nextOrder: number;
  onColumnCreated: (phase: TaskPhaseItemType) => void;
};

const AddNewColumn: FC<Props> = ({ projectId, nextOrder, onColumnCreated }) => {
  const { t } = useTranslation("global");
  const colorInputRef = useRef<HTMLInputElement>(null);
  const createTaskPhase = useCreateTaskPhase();

  const [isAdding, setIsAdding] = useState(false);
  const [name, setName] = useState("");
  const [selectedColor, setSelectedColor] = useState(DEFAULT_COLUMN_COLOR);

  const resetForm = () => {
    setName("");
    setSelectedColor(DEFAULT_COLUMN_COLOR);
    setIsAdding(false);
  };

  const handleSubmit = () => {
    const trimmedName = name.trim();
    if (!trimmedName || !projectId) return;

    createTaskPhase.mutate(
      {
        name: trimmedName,
        order: nextOrder,
        color: selectedColor,
        projectId,
      },
      {
        onSuccess: (data) => {
          const phase = (data?.data ?? data) as TaskPhaseItemType;
          onColumnCreated(phase);
          toast(t("success"), 'success');
          resetForm();
        },
        onError: (error: ErrorType) => {
          toast(error.response?.data?.error.message[0], 'error');
        },
      },
    );
  };

  if (!isAdding) {
    return (
      <button
        type="button"
        onClick={() => setIsAdding(true)}
        className="bg-[#F0F3F7BF] bg-opacity-75 rounded-full px-4 sm:px-6 py-3 sm:py-4 flex items-center gap-2 shrink-0 self-start cursor-pointer w-[272px] sm:w-[288px] xl:w-[310px] justify-center"
      >
        <AddCircle size={16} color="black" />
        <span className="text-xs text-black">{t("taskmanager.add_new_column")}</span>
      </button>
    );
  }

  return (
    <div className="bg-[#F0F3F7] rounded-xl p-3 sm:p-4 xl:p-6 w-[272px] sm:w-[288px] xl:w-[310px] shrink-0 self-start flex flex-col gap-3 sm:gap-4">
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder={t("taskmanager.column_name")}
        className="w-full bg-white rounded-lg px-3 py-2.5 text-sm outline-none"
        autoFocus
      />

      <div>
        <div className="text-xs mb-3">{t("taskmanager.choose_color")}</div>
        <div className="flex items-center gap-2 flex-wrap">
          <button
            type="button"
            onClick={() => colorInputRef.current?.click()}
            className={clx(
              "size-6 rounded-lg cursor-pointer overflow-hidden",
              !LABEL_COLOR_OPTIONS.includes(
                selectedColor as (typeof LABEL_COLOR_OPTIONS)[number],
              ) && "ring-1 ring-[#0047FF] rounded-full",
            )}
            aria-label={t("taskmanager.choose_color")}
          >
            <img src={ColorsImage} alt="" className="size-full object-cover" />
          </button>
          {LABEL_COLOR_OPTIONS.map((color) => (
            <button
              key={color}
              type="button"
              onClick={() => setSelectedColor(color)}
              className={clx(
                "size-6 rounded-lg cursor-pointer transition-transform",
                color === "#FFFFFF" && "border border-[#D0D0D0]",
                selectedColor === color && "ring-2 ring-[#0047FF] ring-offset-1",
              )}
              style={{ backgroundColor: color }}
              aria-label={color}
            />
          ))}
          <input
            ref={colorInputRef}
            type="color"
            value={selectedColor}
            onChange={(e) => setSelectedColor(e.target.value)}
            className="sr-only"
          />
        </div>
      </div>

      <div className="flex items-center gap-2">
        <button
          type="button"
          onClick={handleSubmit}
          disabled={!name.trim() || createTaskPhase.isPending}
          className="flex items-center gap-2 bg-black text-white text-[13px] rounded-full px-4 py-2 cursor-pointer disabled:opacity-50"
        >
          <span>{t("taskmanager.add_column")}</span>
          <Add size={18} color="white" />
        </button>
        <button
          type="button"
          onClick={resetForm}
          className="cursor-pointer"
          aria-label={t("cancel")}
        >
          <CloseCircle size={22} color="#888888" variant="Bold" />
        </button>
      </div>
    </div>
  );
};

export default AddNewColumn;
