import { useState } from "preact/hooks";
import { Portal } from "./Portal.tsx";
import { type ModalAction, ProjectModal } from "./ProjectModal.tsx";
import { ImageCarousel } from "./ImageCarousel.tsx";
import * as hi from "@preact-icons/hi2";

export const ProjectCard = function ProjectCard(props: ProjectProps) {
  const [open, setOpen] = useState(false);

  const modalButtons: Array<ModalAction> = [
    {
      label: "Open repository",
      icon: <hi.HiCodeBracket />,
      onClick: () => {
        if (props.repo) globalThis.open(props.repo, "_blank");
      },
      variant: "primary",
    },
  ];

  return (
    <div
      class={`md:m-8 group space-y-1 rounded-md ${
        props.wip ? "border-2" : "cursor-pointer"
      } bg-[#44485b] px-3 py-2 m-4 shadow-md transition-all duration-300 ease-in-out border-b-4 border-b-[#94e2d5] hover:shadow-xl hover:scale-105`}
      style={
        props.wip
          ? {
              borderTopStyle: "dashed",
              borderRightStyle: "dashed",
              borderLeftStyle: "dashed",
            }
          : {}
      }
      onClick={() => {
        // clicking the card (not the link) opens the modal
        setOpen(true);
      }}
    >
      <div class="flex items-center justify-between">
        <h2 class="text-lg text-white font-black uppercase">
          <a
            href={props.repo}
            target="_blank"
            onClick={(e) => {
              // clicking the link should not open the modal
              e.stopPropagation();
            }}
          >
            {props.title}
          </a>
        </h2>
        <div class="bg-[#585b70] text-[#a6adc8] text-xs font-bold uppercase px-2.5 py-0.5 rounded-full">
          {props.repo && <span>Active</span>}
          {!props.repo && !props.wip && <span>Dead</span>}
          {props.wip && <span>WIP</span>}
        </div>
      </div>
      <p class="whitespace-pre-wrap italic font-light text-lg text-[#a6adc8]">
        {props.summary}
      </p>
      <p class="whitespace-pre-wrap text-sm font-semibold text-[#a6adc8]">
        {props.tech}
      </p>

      {open && !props.wip ? (
        <Portal into="body">
          <ProjectModal
            title={props.title}
            onClose={() => setOpen(false)}
            actions={modalButtons}
          >
            <div class="space-y-3">
              {props.images && props.images.length > 0 && (
                <ImageCarousel images={props.images} />
              )}
              <p class="text-sm text-gray-800 dark:text-gray-200">
                {props.description}
              </p>
              <p class="text-xs font-mono text-gray-600 dark:text-gray-300">
                Technologies used: {props.tech}
              </p>
            </div>
          </ProjectModal>
        </Portal>
      ) : null}
    </div>
  );
};

type ProjectProps = {
  title: string;
  repo?: string;
  summary: string;
  description?: string;
  tech: string;
  wip?: boolean;
  images?: string[];
};
