import React from "react";
import { Button } from "../../button";
import { backgroundColorMap, SimpleCardProps } from "./types";

import { Link } from "@shared/components/link";
import { MaterialIcon } from "@shared/components/material-icon";
import { NextImage } from "@shared/components/next-image";
import { Text } from "@shared/components/text";
import { cx } from "@shared/utils";
import { SpeedCardBg } from "@shared/utils/speed-card-bg";

const ICON_SIZE = 60;

const alignmentClasses: Record<string, string> = {
  left: "flex w-full justify-start",
  right: "flex w-full justify-end",
  center: "flex w-full justify-center",
};

const justifyClass: Record<string, string> = {
  left: "justify-start",
  right: "justify-end",
  center: "justify-center",
};

const formatPhoneHref = (phone: string): string => {
  const digits = (phone || "").replace(/\D/g, "");
  return digits ? `tel:${digits}` : "";
};

export const SimpleCard: React.FC<SimpleCardProps> = ({
  card,
  lgWidth,
  mdWidth,
  className,
  contentClassName,
  style,
}) => {
  const view = card.imageView?.toLowerCase();
  const fullSizeImage = view === "full";
  const marginSizeImage = view === "margin";
  const standardSizeImage = view === "standard";
  const iconSizeImage =
    view === "icon" || view === "inset" || (!view && !!card.image);

  // Local @ui CalloutCard treats "standard" + "icon" as the new card design
  // that supports background color / pinwheel / inverted text via CSS vars.
  const hasNewDesign = standardSizeImage || iconSizeImage;

  const iconAlignment =
    card.iconAlignment?.toLowerCase() ||
    card.imageAlignment?.toLowerCase() ||
    "left";

  const ctaAlignmentClass =
    (card.ctaAlignment && alignmentClasses[card.ctaAlignment]) ||
    alignmentClasses.left;
  const ctaAlignmentBottomClass =
    (card.ctaAlignmentBottom && justifyClass[card.ctaAlignmentBottom]) ||
    justifyClass.left;

  const pinwheelColorCode = card.pinwheelColor?.split("-")[1];

  const useDynamicColors = hasNewDesign && card.applyCardBackgroundColor;

  const dynamicStyle: React.CSSProperties = {
    ...style,
    ...(useDynamicColors && card.backgroundColor
      ? ({ ["--scc-bg" as any]: card.backgroundColor } as React.CSSProperties)
      : {}),
    ...(useDynamicColors && card.textColor
      ? ({ ["--scc-fg" as any]: card.textColor } as React.CSSProperties)
      : {}),
    ...(useDynamicColors && card.backgroundColor
      ? { backgroundColor: "var(--scc-bg)" }
      : {}),
    ...(useDynamicColors && card.showBackgroundImage && pinwheelColorCode
      ? {
          backgroundImage: `url('data:image/svg+xml;utf8,${encodeURIComponent(
            SpeedCardBg(pinwheelColorCode)
          )}')`,
          backgroundPosition: "top left",
          backgroundSize: "684px 107px",
          backgroundRepeat: "no-repeat",
        }
      : {}),
  };

  const renderFullImage = (margin: boolean) => {
    if (!card.image) return null;
    return (
      <div
        className={cx(
          "relative aspect-video overflow-hidden",
          !margin ? "rounded-t-3xl" : "mx-6 lg:mx-8"
        )}
      >
        <NextImage
          src={card.image}
          alt={card.imageAlt ?? card.title ?? "card-image"}
          width={card.imageWidth || 400}
          height={card.imageHeight || 280}
          className={cx("w-full", !margin && "rounded-t-3xl")}
        />
      </div>
    );
  };

  const renderIcon = () => {
    if (!card.image) return null;
    const imgWidth = standardSizeImage
      ? card.imageWidth || ICON_SIZE
      : ICON_SIZE;
    const imgHeight = standardSizeImage
      ? card.imageHeight || ICON_SIZE
      : ICON_SIZE;
    return (
      <div
        className={cx(
          "relative mb-8 flex",
          card.imageToRichTextAlignment && "h-[60px] w-[60px] flex-shrink-0"
        )}
        style={{ justifyContent: iconAlignment }}
      >
        <NextImage
          src={card.image}
          alt={card.imageAlt ?? card.title ?? "card-icon"}
          width={imgWidth}
          height={imgHeight}
          className={cx(
            "object-contain",
            card.imageToRichTextAlignment && "!h-[60px] !w-[60px]"
          )}
        />
      </div>
    );
  };

  const textColorStyle =
    useDynamicColors && card.textColor ? { color: card.textColor } : undefined;

  const titleNode = card.title ? (
    <Text
      as="h3"
      className="heading6 mb-2 text-text md:heading6"
      style={textColorStyle}
    >
      {card.title}
    </Text>
  ) : null;

  const titleWithLink =
    card.cta?.href && titleNode ? (
      <Link
        href={card.cta.href}
        target={card.cta.target}
        className="no-underline hover:underline"
        style={textColorStyle}
      >
        {titleNode}
      </Link>
    ) : (
      titleNode
    );

  const hasTable =
    (card.workingHours?.length ?? 0) > 0 || (card.phoneNumber?.length ?? 0) > 0;

  return (
    <section
      className={cx(
        "callout-card relative flex h-full w-full flex-col rounded-3xl p-0",
        card.shadow && "shadow-card",
        card.image && !fullSizeImage && !card.showBackgroundImage && "pt-1",
        !card.applyCardBackgroundColor &&
          (backgroundColorMap[card.backgroundColor ?? ""] ?? ""),
        mdWidth,
        lgWidth,
        className
      )}
      style={dynamicStyle}
      aria-labelledby={card.title ? `callout-${card.title}` : undefined}
    >
      {/* Top "location" CTA */}
      {card.ctaBottom?.title && card.ctaBottom?.href ? (
        <div
          className={cx(
            "top-link m-6 flex items-center lg:m-8",
            ctaAlignmentBottomClass
          )}
        >
          <Link
            href={card.ctaBottom.href}
            className="label1 inline-flex items-center gap-2 text-text decoration-text underline-offset-4 hover:underline"
          >
            <MaterialIcon name="location_on" fill={1} size={24} />
            <span>{card.ctaBottom.title}</span>
          </Link>
        </div>
      ) : null}

      {card.image && fullSizeImage ? renderFullImage(false) : null}
      {card.image && marginSizeImage ? renderFullImage(true) : null}

      <div
        className={cx(
          "relative flex flex-1 flex-col justify-between px-6 pb-8 pt-7 lg:px-8 lg:py-8",
          contentClassName
        )}
      >
        <div className="flex flex-1 flex-col justify-between">
          <div
            className={cx(
              "flex flex-col",
              card.imageToRichTextAlignment &&
                "lg:flex-row lg:items-start lg:gap-6"
            )}
          >
            <div
              className={cx(card.imageToRichTextAlignment && "flex-shrink-0")}
            >
              {card.image && !fullSizeImage && !marginSizeImage
                ? renderIcon()
                : null}
            </div>
            <div className="flex flex-col gap-3 md:gap-4">
              {titleWithLink}

              {card.titleLocation ? (
                <div className="mb-1 lg:mb-2">
                  <Text as="h4" className="label1 font-bold text-text">
                    {card.titleLocation}
                  </Text>
                </div>
              ) : null}

              {hasTable ? (
                <div className="mb-2">
                  <table>
                    <tbody>
                      {card.workingHours?.map((hours, index) => {
                        const [label, value] = (hours ?? "").split("|");
                        return (
                          <tr key={`wh-${index}`}>
                            <td className="py-2 pr-3">
                              <Text className="label2 text-text">{label}</Text>
                            </td>
                            <td className="py-2 pl-3">
                              <Text className="body2 font-bold text-text">
                                {value}
                              </Text>
                            </td>
                          </tr>
                        );
                      })}
                      {card.phoneNumber?.map((phone, index) => (
                        <tr key={`ph-${index}`}>
                          <td className="py-1 pr-3 align-middle">
                            <MaterialIcon
                              fill={1}
                              name="call"
                              size={24}
                              weight="200"
                              className="text-text"
                            />
                          </td>
                          <td className="py-1 pl-3">
                            <Link
                              href={formatPhoneHref(phone)}
                              className="text-inherit no-underline"
                            >
                              <Text className="body2 font-bold text-text">
                                {phone}
                              </Text>
                            </Link>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              ) : null}

              {card.body ? (
                <Text
                  as="div"
                  className="body1 text-text"
                  style={textColorStyle}
                >
                  {card.body}
                </Text>
              ) : null}
              {card.richText ? (
                <Text
                  as="div"
                  className="body1 text-text"
                  style={textColorStyle}
                >
                  {card.richText}
                </Text>
              ) : null}
            </div>
          </div>
        </div>

        {card.cta ? (
          <div className={cx("mt-2", ctaAlignmentClass)}>
            <Button
              linkVariant="unstyled"
              linkClassName={cx(
                "label1 flex items-center gap-2 text-text",
                useDynamicColors && card.textColor && "decoration-current"
              )}
              {...card.cta}
              iconName={card.cta.iconName ?? "expand_circle_right"}
              iconFill={card.cta.iconFill ?? 1}
            />
          </div>
        ) : null}
      </div>
    </section>
  );
};

export default SimpleCard;
