"use client";

import { useState } from "react";
import Link from "next/link";
import { RankIcon1st } from "./RankIcon1st";
import { RankIcon2nd } from "./RankIcon2nd";
import { RankIcon3rd } from "./RankIcon3rd";
import { UserAvatar } from "./UserAvatar";
import { ImagePlaceholderIcon } from "./ImagePlaceholderIcon";
import { PostList } from "./PostList";
import { GradeIcon } from "./GradeIcon";

type BoardMeta = {
  id: string;
  name: string;
  slug: string;
  mainTypeKey?: string;
};

type UserData = {
  userId: string;
  nickname: string | null;
  points: number;
  profileImage: string | null;
  grade: number;
};

type PostData = {
  id: string;
  title: string;
  createdAt: Date;
  content?: string | null;
  attachments?: { url: string }[];
  stat?: { recommendCount: number | null; commentsCount: number | null };
};

type BoardPanelData = {
  board: BoardMeta;
  categoryName: string;
  siblingBoards: BoardMeta[];
  specialRankUsers?: UserData[];
  previewPosts?: PostData[];
  textPosts?: PostData[];
};

export function BoardPanelClient({ 
  initialBoardId, 
  boardsData 
}: { 
  initialBoardId: string; 
  boardsData: BoardPanelData[];
}) {
  const [selectedBoardId, setSelectedBoardId] = useState(initialBoardId);
  
  // 선택된 게시판 데이터 찾기
  const selectedBoardData = boardsData.find(bd => bd.board.id === selectedBoardId) || boardsData[0];
  const { board, categoryName, siblingBoards } = selectedBoardData;

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

  function stripHtml(html: string | null | undefined): string {
    if (!html) return "";
    // HTML 태그 제거
    return html.replace(/<[^>]*>/g, "").trim();
  }

  function extractImageFromContent(content: string | null | undefined): string | null {
    if (!content) return null;
    // img 태그에서 src 속성 추출
    const imgMatch = content.match(/<img[^>]+src=["']([^"']+)["'][^>]*>/i);
    if (imgMatch && imgMatch[1]) {
      return imgMatch[1];
    }
    // figure 안의 img 태그도 확인
    const figureMatch = content.match(/<figure[^>]*>[\s\S]*?<img[^>]+src=["']([^"']+)["'][^>]*>/i);
    if (figureMatch && figureMatch[1]) {
      return figureMatch[1];
    }
    return null;
  }

  const isTextMain = board.mainTypeKey === "main_text";
  const isSpecialRank = board.mainTypeKey === "main_special_rank";
  const isPreview = board.mainTypeKey === "main_preview";

  // 특수 랭킹 타입 렌더링
  if (isSpecialRank && selectedBoardData.specialRankUsers) {
    return (
      <div className="h-full min-h-0 flex flex-col">
        <div className="content-stretch flex gap-[30px] items-start w-full mb-2">
          <div className="flex items-center gap-[8px] shrink-0">
            <div className="text-[30px] text-[#5c5c5c] leading-[30px]">{categoryName || board.name}</div>
          </div>
          <div className="flex items-center gap-[8px] overflow-x-auto flex-nowrap min-w-0 flex-1 no-scrollbar">
            {siblingBoards.map((sb) => (
              <button
                key={sb.id}
                onClick={() => setSelectedBoardId(sb.id)}
                className={`px-[16px] py-[8px] rounded-[14px] text-[14px] shrink-0 cursor-pointer ${
                  sb.id === selectedBoardId ? "bg-[#5c5c5c] text-white border border-[#5c5c5c]" : "bg-white text-[#5c5c5c] border border-[#d5d5d5]"
                }`}
              >
                {sb.name}
              </button>
            ))}
          </div>
        </div>
        <div className="rounded-xl overflow-hidden h-full min-h-0 flex flex-col">
          <div className="flex-1 min-h-0 overflow-hidden p-0">
            <div className="px-[0px] pt-[8px] pb-[16px]">
              <div className="flex flex-col gap-[16px]">
                {selectedBoardData.specialRankUsers.map((user, idx) => {
                  const rank = idx + 1;
                  return (
                    <Link href="/boards/ranking" key={user.userId} className="flex h-[150px] items-center rounded-[16px] overflow-hidden bg-white hover:bg-neutral-50">
                      <div className="h-[150px] w-[160px] relative shrink-0 bg-[#d5d5d5] overflow-hidden">
                        <UserAvatar 
                          src={user.profileImage} 
                          alt={user.nickname || "프로필"} 
                          width={160}
                          height={150}
                          className="w-full h-full object-cover rounded-none"
                        />
                        <div className="absolute top-0 right-0 w-[40px] h-[40px] flex items-center justify-center">
                          <GradeIcon grade={user.grade} width={40} height={40} />
                        </div>
                      </div>
                      <div className="flex-1 flex items-center gap-[10px] px-[24px] md:px-[30px] py-[24px] min-w-0">
                        <div className="flex flex-col gap-[12px] min-w-0 flex-1">
                          <div className="flex items-center gap-[12px]">
                            <div className="relative w-[20px] h-[20px] shrink-0">
                              {rank === 1 && <RankIcon1st />}
                              {rank === 2 && <RankIcon2nd />}
                              {rank === 3 && <RankIcon3rd />}
                            </div>
                            <div className="bg-white border border-[#d5d5d5] px-[16px] py-[5px] rounded-[12px] text-[14px] text-[#5c5c5c] shrink-0">
                              {rank}위
                            </div>
                          </div>
                          <div className="text-[24px] font-medium text-[#5c5c5c] truncate leading-[22px]">
                            {user.nickname || "익명"}
                          </div>
                        </div>
                        <div className="h-[24px] flex items-center gap-[4px] shrink-0">
                          <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" className="shrink-0">
                            <path d="M8.17377 0.0481988C8.1834 0.0326271 8.19596 0.0201252 8.21037 0.0117499C8.22478 0.00337451 8.24062 -0.000628204 8.25656 7.99922e-05C8.2725 0.000788189 8.28806 0.0061865 8.30194 0.0158187C8.31582 0.0254509 8.3276 0.0390338 8.33629 0.0554196L11.3323 5.55973C11.3575 5.60512 11.4038 5.62472 11.4468 5.60718L15.8683 3.80198C15.9441 3.77104 16.0174 3.85666 15.9963 3.95053L14.2584 16H1.74226L0.00344328 3.95156C-0.00125237 3.93019 -0.0011435 3.90765 0.00375838 3.88635C0.00866025 3.86505 0.0181727 3.84576 0.0312889 3.83054C0.0444051 3.81532 0.0606369 3.80472 0.0782661 3.79988C0.0958953 3.79503 0.114266 3.79612 0.131434 3.80302L4.55889 5.61131C4.59846 5.62678 4.64309 5.61131 4.66835 5.57005L8.17461 0.0481988H8.17377Z" fill="#FFB625"/>
                          </svg>
                          <span className="text-[20px] font-semibold text-[#5c5c5c] leading-[22px]">{user.points.toLocaleString()}</span>
                        </div>
                      </div>
                    </Link>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // 미리보기 타입 렌더링
  if (isPreview && selectedBoardData.previewPosts) {
    return (
      <div className="h-full min-h-0 flex flex-col">
        <div className="content-stretch flex gap-[30px] items-start w-full mb-2">
          <div className="flex items-center gap-[8px] shrink-0">
            <div className="text-[30px] text-[#5c5c5c] leading-[30px]">{categoryName || board.name}</div>
          </div>
          <div className="flex items-center gap-[8px] overflow-x-auto flex-nowrap min-w-0 flex-1 no-scrollbar">
            {siblingBoards.map((sb) => (
              <button
                key={sb.id}
                onClick={() => setSelectedBoardId(sb.id)}
                className={`px-[16px] py-[8px] rounded-[14px] text-[14px] shrink-0 cursor-pointer ${
                  sb.id === selectedBoardId ? "bg-[#5c5c5c] text-white border border-[#5c5c5c]" : "bg-white text-[#5c5c5c] border border-[#d5d5d5]"
                }`}
              >
                {sb.name}
              </button>
            ))}
          </div>
        </div>
        <div className="rounded-xl overflow-hidden h-full min-h-0 flex flex-col">
          <div className="flex-1 min-h-0 overflow-hidden p-0">
            <div className="px-[0px] pt-[8px] pb-[16px]">
              <div className="flex flex-col gap-[16px]">
                {selectedBoardData.previewPosts.map((post) => {
                  // attachments에서 이미지를 먼저 찾고, 없으면 content에서 추출
                  const firstImage = post.attachments?.[0]?.url || extractImageFromContent(post.content);
                  return (
                    <Link key={post.id} href={`/posts/${post.id}`} className="flex h-[150px] items-start rounded-[16px] overflow-hidden bg-white">
                      <div className="h-[150px] w-[214px] relative shrink-0 bg-[#ededed] overflow-hidden">
                        {firstImage ? (
                          <img
                            src={firstImage}
                            alt={stripHtml(post.title)}
                            className="w-full h-full object-cover"
                          />
                        ) : (
                          <div className="absolute left-1/2 top-1/2 translate-x-[-50%] translate-y-[-50%] flex items-center justify-center">
                            <ImagePlaceholderIcon width={32} height={32} />
                          </div>
                        )}
                      </div>
                      <div className="flex-1 flex items-center gap-[10px] px-[24px] md:px-[30px] py-[24px] min-w-0">
                        <div className="flex flex-col gap-[12px] min-w-0 flex-1">
                          <div className="bg-white border border-[#d5d5d5] px-[16px] py-[5px] rounded-[12px] text-[14px] text-[#5c5c5c] shrink-0 w-fit">
                            {board.name}
                          </div>
                          <div className="flex items-center gap-[4px] overflow-hidden">
                            <div className="relative w-[16px] h-[16px] shrink-0">
                              <div className="absolute inset-0 rounded-full bg-[#f45f00] opacity-0" />
                              <div className="absolute inset-0 flex items-center justify-center text-[10px] text-white font-extrabold select-none">n</div>
                            </div>
                            <span className="text-[16px] leading-[22px] text-[#5c5c5c] truncate">{stripHtml(post.title)}</span>
                            {(post.stat?.commentsCount ?? 0) > 0 && (
                              <span className="ml-1 text-[14px] text-[#f45f00] font-bold shrink-0">[{post.stat?.commentsCount}]</span>
                            )}
                          </div>
                          <div className="h-[16px] relative">
                            <span className="absolute top-1/2 translate-y-[-50%] text-[12px] leading-[12px] tracking-[-0.24px] text-[#8c8c8c]">
                              {formatDateYmd(post.createdAt)}
                            </span>
                          </div>
                        </div>
                      </div>
                    </Link>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // 텍스트 메인 타입 또는 기본 타입 렌더링
  return (
    <div className="h-full min-h-0 flex flex-col">
      <div className="content-stretch flex gap-[30px] items-start w-full mb-2">
        <div className="flex items-center gap-[8px] shrink-0">
          <div className="text-[30px] text-[#5c5c5c] leading-[30px]">{categoryName || board.name}</div>
        </div>
        <div className="flex items-center gap-[8px] overflow-x-auto flex-nowrap min-w-0 flex-1 no-scrollbar">
          {siblingBoards.map((sb) => (
            <button
              key={sb.id}
              onClick={() => setSelectedBoardId(sb.id)}
              className={`px-[16px] py-[8px] rounded-[14px] text-[14px] shrink-0 cursor-pointer ${
                sb.id === selectedBoardId ? "bg-[#5c5c5c] text-white border border-[#5c5c5c]" : "bg-white text-[#5c5c5c] border border-[#d5d5d5]"
              }`}
            >
              {sb.name}
            </button>
          ))}
        </div>
      </div>
      <div className="rounded-xl overflow-hidden h-full min-h-0 flex flex-col bg-white">
        <div className="px-3 py-2 border-b border-neutral-200 flex items-center justify-between">
          <Link href={`/boards/${board.slug}`} className="text-lg md:text-xl font-bold text-neutral-800 truncate">{board.name}</Link>
          <Link href={`/boards/${board.slug}`} className="text-xs px-3 py-1 rounded-full border border-neutral-300 text-neutral-700 hover:bg-neutral-100">더보기</Link>
        </div>
        <div className="flex-1 min-h-0 overflow-hidden p-0">
          {isTextMain && selectedBoardData.textPosts ? (
            <div className="bg-white px-[24px] pt-[8px] pb-[16px]">
              <ul className="min-h-[326px]">
                {selectedBoardData.textPosts.map((p) => (
                  <li key={p.id} className="border-b border-[#ededed] h-[56px] pl-0 pr-[24px] pt-[16px] pb-[16px]">
                    <div className="flex items-center justify-between w-full">
                      <Link href={`/posts/${p.id}`} className="flex items-center gap-[4px] h-[24px] overflow-hidden flex-1 min-w-0">
                        <div className="relative w-[16px] h-[16px] shrink-0">
                          <div className="absolute inset-0 rounded-full bg-[#f45f00] opacity-0" />
                          <div className="absolute inset-0 flex items-center justify-center text-[10px] text-white font-extrabold select-none">n</div>
                        </div>
                        <span className="text-[16px] leading-[22px] text-[#5c5c5c] truncate max-w-[calc(100vw-280px)]">{stripHtml(p.title)}</span>
                        {(p.stat?.commentsCount ?? 0) > 0 && (
                          <span className="text-[14px] text-[#f45f00] font-bold">[{p.stat?.commentsCount}]</span>
                        )}
                      </Link>
                      <span className="text-[12px] leading-[12px] tracking-[-0.24px] text-[#8c8c8c]">{formatDateYmd(p.createdAt)}</span>
                    </div>
                  </li>
                ))}
              </ul>
            </div>
          ) : (
            <PostList key={board.id} boardId={board.id} sort="recent" />
          )}
        </div>
      </div>
    </div>
  );
}

