import { HeroBanner } from "@/app/components/HeroBanner";
import PartnerCategorySection from "@/app/components/PartnerCategorySection";
import Link from "next/link";
import HorizontalCardScroller from "@/app/components/HorizontalCardScroller";
import { PostList } from "@/app/components/PostList";
import ProfileLabelIcon from "@/app/svgs/profilelableicon";
import SearchIcon from "@/app/svgs/SearchIcon";
import { RankIcon1st } from "@/app/components/RankIcon1st";
import { RankIcon2nd } from "@/app/components/RankIcon2nd";
import { RankIcon3rd } from "@/app/components/RankIcon3rd";
import { UserAvatar } from "@/app/components/UserAvatar";
import { ImagePlaceholderIcon } from "@/app/components/ImagePlaceholderIcon";
import { BoardPanelClient } from "@/app/components/BoardPanelClient";
import { GradeIcon, getGradeName } from "@/app/components/GradeIcon";
import prisma from "@/lib/prisma";
import { headers } from "next/headers";

export default async function Home({ searchParams }: { searchParams: Promise<{ sort?: "recent" | "popular" } | undefined> }) {
  const sp = await searchParams;
  const sort = sp?.sort ?? "recent";

  // 로그인된 사용자 정보 가져오기 (기본값: 어드민)
  let currentUser: {
    userId: string;
    nickname: string;
    profileImage: string | null;
    points: number;
    level: number;
    grade: number;
  } | null = null;
  
  try {
    const h = await headers();
    const cookieHeader = h.get("cookie") || "";
    const uid = cookieHeader
      .split(";")
      .map((s) => s.trim())
      .find((pair) => pair.startsWith("uid="))
      ?.split("=")[1];
    
    if (uid) {
      const user = await prisma.user.findUnique({
        where: { userId: decodeURIComponent(uid) },
        select: { userId: true, nickname: true, profileImage: true, points: true, level: true, grade: true },
      });
      if (user) currentUser = user;
    }
  } catch (e) {
    // 에러 무시
  }
  
  // 로그인되지 않은 경우 어드민 사용자 가져오기
  if (!currentUser) {
    const admin = await prisma.user.findUnique({
      where: { nickname: "admin" },
      select: { userId: true, nickname: true, profileImage: true, points: true, level: true, grade: true },
    });
    if (admin) currentUser = admin;
  }

  // 내가 쓴 게시글/댓글 수
  let myPostsCount = 0;
  let myCommentsCount = 0;
  if (currentUser) {
    myPostsCount = await prisma.post.count({ where: { authorId: currentUser.userId, status: "published" } });
    myCommentsCount = await prisma.comment.count({ where: { authorId: currentUser.userId } });
  }

  // 메인페이지 설정 불러오기
  const SETTINGS_KEY = "mainpage_settings" as const;
  const settingRow = await prisma.setting.findUnique({ where: { key: SETTINGS_KEY } });
  const parsed = settingRow ? JSON.parse(settingRow.value as string) : {};
  const showBanner: boolean = parsed.showBanner ?? true;
  const showPartnerShops: boolean = parsed.showPartnerShops ?? true;
  const visibleBoardIds: string[] = Array.isArray(parsed.visibleBoardIds) ? parsed.visibleBoardIds : [];

  // 보드 메타데이터 (메인뷰 타입 포함)
  const boardsMeta = visibleBoardIds.length
    ? await prisma.board.findMany({
        where: { id: { in: visibleBoardIds } },
        select: {
          id: true,
          name: true,
          slug: true,
          category: { select: { id: true, name: true } },
          mainPageViewType: { select: { key: true } },
        },
      })
    : [];
  const idToMeta = new Map(
    boardsMeta.map((b) => [
      b.id,
      {
        id: b.id,
        name: b.name,
        slug: b.slug,
        categoryId: b.category?.id ?? null,
        categoryName: b.category?.name ?? "",
        mainTypeKey: b.mainPageViewType?.key,
      },
    ] as const)
  );
  const orderedBoards = visibleBoardIds
    .map((id) => idToMeta.get(id))
    .filter((v): v is any => Boolean(v));
  const firstTwo = orderedBoards.slice(0, 2);
  const restBoards = orderedBoards.slice(2);

  function formatDateYmd(d: Date) {
    const yyyy = d.getFullYear();
    const mm = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");
    return `${yyyy}.${mm}.${dd}`;
  }

  // 게시판 패널 데이터 수집 함수 (모든 sibling boards 포함)
  const prepareBoardPanelData = async (board: { id: string; name: string; slug: string; categoryId: string | null; categoryName: string; mainTypeKey?: string }) => {
    // 같은 카테고리의 소분류(게시판) 탭 목록
    const siblingBoards = board.categoryId
      ? await prisma.board.findMany({
          where: { categoryId: board.categoryId },
          select: { id: true, name: true, slug: true, mainPageViewType: { select: { key: true } } },
          orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
        })
      : [];

    const boardsData = [];
    
    for (const sb of siblingBoards) {
      const isTextMain = sb.mainPageViewType?.key === "main_text";
      const isSpecialRank = sb.mainPageViewType?.key === "main_special_rank";
      const isPreview = sb.mainPageViewType?.key === "main_preview";

      const boardMeta = {
        id: sb.id,
        name: sb.name,
        slug: sb.slug,
        mainTypeKey: sb.mainPageViewType?.key,
      };

      let specialRankUsers;
      let previewPosts;
      let textPosts;

      if (isSpecialRank) {
        specialRankUsers = await prisma.user.findMany({
          select: { userId: true, nickname: true, points: true, profileImage: true, grade: true },
          where: { status: "active" },
          orderBy: { points: "desc" },
          take: 6,
        });
      } else if (isPreview) {
        previewPosts = await prisma.post.findMany({
          where: { boardId: sb.id, status: "published" },
          select: {
            id: true,
            title: true,
            createdAt: true,
            content: true,
            attachments: {
              where: { type: "image" },
              orderBy: { sortOrder: "asc" },
              take: 1,
              select: { url: true },
            },
            stat: { select: { commentsCount: true } },
          },
          orderBy: { createdAt: "desc" },
          take: 6,
        });
      } else if (isTextMain) {
        textPosts = await prisma.post.findMany({
          where: { boardId: sb.id, status: "published" },
          select: { id: true, title: true, createdAt: true, stat: { select: { recommendCount: true, commentsCount: true } } },
          orderBy: { createdAt: "desc" },
          take: 16,
        });
      }
      // 기본 타입은 PostList가 자체적으로 API를 호출하므로 데이터 미리 가져오지 않음

      boardsData.push({
        board: boardMeta,
        categoryName: board.categoryName || board.name,
        siblingBoards: siblingBoards.map(sb => ({
          id: sb.id,
          name: sb.name,
          slug: sb.slug,
          mainTypeKey: sb.mainPageViewType?.key,
        })),
        specialRankUsers,
        previewPosts,
        textPosts,
      });
    }

    return { initialBoardId: board.id, boardsData };
  };

  return (
    <div className="space-y-8">
      {/* 히어로 섹션: 상단 대형 비주얼 영역 (설정 온오프) */}
      {showBanner && (
        <section>
          <HeroBanner />
        </section>
      )}

      {/* 배너 아래: 파트너 카테고리 탭 + 파트너 리스트 */}
      <PartnerCategorySection />

      {/* 제휴 샾 가로 스크롤 (설정 온오프, DB에서 불러오기)
         - 우선 partners 테이블(관리자 페이지 관리 대상) 사용
         - 없으면 partner_shops로 대체 */}
      {showPartnerShops && (async () => {
        // 우선순위: partners(관리자 관리) → partner_shops(폴백)
        let partners: any[] = [];
        try {
          partners = await (prisma as any).partner.findMany({ orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }], take: 10 });
        } catch (_) {
          partners = await prisma.partner.findMany({ orderBy: { createdAt: "desc" }, take: 10 });
        }
        const items = partners.map((p: any) => ({
          id: p.id,
          region: p.address ? String(p.address).split(" ")[0] : p.category,
          name: p.name,
          address: p.address || "",
          image: p.imageUrl || "/sample.jpg",
        }));
        if (items.length > 0) return <HorizontalCardScroller items={items} />;

        const shops = await (prisma as any).partnerShop.findMany({ where: { active: true }, orderBy: [{ sortOrder: "asc" }, { createdAt: "desc" }] });
        const shopItems = shops.map((s: any) => ({ id: s.id, region: s.region, name: s.name, address: s.address, image: s.imageUrl }));
        return <HorizontalCardScroller items={shopItems} />;
      })()}

      {/* 1행: 프로필 + 선택된 보드 2개 (최대 2개) */}
      {(firstTwo.length > 0) && (
        <section className="min-h-[395px] overflow-hidden">
          <div className="grid grid-cols-1 md:grid-cols-2 xl:flex xl:gap-[23px] gap-4 h-full min-h-0">
            <div className="hidden xl:grid relative overflow-hidden rounded-xl bg-white px-[25px] py-[34px] grid-rows-[120px_120px_1fr] gap-y-[32px] h-[514px] w-[350px] shrink-0">
              <div className="absolute inset-x-0 top-0 h-[56px] bg-[#d5d5d5] z-0" />
              <div className="h-[120px] flex items-center justify-center relative z-10">
                <div className="flex items-center justify-center gap-[8px]">
                  <UserAvatar 
                    src={currentUser?.profileImage || null}
                    alt={currentUser?.nickname || "프로필"}
                    width={120}
                    height={120}
                    className="rounded-full"
                  />
                  {currentUser && (
                    <div className="w-[62px] h-[62px] flex items-center justify-center">
                      <GradeIcon grade={currentUser.grade} width={62} height={62} />
                    </div>
                  )}
                </div>
              </div>
              <div className="h-[120px] flex flex-col items-center relative z-10">
                <div className="text-[18px] text-[#5c5c5c] font-[700] truncate text-center mb-[20px]">{currentUser?.nickname || "사용자"}</div>
                <div className="w-[300px] pl-[67px] flex flex-col gap-[12px]">
                  <div className="grid grid-cols-[64px_auto] gap-x-[24px] items-center h-[16px]">
                    <div className="w-[64px] flex items-center">
                      <ProfileLabelIcon width={16} height={16} />
                      <span className="ml-[8px] text-[12px] text-[#8c8c8c] font-[700]">레벨</span>
                    </div>
                    <div className="text-[16px] text-[#5c5c5c] font-[700]">Lv. {currentUser?.level || 1}</div>
                  </div>
                  <div className="grid grid-cols-[64px_auto] gap-x-[24px] items-center h-[16px]">
                    <div className="w-[64px] flex items-center">
                      <ProfileLabelIcon width={16} height={16} />
                      <span className="ml-[8px] text-[12px] text-[#8c8c8c] font-[700]">등급</span>
                    </div>
                    <div className="text-[16px] text-[#5c5c5c] font-[700]">{getGradeName(currentUser?.grade || 0)}</div>
                  </div>
                  <div className="grid grid-cols-[64px_auto] gap-x-[24px] items-center h-[16px]">
                    <div className="w-[64px] flex items-center">
                      <ProfileLabelIcon width={16} height={16} />
                      <span className="ml-[8px] text-[12px] text-[#8c8c8c] font-[700]">포인트</span>
                    </div>
                    <div className="text-[16px] text-[#5c5c5c] font-[700]">{(currentUser?.points || 0).toLocaleString()}</div>
                  </div>
                </div>
              </div>
              <div className="flex flex-col gap-[12px] relative z-10">
                <Link href="/my-page" className="w-[300px] h-[32px] rounded-full bg-[#8c8c8c] hover:bg-[#5c5c5c] text-white text-[12px] font-[700] flex items-center px-[12px]">
                  <span className="flex items-center w-full pl-[88px]">
                    <span className="flex items-center gap-[8px]">
                      <SearchIcon width={16} height={16} />
                      <span>내 정보 페이지</span>
                    </span>
                  </span>
                </Link>
                <Link href="/my-page?tab=points" className="w-[300px] h-[32px] rounded-full bg-[#8c8c8c] hover:bg-[#5c5c5c] text-white text-[12px] font-[700] flex items-center px-[12px]">
                  <span className="flex items-center w-full pl-[88px]">
                    <span className="flex items-center gap-[8px]">
                      <SearchIcon width={16} height={16} />
                      <span>포인트 히스토리</span>
                    </span>
                  </span>
                </Link>
                <Link href={`/my-page?tab=posts`} className="w-[300px] h-[32px] rounded-full bg-[#8c8c8c] hover:bg-[#5c5c5c] text-white text-[12px] font-[700] flex items-center px-[12px]">
                  <span className="flex items-center w-full pl-[88px]">
                    <span className="flex items-center gap-[8px]">
                      <SearchIcon width={16} height={16} />
                      <span>내가 쓴 게시글</span>
                    </span>
                    <span className="ml-auto inline-flex items-center justify-center h-[20px] px-[8px] rounded-full bg-white text-[#5c5c5c] text-[12px] leading-[20px] shrink-0">{myPostsCount.toLocaleString()}개</span>
                  </span>
                </Link>
                <Link href={`/my-page?tab=comments`} className="w-[300px] h-[32px] rounded-full bg-[#8c8c8c] hover:bg-[#5c5c5c] text-white text-[12px] font-[700] flex items-center px-[12px]">
                  <span className="flex items-center w-full pl-[88px]">
                    <span className="flex items-center gap-[8px]">
                      <SearchIcon width={16} height={16} />
                      <span>내가 쓴 댓글</span>
                    </span>
                    <span className="ml-auto inline-flex items-center justify-center h-[20px] px-[8px] rounded-full bg-white text-[#5c5c5c] text-[12px] leading-[20px] shrink-0">{myCommentsCount.toLocaleString()}개</span>
                  </span>
                </Link>
              </div>
            </div>
            {(await Promise.all(firstTwo.map((b) => prepareBoardPanelData(b)))).map((panelData, idx) => (
              <div key={firstTwo[idx].id} className="overflow-hidden xl:h-[514px] h-full min-h-0 flex flex-col flex-1">
                <BoardPanelClient initialBoardId={panelData.initialBoardId} boardsData={panelData.boardsData} />
              </div>
            ))}
          </div>
        </section>
      )}

      {/* 나머지 보드: 2개씩 다음 열로 렌더링 */}
      {restBoards.length > 0 && (
        <>
          {Array.from({ length: Math.ceil(restBoards.length / 2) }).map(async (_, i) => {
            const pair = restBoards.slice(i * 2, i * 2 + 2);
            return (
              <section key={`rest-${i}`} className="min-h-[395px] md:h-[540px] overflow-hidden">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4 h-full min-h-0">
                  {(await Promise.all(pair.map((b) => prepareBoardPanelData(b)))).map((panelData, idx) => (
                    <div key={pair[idx].id} className="overflow-hidden h-full min-h-0 flex flex-col">
                      <BoardPanelClient initialBoardId={panelData.initialBoardId} boardsData={panelData.boardsData} />
                    </div>
                  ))}
                </div>
              </section>
            );
          })}
        </>
      )}
    </div>
  );
}
