"use client";

import Image from "next/image";
import { Button, Card, CardBody } from "@heroui/react";
import { buttonStyles } from "@/lib/buttonStyles";
import { useApp } from "@/contexts/AppContext";

const COLOR_KEYS = ["orange", "green", "blue", "purple", "red", "teal", "indigo", "rose", "amber", "cyan"] as const;
type ColorKey = typeof COLOR_KEYS[number];

const COLOR_MAP: Record<ColorKey, { iconBg: string; text: string; border: string }> = {
  orange:  { iconBg: "bg-orange-50 dark:bg-orange-900/20",  text: "text-orange-600",  border: "border-orange-300" },
  green:   { iconBg: "bg-green-50 dark:bg-green-900/20",    text: "text-green-600",   border: "border-green-300" },
  blue:    { iconBg: "bg-blue-50 dark:bg-blue-900/20",      text: "text-blue-600",    border: "border-blue-300" },
  purple:  { iconBg: "bg-purple-50 dark:bg-purple-900/20",  text: "text-purple-600",  border: "border-purple-300" },
  red:     { iconBg: "bg-red-50 dark:bg-red-900/20",        text: "text-red-600",     border: "border-red-300" },
  teal:    { iconBg: "bg-teal-50 dark:bg-teal-900/20",      text: "text-teal-600",    border: "border-teal-300" },
  indigo:  { iconBg: "bg-indigo-50 dark:bg-indigo-900/20",  text: "text-indigo-600",  border: "border-indigo-300" },
  rose:    { iconBg: "bg-rose-50 dark:bg-rose-900/20",      text: "text-rose-600",    border: "border-rose-300" },
  amber:   { iconBg: "bg-amber-50 dark:bg-amber-900/20",    text: "text-amber-600",   border: "border-amber-300" },
  cyan:    { iconBg: "bg-cyan-50 dark:bg-cyan-900/20",      text: "text-cyan-600",    border: "border-cyan-300" },
};

function resolveColor(categoryColor: string, productId: number) {
  if ((COLOR_KEYS as readonly string[]).includes(categoryColor)) {
    return COLOR_MAP[categoryColor as ColorKey];
  }
  return COLOR_MAP[COLOR_KEYS[productId % COLOR_KEYS.length]];
}

interface ProductCardListProps {
  productId: number;
  name: string;
  category: string;
  categoryColor: string;
  iconUrl: string;
  poolCap: string;
  lockUp: string;
  poolCapacityPercent: number;
  status?: 'active' | 'full' | 'ended';
  onInvest?: () => void;
}

