"use client";

import Image from "next/image";
import { useRouter } from "next/navigation";

import { Card, Icon, IconName, Typography } from "@/components/ui";
import { PartnerPortrait } from "@/entities/dashboard/types";
import { useGenerationStatus } from "@/hooks/generations/useGenerationStatus";

import styles from "./PortraitCard.module.scss";

type PortraitCardProps = PartnerPortrait;

const HeartCheckIcon = () => (
  <svg
    width="15"
    height="15"
    viewBox="0 0 15 15"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
  >
    <g clipPath="url(#clip0_2443_1886)">
      <path
        d="M1.78594 8.96384L6.72695 13.5767C6.93203 13.7681 7.20273 13.8748 7.48438 13.8748C7.76602 13.8748 8.03672 13.7681 8.2418 13.5767L13.1828 8.96384C14.0141 8.19001 14.4844 7.10447 14.4844 5.9697V5.81111C14.4844 3.89978 13.1035 2.27009 11.2195 1.95564C9.97266 1.74783 8.70391 2.15525 7.8125 3.04666L7.48438 3.37478L7.15625 3.04666C6.26484 2.15525 4.99609 1.74783 3.74922 1.95564C1.86523 2.27009 0.484375 3.89978 0.484375 5.81111V5.9697C0.484375 7.10447 0.954687 8.19001 1.78594 8.96384Z"
        fill="#16A34A"
      />
    </g>
    <defs>
      <clipPath id="clip0_2443_1886">
        <path d="M0.484375 0.75H14.4844V14.75H0.484375V0.75Z" fill="white" />
      </clipPath>
    </defs>
  </svg>
);

const getStatusConfig = (status: PartnerPortrait["status"]) => {
  switch (status) {
    case "done":
      return {
        icon: <HeartCheckIcon />,
        text: "Ready",
        showCheckmark: true,
        className: styles.statusDone,
      };
    case "processing":
      return {
        icon: (
          <Icon
            name={IconName.Loader}
            className={styles.iconProcessing}
            size={{ width: 16, height: 16 }}
          />
        ),
        text: "Processing...",
        showCheckmark: false,
        className: styles.statusProcessing,
      };
    case "queued":
      return {
        icon: (
          <Icon
            name={IconName.Clock}
            className={styles.iconQueued}
            size={{ width: 16, height: 16 }}
          />
        ),
        text: "In Queue",
        showCheckmark: false,
        className: styles.statusQueued,
      };
    case "error":
      return {
        icon: (
          <Icon
            name={IconName.AlertCircle}
            className={styles.iconError}
            size={{ width: 16, height: 16 }}
          />
        ),
        text: "Error",
        showCheckmark: false,
        className: styles.statusError,
      };
  }
};

export default function PortraitCard({
  _id,
  title,
  status: initialStatus,
  imageUrl: initialImageUrl,
}: PortraitCardProps) {
  const router = useRouter();

  // Use polling hook to update status in real-time
  const { status, imageUrl: polledImageUrl } = useGenerationStatus(
    _id,
    initialStatus
  );

  // Use polled imageUrl if available, otherwise use initial
  const imageUrl = polledImageUrl || initialImageUrl;

  const statusConfig = getStatusConfig(status as PartnerPortrait["status"]);
  const isReady = status === "done" && imageUrl;

  const handleClick = () => {
    if (isReady) {
      router.push(`/portraits/${_id}`);
    }
  };

  return (
    <Card
      className={`${styles.card} ${!isReady ? styles.disabled : ""}`}
      onClick={handleClick}
      style={{ cursor: isReady ? "pointer" : "default" }}
    >
      <div className={styles.imageContainer}>
        {imageUrl ? (
          <Image
            className={styles.portraitImage}
            src={imageUrl}
            alt={title}
            fill
            sizes="(max-width: 768px) 100vw, 300px"
            style={{ objectFit: "cover" }}
          />
        ) : (
          <div className={styles.placeholderImage}>
            <Icon
              name={IconName.Loader}
              className={styles.placeholderLoader}
              size={{ width: 48, height: 48 }}
            />
          </div>
        )}
      </div>

      <div className={styles.content}>
        <div className={styles.textContent}>
          <Typography
            as="h3"
            size="lg"
            weight="semiBold"
            align="left"
            className={styles.title}
          >
            {title}
          </Typography>
          <Typography
            size="sm"
            color="secondary"
            align="left"
            className={styles.subtitle}
          >
            Finding the One Guide
          </Typography>
        </div>

        <div className={styles.footer}>
          <div className={`${styles.status} ${statusConfig.className}`}>
            {statusConfig.icon}
            <Typography size="sm" weight="medium" className={styles.statusText}>
              {statusConfig.text}
            </Typography>
            {statusConfig.showCheckmark && (
              <Icon
                name={IconName.Check}
                className={styles.checkmark}
                size={{ width: 14, height: 14 }}
              />
            )}
          </div>

          {status === "done" && (
            <button className={styles.actionButton} aria-label="View portrait">
              <Icon
                name={IconName.ChevronRight}
                size={{ width: 20, height: 20 }}
                color="white"
              />
            </button>
          )}
        </div>
      </div>
    </Card>
  );
}
