import { FC } from "react";
import { Link } from "react-router-dom";
import { Pages } from "../../../../config/Pages";
import type { ProjectItem } from "../types/ProjectTypes";
import ProjectCardMenu from "./ProjectCardMenu";

type Props = {
  project: ProjectItem;
  onDelete: (id: string) => void;
};

const hexToRgba = (hex: string, alpha: number) => {
  const normalized = hex.replace("#", "");
  const r = parseInt(normalized.slice(0, 2), 16);
  const g = parseInt(normalized.slice(2, 4), 16);
  const b = parseInt(normalized.slice(4, 6), 16);
  return `rgba(${r}, ${g}, ${b}, ${alpha})`;
};

const getCardBackground = (background: string) => {
  const color = /^#[0-9A-Fa-f]{6}$/i.test(background) ? background : (background.match(/#[0-9A-Fa-f]{6}/i)?.[0] ?? "#A8E6CF");

  return `linear-gradient(135deg, ${color}, ${hexToRgba(color, 0.5)})`;
};

const ProjectCard: FC<Props> = ({ project, onDelete }) => {
  const handleEdit = () => {
    // TODO: navigate to edit page when available
  };

  return (
    <div className="bg-white rounded-[20px] overflow-hidden shadow-sm border border-border/40 p-3">
      <Link to={Pages.taskmanager.workspace + project.id}>
        <div className="h-[84px] w-full rounded-[16px]" style={{ background: getCardBackground(project.background) }} />
      </Link>

      <div className="flex items-center justify-between mt-3.5">
        <Link to={Pages.taskmanager.workspace + project.id} className="text-sm font-medium text-black hover:opacity-70 transition-opacity">
          {project.name}
        </Link>

        <ProjectCardMenu onEdit={handleEdit} onDelete={() => onDelete(project.id)} />
      </div>
    </div>
  );
};

export default ProjectCard;