export default function ProductCardList({
  productId,
  name,
  category,
  categoryColor,
  iconUrl,
  poolCap,
  lockUp,
  poolCapacityPercent,
  status,
  onInvest,
}: ProductCardListProps) {
  const { t } = useApp();
  const colors = resolveColor(categoryColor, productId);

  const statusCfg = status
    ? status === 'ended'
      ? { label: t("product.statusEnded"), dot: "bg-gray-400", bg: "bg-gray-100", border: "border-gray-300", text: "text-gray-500" }
      : status === 'full'
      ? { label: t("product.statusFull"), dot: "bg-orange-500", bg: "bg-orange-50", border: "border-orange-200", text: "text-orange-600" }
      : { label: t("product.statusActive"), dot: "bg-green-500", bg: "bg-green-50", border: "border-green-200", text: "text-green-600" }
    : null;

  const isSoldOut = status === 'full' && lockUp !== 'Matured';

  return (
    <Card className="bg-bg-subtle dark:bg-gray-800 border border-border-gray dark:border-gray-700 rounded-xl">
      <CardBody className="py-4 px-4 md:py-6 md:px-8">

        {/* ── 桌面端横向布局 ── */}
        <div className="hidden md:flex flex-row items-center justify-between">
          {/* Icon + Title */}
          <div className="flex flex-row gap-4 items-center w-[280px] flex-shrink-0">
            <div className={`${colors.iconBg} rounded-md border-[0.75px] border-black/10 dark:border-white/10 w-10 h-[30px] relative shadow-[inset_0_1.5px_3px_0_rgba(0,0,0,0.05)] overflow-hidden flex items-center justify-center flex-shrink-0`}>
              <Image
                src={iconUrl || "/assets/tokens/default.svg"}
                alt={name}
                width={43}
                height={30}
                className="w-[107.69%] h-full object-cover"
              />
            </div>
            <div className="flex flex-col gap-0.5 items-start min-w-0 flex-1">
              <div className="text-text-tertiary dark:text-gray-400 text-caption-tiny font-normal font-inter">
                {category}
              </div>
              <div className="flex items-center gap-2 w-full">
                <span className="text-text-primary dark:text-white text-body-default font-bold font-inter truncate">
                  {name}
                </span>
                {statusCfg && (
                  <div className={`inline-flex items-center gap-1 flex-shrink-0 rounded-full border px-2 py-0.5 ${statusCfg.bg} ${statusCfg.border}`}>
                    <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${statusCfg.dot}`} />
                    <span className={`text-[10px] font-semibold ${statusCfg.text}`}>{statusCfg.label}</span>
                  </div>
                )}
              </div>
            </div>
          </div>

          {/* Stats */}
          <div className="flex flex-row items-center justify-between flex-1 px-12">
            <div className="flex flex-col gap-1 items-start w-[120px] flex-shrink-0">
              <div className="text-text-tertiary dark:text-gray-400 text-caption-tiny font-normal font-inter">
                {t("productPage.lockUp")}
              </div>
              <div className="text-text-primary dark:text-white text-body-small font-bold font-inter">
                {lockUp || "--"}
              </div>
            </div>
            <div className="flex flex-col gap-1 items-start w-[100px] flex-shrink-0">
              <div className="text-text-tertiary dark:text-gray-400 text-caption-tiny font-normal font-inter">
                {t("productPage.poolCap")}
              </div>
              <div className="text-green-500 dark:text-green-400 text-body-small font-bold font-inter">
                {poolCap || "--"}
              </div>
            </div>
            <div className="flex flex-col gap-1 items-start w-[260px] flex-shrink-0">
              <div className="text-text-tertiary dark:text-gray-400 text-caption-tiny font-normal font-inter">
                {t("productPage.poolCapacity")}
              </div>
              <div className="flex flex-row gap-3 items-center">
                <div className="bg-gray-100 dark:bg-gray-700 rounded-full w-24 h-2 relative overflow-hidden flex-shrink-0">
                  <div
                    className="rounded-full h-2"
                    style={{
                      background: "linear-gradient(90deg, rgba(20, 71, 230, 1) 0%, rgba(3, 43, 189, 1) 100%)",
                      width: `${poolCapacityPercent}%`,
                    }}
                  />
                </div>
                <div className="text-text-primary dark:text-white text-body-small font-bold font-inter whitespace-nowrap">
                  {poolCapacityPercent.toFixed(4)}% {t("productPage.filled")}
                </div>
              </div>
            </div>
          </div>

          {/* Invest Button */}
          <div className="flex-shrink-0">
            <Button
              color="default"
              variant="solid"
              onPress={isSoldOut ? undefined : onInvest}
              isDisabled={isSoldOut}
              className={isSoldOut ? `${buttonStyles({ intent: "theme" })} !bg-[#E5E7EB] !text-[#9CA1AF] cursor-not-allowed` : buttonStyles({ intent: "theme" })}
            >
              {isSoldOut ? t("productPage.soldOut") : t("productPage.invest")}
            </Button>
          </div>
        </div>

        {/* ── 移动端竖向布局 ── */}
        <div className="flex md:hidden flex-col gap-3">
          {/* 第一行：Icon + 名称 + 状态 */}
          <div className="flex items-center gap-3">
            <div className={`${colors.iconBg} rounded-md border-[0.75px] border-black/10 dark:border-white/10 w-10 h-[30px] relative shadow-[inset_0_1.5px_3px_0_rgba(0,0,0,0.05)] overflow-hidden flex items-center justify-center flex-shrink-0`}>
              <Image
                src={iconUrl || "/assets/tokens/default.svg"}
                alt={name}
                width={43}
                height={30}
                className="w-[107.69%] h-full object-cover"
              />
            </div>
            <div className="flex-1 min-w-0">
              <div className="text-text-tertiary dark:text-gray-400 text-[11px] font-normal">{category}</div>
              <div className="text-text-primary dark:text-white text-sm font-bold truncate">{name}</div>
            </div>
            {statusCfg && (
              <div className={`inline-flex items-center gap-1 flex-shrink-0 rounded-full border px-2 py-0.5 ${statusCfg.bg} ${statusCfg.border}`}>
                <span className={`w-1.5 h-1.5 rounded-full flex-shrink-0 ${statusCfg.dot}`} />
                <span className={`text-[10px] font-semibold ${statusCfg.text}`}>{statusCfg.label}</span>
              </div>
            )}
          </div>

          {/* 第二行：Lock-up + Pool Cap */}
          <div className="grid grid-cols-2 gap-3">
            <div className="bg-white dark:bg-gray-700/50 rounded-lg px-3 py-2">
              <div className="text-text-tertiary dark:text-gray-400 text-[11px] mb-0.5">{t("productPage.lockUp")}</div>
              <div className="text-text-primary dark:text-white text-sm font-bold">{lockUp || "--"}</div>
            </div>
            <div className="bg-white dark:bg-gray-700/50 rounded-lg px-3 py-2">
              <div className="text-text-tertiary dark:text-gray-400 text-[11px] mb-0.5">{t("productPage.poolCap")}</div>
              <div className="text-green-500 dark:text-green-400 text-sm font-bold">{poolCap || "--"}</div>
            </div>
          </div>

          {/* 第三行：Pool Capacity 进度条 */}
          <div className="bg-white dark:bg-gray-700/50 rounded-lg px-3 py-2">
            <div className="flex items-center justify-between mb-1.5">
              <div className="text-text-tertiary dark:text-gray-400 text-[11px]">{t("productPage.poolCapacity")}</div>
              <div className="text-text-primary dark:text-white text-[11px] font-bold">
                {poolCapacityPercent.toFixed(2)}% {t("productPage.filled")}
              </div>
            </div>
            <div className="bg-gray-100 dark:bg-gray-600 rounded-full w-full h-1.5 overflow-hidden">
              <div
                className="rounded-full h-1.5"
                style={{
                  background: "linear-gradient(90deg, rgba(20, 71, 230, 1) 0%, rgba(3, 43, 189, 1) 100%)",
                  width: `${poolCapacityPercent}%`,
                }}
              />
            </div>
          </div>

          {/* 第四行：按钮 */}
          <Button
            color="default"
            variant="solid"
            onPress={isSoldOut ? undefined : onInvest}
            isDisabled={isSoldOut}
            className={`w-full ${isSoldOut ? `${buttonStyles({ intent: "theme" })} !bg-[#E5E7EB] !text-[#9CA1AF] cursor-not-allowed` : buttonStyles({ intent: "theme" })}`}
          >
            {isSoldOut ? t("productPage.soldOut") : t("productPage.invest")}
          </Button>
        </div>

      </CardBody>
    </Card>
  );
}
