"use client";

import type { TenantRecommendationFeed } from "../adapters/tenant-recommendations";
import type { AdapterResult } from "../types";
import { CommercialEmptyState } from "./CommercialEmptyState";
import { commercialEntityName, recommendationReason } from "../presentation";

function RecList({
  title,
  items,
  kind,
}: {
  title: string;
  items?: Array<{ code: string; score?: number; reason?: string; kind?: string }>;
  kind: string;
}) {
  if (!items?.length) return null;
  return (
    <div>
      <p className="text-xs font-semibold text-gray-500">{title}</p>
      <ul className="mt-2 space-y-1">
        {items.map((i) => (
          <li
            key={`${title}-${i.code}`}
            className="rounded-lg border border-gray-100 bg-white px-3 py-2 text-sm"
          >
            <span className="font-semibold text-secondary">
              {commercialEntityName(i.kind || kind, i.code)}
            </span>
            {typeof i.score === "number" ? (
              <span className="ms-2 rounded-full bg-sky-50 px-2 py-0.5 text-[10px] text-primary">
                پیشنهاد متناسب
              </span>
            ) : null}
            <p className="mt-1 text-xs text-gray-500">{recommendationReason(i.reason)}</p>
          </li>
        ))}
      </ul>
    </div>
  );
}

export function RecommendationsPanel({
  result,
}: {
  result: AdapterResult<TenantRecommendationFeed> | null;
}) {
  if (!result || result.availability !== "ready") {
    return (
      <CommercialEmptyState
        title="پیشنهادها"
        description="با پاسخ به چند سؤال کوتاه، پیشنهادهای مناسب کسب‌وکار شما اینجا نمایش داده می‌شود."
      />
    );
  }
  const d = result.data;
  return (
    <div className="grid gap-5 lg:grid-cols-3">
      <RecList title="ضروری" kind="products" items={d.recommended_products?.slice(0, 3)} />
      <RecList
        title="پیشنهادی"
        kind="bundles"
        items={[
          ...(d.recommended_bundles || []).map((item) => ({ ...item, kind: "bundles" })),
          ...(d.recommended_services || []).map((item) => ({ ...item, kind: "products" })),
        ].slice(0, 4)}
      />
      <RecList
        title="بعداً اضافه کنید"
        kind="products"
        items={[
          ...(d.recommended_upgrades || []).map((item) => ({ ...item, kind: "products" })),
          ...(d.recommended_automation_packs || []).map((item) => ({ ...item, kind: "automation-packs" })),
          ...(d.recommended_extensions || []).map((item) => ({ ...item, kind: "extensions" })),
        ].slice(0, 4)}
      />
    </div>
  );
}
