"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import {
  FilePlus2,
  Trash2,
  Eye,
  Pencil,
  ListChecks,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

interface ProjectListItem {
  id: string;
  title: string;
  slug: string;
  status: string;
  createdAt: string;
  updatedAt: string;
}

export default function ProjectsPage() {
  const router = useRouter();
  const [projects, setProjects] = useState<ProjectListItem[]>([]);
  const [status, setStatus] = useState<"idle" | "loading" | "error">("idle");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [selectedSlugs, setSelectedSlugs] = useState<string[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 10;

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      try {
        setStatus("loading");
        setErrorMessage(null);

        const res = await fetch("/api/projects");
        if (!res.ok) {
          if (!cancelled) {
            setStatus("error");

            if (res.status === 401) {
              setErrorMessage("프로젝트 목록을 불러오는 중 인증 오류가 발생했습니다. 다시 로그인해 주세요.");
              router.push("/login");
            } else {
              setErrorMessage(
                "프로젝트 목록을 불러오는 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.",
              );
            }
          }
          return;
        }

        const data = (await res.json()) as ProjectListItem[];
        if (!cancelled) {
          setProjects(Array.isArray(data) ? data : []);
          setStatus("idle");
          setErrorMessage(null);
        }
      } catch {
        if (!cancelled) {
          setStatus("error");
          setErrorMessage("프로젝트 목록을 불러오는 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
        }
      }
    };

    void load();

    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    const totalPages = Math.max(1, Math.ceil(projects.length / pageSize));
    setCurrentPage((prev) => Math.min(prev, totalPages));
  }, [projects.length, pageSize]);

  const handleDelete = async (slug: string) => {
    if (typeof window !== "undefined") {
      const confirmed = window.confirm(
        "이 프로젝트를 삭제할까요? 삭제 후에는 되돌릴 수 없습니다. (로컬 저장 및 자동저장 데이터도 함께 삭제됩니다.)",
      );

      if (!confirmed) return;
    }

    try {
      const res = await fetch(`/api/projects/${encodeURIComponent(slug)}`, {
        method: "DELETE",
      });

      if (!res.ok) {
        setStatus("error");
        setErrorMessage("프로젝트 삭제 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
        return;
      }

      setProjects((prev) => prev.filter((p) => p.slug !== slug));
      setSelectedSlugs((prev) => prev.filter((s) => s !== slug));

      if (typeof window !== "undefined") {
        window.localStorage.removeItem(`pb:project:${slug}`);
        window.localStorage.removeItem(`pb:autosave:${slug}`);
      }

      setStatus("idle");
      setErrorMessage(null);
    } catch {
      setStatus("error");
      setErrorMessage("프로젝트 삭제 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
    }
  };

  const handleLogout = async () => {
    try {
      const res = await fetch("/api/auth/logout", {
        method: "POST",
      });

      if (!res.ok) {
        setStatus("error");
        setErrorMessage("로그아웃 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
        return;
      }

      router.push("/login");
    } catch {
      setStatus("error");
      setErrorMessage("로그아웃 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
    }
  };

  const totalCount = projects.length;
  const totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
  const startIndex = (currentPage - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pageProjects = projects.slice(startIndex, endIndex);

  const handleBulkDelete = async () => {
    const slugs = selectedSlugs;
    if (slugs.length === 0) return;

    if (typeof window !== "undefined") {
      const confirmed = window.confirm(
        "선택한 프로젝트를 모두 삭제할까요? 삭제 후에는 되돌릴 수 없습니다. (로컬 저장 및 자동저장 데이터도 함께 삭제됩니다.)",
      );
      if (!confirmed) return;
    }

    try {
      const results = await Promise.all(
        slugs.map(async (slug) => {
          const res = await fetch(`/api/projects/${encodeURIComponent(slug)}`, { method: "DELETE" });
          return { slug, ok: res.ok };
        }),
      );

      const okSlugs = results.filter((r) => r.ok).map((r) => r.slug);

      if (okSlugs.length === 0) {
        setStatus("error");
        setErrorMessage("선택한 프로젝트를 삭제하는 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
        return;
      }

      setProjects((prev) => prev.filter((p) => !okSlugs.includes(p.slug)));
      setSelectedSlugs((prev) => prev.filter((s) => !okSlugs.includes(s)));

      if (typeof window !== "undefined") {
        for (const slug of okSlugs) {
          window.localStorage.removeItem(`pb:project:${slug}`);
          window.localStorage.removeItem(`pb:autosave:${slug}`);
        }
      }

      if (okSlugs.length !== slugs.length) {
        setStatus("error");
        setErrorMessage(
          "일부 프로젝트 삭제에 실패했습니다. 페이지를 새로고침한 뒤 목록을 확인해 주세요.",
        );
      } else {
        setStatus("idle");
        setErrorMessage(null);
      }
    } catch {
      setStatus("error");
      setErrorMessage("선택한 프로젝트를 삭제하는 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
    }
  };

  return (
    <main className="min-h-screen flex flex-col bg-slate-950 text-slate-50">
      <header className="border-b border-slate-800 px-6 py-4 flex items-center justify-between bg-slate-950/80 backdrop-blur">
        <div>
          <h1 className="text-xl font-semibold">프로젝트 목록</h1>
          <p className="text-xs text-slate-400">저장된 프로젝트들을 한 눈에 볼 수 있는 목록</p>
        </div>
        <div className="flex items-center gap-2 text-xs">
          <button
            type="button"
            className="inline-flex items-center gap-1 rounded border border-slate-700 px-3 py-1 text-slate-200 hover:bg-slate-900"
            onClick={() => {
              void handleLogout();
            }}
          >
            로그아웃
          </button>
          <Link
            href="/editor"
            className="inline-flex items-center gap-1 rounded border border-sky-700 bg-sky-950 px-3 py-1 text-sky-100 hover:bg-sky-900 shadow-sm"
          >
            <FilePlus2 className="w-4 h-4" aria-hidden="true" />
            <span>새 프로젝트 만들기</span>
          </Link>
        </div>
      </header>
      <section className="flex-1 px-6 py-4 overflow-auto">
        {status === "error" && (
          <p className="text-xs text-red-300 mb-3">
            {errorMessage ?? "프로젝트 목록을 불러오는 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요."}
          </p>
        )}
        {projects.length === 0 && status === "idle" && (
          <p className="text-xs text-slate-400">아직 저장된 프로젝트가 없습니다. 에디터에서 프로젝트를 저장해 보세요.</p>
        )}
        {projects.length > 0 && (
          <>
            <div className="flex items-center justify-between mb-2 text-[11px] text-slate-300">
              <div className="inline-flex items-center gap-2">
                <span className="inline-flex items-center gap-1 px-2 py-1 rounded-full bg-slate-900/70 border border-slate-700">
                  <ListChecks className="w-3 h-3 text-slate-400" aria-hidden="true" />
                  <span>
                    선택된 프로젝트: <span className="font-semibold">{selectedSlugs.length}</span>개
                  </span>
                </span>
              </div>
              <button
                type="button"
                className="inline-flex items-center gap-1 rounded border border-red-700 px-2 py-1 text-red-200 hover:bg-red-900/40 disabled:opacity-40 disabled:cursor-not-allowed"
                disabled={selectedSlugs.length === 0}
                onClick={() => {
                  void handleBulkDelete();
                }}
              >
                <Trash2 className="w-3 h-3" aria-hidden="true" />
                <span>선택 삭제</span>
              </button>
            </div>
            <table className="w-full text-xs text-left border-collapse mt-2">
              <thead>
                <tr className="border-b border-slate-800 text-slate-400">
                  <th className="py-2 pr-2 w-8">
                    <input
                      type="checkbox"
                      className="h-3 w-3 rounded border-slate-700 bg-slate-900 align-middle"
                      aria-label="전체 선택"
                      checked={
                        pageProjects.length > 0 && pageProjects.every((p) => selectedSlugs.includes(p.slug))
                      }
                      onChange={(e) => {
                        if (e.target.checked) {
                          const slugsOnPage = pageProjects.map((p) => p.slug);
                          setSelectedSlugs((prev) => Array.from(new Set([...prev, ...slugsOnPage])));
                        } else {
                          const slugsOnPage = pageProjects.map((p) => p.slug);
                          setSelectedSlugs((prev) => prev.filter((s) => !slugsOnPage.includes(s)));
                        }
                      }}
                    />
                  </th>
                  <th className="py-2 pr-4">제목</th>
                  <th className="py-2 pr-4">주소(slug)</th>
                  <th className="py-2 pr-4">상태</th>
                  <th className="py-2 pr-4">생성일</th>
                  <th className="py-2 pr-4">수정일</th>
                  <th className="py-2 pr-4 text-right">액션</th>
                </tr>
              </thead>
              <tbody>
                {pageProjects.map((project) => {
                  const checked = selectedSlugs.includes(project.slug);
                  return (
                    <tr key={project.id} className="border-b border-slate-900 hover:bg-slate-900/60">
                      <td className="py-2 pr-2 w-8">
                        <input
                          type="checkbox"
                          className="h-3 w-3 rounded border-slate-700 bg-slate-900 align-middle"
                          aria-label={`${project.title} 선택`}
                          checked={checked}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setSelectedSlugs((prev) =>
                                prev.includes(project.slug) ? prev : [...prev, project.slug],
                              );
                            } else {
                              setSelectedSlugs((prev) => prev.filter((s) => s !== project.slug));
                            }
                          }}
                        />
                      </td>
                      <td className="py-2 pr-4 text-slate-100">{project.title}</td>
                      <td className="py-2 pr-4 text-slate-300 font-mono text-[11px]">{project.slug}</td>
                      <td className="py-2 pr-4 text-slate-300">{project.status}</td>
                      <td className="py-2 pr-4 text-slate-500 text-[11px]">
                        {new Date(project.createdAt).toLocaleString()}
                      </td>
                      <td className="py-2 pr-4 text-slate-500 text-[11px]">
                        {new Date(project.updatedAt).toLocaleString()}
                      </td>
                      <td className="py-2 pl-4 pr-0 text-right text-[11px]">
                        <div className="inline-flex items-center gap-2">
                          <Link
                            href={`/editor?slug=${encodeURIComponent(project.slug)}`}
                            className="inline-flex items-center gap-1 text-sky-300 hover:text-sky-200 underline-offset-2 hover:underline"
                          >
                            <Pencil className="w-3 h-3" aria-hidden="true" />
                            <span>편집</span>
                          </Link>
                          <Link
                            href={`/preview?slug=${encodeURIComponent(project.slug)}`}
                            className="inline-flex items-center gap-1 text-slate-300 hover:text-slate-100 underline-offset-2 hover:underline"
                          >
                            <Eye className="w-3 h-3" aria-hidden="true" />
                            <span>미리보기</span>
                          </Link>
                          <button
                            type="button"
                            className="inline-flex items-center gap-1 text-red-300 hover:text-red-200 underline-offset-2 hover:underline"
                            onClick={() => {
                              void handleDelete(project.slug);
                            }}
                          >
                            <Trash2 className="w-3 h-3" aria-hidden="true" />
                            <span>삭제</span>
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>

            <div className="mt-3 flex items-center justify-between text-[11px] text-slate-300">
              <div className="inline-flex items-center gap-2">
                <span className="px-2 py-1 rounded-full bg-slate-900/70 border border-slate-700">
                  전체 {totalCount}개 중{" "}
                  <span className="font-semibold">
                    {totalCount === 0 ? 0 : startIndex + 1}–{Math.min(endIndex, totalCount)}
                  </span>
                </span>
              </div>
              <div className="flex items-center gap-1">
                {Array.from({ length: totalPages }).map((_, idx) => {
                  const page = idx + 1;
                  const isActive = page === currentPage;
                  return (
                    <button
                      key={page}
                      type="button"
                      onClick={() => setCurrentPage(page)}
                      className={`w-6 h-6 rounded-full text-[10px] flex items-center justify-center border transition-colors ${
                        isActive
                          ? "bg-sky-600 text-white border-sky-500 shadow-sm"
                          : "bg-slate-900 text-slate-300 border-slate-700 hover:bg-slate-800"
                      }`}
                    >
                      {page}
                    </button>
                  );
                })}
              </div>
              <div className="flex items-center gap-1">
                <button
                  type="button"
                  disabled={currentPage === 1}
                  className="inline-flex items-center gap-1 px-2 py-1 rounded border border-slate-700 text-slate-300 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-slate-800"
                  onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                >
                  <ChevronLeft className="w-3 h-3" aria-hidden="true" />
                  <span>이전</span>
                </button>
                <button
                  type="button"
                  disabled={currentPage === totalPages}
                  className="inline-flex items-center gap-1 px-2 py-1 rounded border border-slate-700 text-slate-300 disabled:opacity-40 disabled:cursor-not-allowed hover:bg-slate-800"
                  onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                >
                  <span>다음</span>
                  <ChevronRight className="w-3 h-3" aria-hidden="true" />
                </button>
              </div>
            </div>
          </>
        )}
      </section>
    </main>
  );
}
