"use client";

import { useCallback, useEffect, useState } from "react";
import useAxios from "@/hooks/useAxios";
import { useUser } from "@/hooks/useUser";
import { Course, IAdvertising, IShopProductListing, Project } from "@/types/types";
import type { PostLinkKind } from "@/lib/postLinkCaption";
import { cn } from "@/lib/utils";
import BoldIcon from "@/components/ui/BoldIcon";
import { useTranslation } from "react-i18next";

type MyShop = { _id: string; name: string };

export type PickedStoryLink = {
  link_kind: PostLinkKind;
  link_id: string;
  link_title: string;
};

type Item = { kind: PostLinkKind; _id: string; title: string; icon: string };

// پیکر مستقل و سبک برای انتخاب یه آیتم و انداختنش روی استوری به‌عنوان اورلی قابل‌جابجایی —
// عمداً جدا از PostLinkPicker.tsx نگه داشته شده (نه ریفکتور اون) تا پیکر پست که همین الان
// درست کار می‌کنه، دست‌نخورده بمونه؛ چندتا فراخوانی فچ مشابه تکرار شده، معامله‌ی قابل‌قبولیه
export default function StoryLinkPicker({
  onSelect,
  onClose,
}: {
  onSelect: (item: PickedStoryLink) => void;
  onClose: () => void;
}) {
  const { t } = useTranslation("common");
  const { request } = useAxios();
  const user = useUser();
  const [items, setItems] = useState<Item[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    const collected: Item[] = [];

    try {
      const res = await request<{ data?: { courses?: Course[] }; courses?: Course[] }>(
        "GET",
        "/academy/academy/get/course?page=1&limit=100",
        null,
        { noToast: true }
      );
      const list = res?.data?.courses ?? res?.courses ?? [];
      list.forEach((c) => {
        const id = String(c._id || c.id || "");
        if (id) collected.push({ kind: "pkg", _id: id, title: c.cuorse_name || t("posts.defaultPackageTitle"), icon: "teacher" });
      });
    } catch {
      /* ignore */
    }

    try {
      if (user?._id) {
        const res = await request<{ data?: { projects?: Project[] }; projects?: Project[] }>(
          "GET",
          `/projects/user-projects?user_id=${user._id}&page=1&limit=100&linkable=1`,
          null,
          { noToast: true }
        );
        const list = res?.data?.projects ?? res?.projects ?? [];
        list.forEach((p) => {
          if (p._id) collected.push({ kind: "project", _id: String(p._id), title: p.title || t("posts.defaultProjectTitle"), icon: "briefcase" });
        });
      }
    } catch {
      /* ignore */
    }

    try {
      const res = await request<{ advertisings?: IAdvertising[]; data?: { advertisings?: IAdvertising[] } }>(
        "GET",
        "/advertising/user-advertising?page=1&limit=100",
        null,
        { noToast: true }
      );
      const list = res?.advertisings ?? res?.data?.advertisings ?? [];
      list.forEach((b) => {
        if (b._id) collected.push({ kind: "billboard", _id: String(b._id), title: b.title || t("posts.defaultBillboardTitle"), icon: "flash-circle" });
      });
    } catch {
      /* ignore */
    }

    try {
      const res = await request<{ shops?: MyShop[] }>("GET", "/shops/mine", null, { noToast: true });
      const shops = Array.isArray(res?.shops) ? res.shops : [];
      for (const shop of shops) {
        collected.push({ kind: "shop", _id: shop._id, title: shop.name, icon: "shop" });
        try {
          const productsRes = await request<{ docs?: IShopProductListing[] }>(
            "GET",
            `/shop-products?shopId=${shop._id}&limit=100`,
            null,
            { noToast: true }
          );
          (productsRes?.docs || []).forEach((p) => {
            collected.push({ kind: "shopproduct", _id: String(p._id), title: p.title, icon: "box" });
          });
        } catch {
          /* ignore */
        }
      }
    } catch {
      /* ignore */
    }

    try {
      if (user?._id) {
        const res = await request<{ config?: { name: string } }>(
          "GET",
          `/bookings/public/${user._id}`,
          null,
          { noToast: true }
        );
        if (res?.config) {
          collected.push({
            kind: "booking",
            _id: String(user._id),
            title: res.config.name || t("posts.defaultBookingTitle"),
            icon: "calendar",
          });
        }
      }
    } catch {
      /* ignore */
    }

    setItems(collected);
    setLoading(false);
  }, [request, user?._id, t]);

  useEffect(() => {
    void load();
  }, [load]);

  return (
    <div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/60" onClick={onClose}>
      <div
        className="max-h-[70vh] w-full max-w-md overflow-y-auto rounded-t-3xl bg-white p-4 dark:bg-neutral-900"
        onClick={(e) => e.stopPropagation()}
      >
        <p className="mb-3 text-center text-sm font-semibold text-neutral-700 dark:text-neutral-200">
          {t("stories.attachLink")}
        </p>
        {loading ? (
          <p className="py-6 text-center text-xs text-neutral-400">{t("common.loading")}</p>
        ) : items.length === 0 ? (
          <p className="py-6 text-center text-xs text-neutral-400">{t("stories.noLinkableItems")}</p>
        ) : (
          <ul className="space-y-1.5">
            {items.map((item) => (
              <li key={`${item.kind}-${item._id}`}>
                <button
                  type="button"
                  onClick={() =>
                    onSelect({ link_kind: item.kind, link_id: item._id, link_title: item.title })
                  }
                  className={cn(
                    "flex w-full items-center gap-2.5 rounded-lg px-2 py-2 text-right transition",
                    "hover:bg-neutral-100 dark:hover:bg-neutral-800"
                  )}
                >
                  <BoldIcon name={item.icon} size={18} className="dark:invert" />
                  <span className="min-w-0 flex-1 truncate text-sm font-semibold">{item.title}</span>
                </button>
              </li>
            ))}
          </ul>
        )}
      </div>
    </div>
  );
}
