"use client";

import { useTransition } from "react";
import { Card } from "@/components/Card";
import "./HomeWalkingPill.css";

type ProgressDotState = "completed" | "current" | "upcoming";

type Props = {
  title: string;
  subtitle: string;
  accentColor: string;
  backgroundColor: string;
  linkTo: string;
  dots: ProgressDotState[];
  deleteAction?: () => Promise<void> | void;
  deleteLabel?: string;
  deleteConfirmMessage?: string;
};

export function HomeWalkingPill({
  title,
  subtitle,
  accentColor,
  backgroundColor,
  linkTo,
  dots,
  deleteAction,
  deleteLabel,
  deleteConfirmMessage = "abandon this trail? your progress will be lost",
}: Props) {
  const [isPending, startTransition] = useTransition();

  const handleDelete = (e: React.MouseEvent) => {
    e.preventDefault();
    e.stopPropagation();
    if (confirm(deleteConfirmMessage)) {
      startTransition(async () => {
        await deleteAction?.();
      });
    }
  };

  return (
    <div className="HomeWalkingPill-wrapper">
      <Card href={linkTo} accentColor={accentColor} backgroundColor={backgroundColor}>
        <div className="HomeWalkingPill">
          <h3 className="HomeWalkingPill-title">{title}</h3>
          <p className="HomeWalkingPill-subtitle">{subtitle}</p>
          <div className="HomeWalkingPill-progress">
            {dots.map((state, idx) => (
              <div key={idx} className="HomeWalkingPill-dotWrapper">
                <div className={`HomeWalkingPill-dot HomeWalkingPill-dot--${state}`} />
                {idx < dots.length - 1 && <div className="HomeWalkingPill-line" />}
              </div>
            ))}
          </div>
        </div>
      </Card>
      {deleteAction && (
        <button
          onClick={handleDelete}
          className={`HomeWalkingPill-deleteButton${isPending ? " HomeWalkingPill-deleteButton--pending" : ""}`}
          aria-label={deleteLabel}
          disabled={isPending}
        >
          ×
        </button>
      )}
    </div>
  );
}
