import { Boxes, ExternalLink, FolderKanban, Layers3, Plus, Tags } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";

import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { MotionFade } from "@/components/motion-fade";
import { FlashMessage } from "@/components/root/flash-message";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import {
  getAdminPortfolioCategories,
  getAdminPortfolioProjects,
  getLocalizedValue,
} from "@/lib/portfolio";
import { getLocalizedPath } from "@/lib/locale";

export const dynamic = "force-dynamic";

const copy = {
  title: "Portfolio",
  subtitle: "Verwaltung fuer Kategorien, Projekte und Inhalte.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  siteSettings: "SEO",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
  totalCategories: "Kategorien",
  totalProjects: "Projekte",
  publishedProjects: "Veroeffentlicht",
  newProject: "Neues Projekt",
  newCategory: "Neue Kategorie",
  category: "Kategorie",
  all: "Alle",
  status: "Status",
  draft: "Entwurf",
  published: "Veroeffentlicht",
  filter: "Filtern",
  sort: "Sortierung",
  previewSet: "Preview Link gesetzt",
  previewMissing: "Kein Preview Link",
  editProject: "Projekt bearbeiten",
  openProject: "Projekt ansehen",
  empty: "Keine Projekte fuer die aktuellen Filter gefunden.",
};

type RootPortfolioPageProps = {
  searchParams?: {
    category?: string;
    status?: "all" | "draft" | "published";
    success?: string;
    error?: string;
  };
};

export default async function RootPortfolioPage({ searchParams }: RootPortfolioPageProps) {
  if (!isAdminAuthenticated()) {
    redirect("/root");
  }

  async function logoutAction() {
    "use server";

    clearAdminSessionCookie();
    redirect("/root");
  }

  const selectedStatus = searchParams?.status === "draft" || searchParams?.status === "published"
    ? searchParams.status
    : "all";
  const [categories, projects] = await Promise.all([
    getAdminPortfolioCategories(),
    getAdminPortfolioProjects({
      categoryId: searchParams?.category || undefined,
      status: selectedStatus,
    }),
  ]);
  const publishedProjects = projects.filter((project) => project.isPublished).length;

  return (
    <RootDashboardShell
      copy={copy}
      active="portfolio"
      portfolioChild="overview"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
      headerActions={
        <div className="flex flex-wrap gap-3">
          <Button asChild>
            <Link href="/root/portfolio/projects/new">
              <Plus className="h-4 w-4" />
              {copy.newProject}
            </Link>
          </Button>
          <Button asChild variant="outline">
            <Link href="/root/portfolio/categories">
              <Tags className="h-4 w-4" />
              {copy.newCategory}
            </Link>
          </Button>
        </div>
      }
    >
      <div className="space-y-6">
        {searchParams?.success ? (
          <MotionFade delay={0.08}>
            <FlashMessage type="success" message={searchParams.success} />
          </MotionFade>
        ) : null}

        {searchParams?.error ? (
          <MotionFade delay={0.1}>
            <FlashMessage type="error" message={searchParams.error} />
          </MotionFade>
        ) : null}

        <section className="grid gap-4 md:grid-cols-3">
          {[
            {
              icon: Layers3,
              label: copy.totalCategories,
              value: categories.length,
            },
            {
              icon: FolderKanban,
              label: copy.totalProjects,
              value: projects.length,
            },
            {
              icon: Boxes,
              label: copy.publishedProjects,
              value: publishedProjects,
            },
          ].map((item, index) => {
            const Icon = item.icon;

            return (
              <MotionFade key={item.label} delay={index * 0.05}>
                <AppCard level={2}>
                  <CardContent className="flex items-center gap-4 p-6">
                    <div className="flex h-12 w-12 items-center justify-center rounded-pill bg-surface-1">
                      <Icon className="h-5 w-5 text-brand-primary" />
                    </div>
                    <div>
                      <p className="text-sm text-muted-foreground">{item.label}</p>
                      <p className="text-3xl font-semibold text-foreground">{item.value}</p>
                    </div>
                  </CardContent>
                </AppCard>
              </MotionFade>
            );
          })}
        </section>

        <MotionFade delay={0.15}>
          <AppCard>
            <CardContent className="p-6">
              <form className="grid gap-4 md:grid-cols-3">
                <div className="space-y-2">
                  <label htmlFor="category" className="text-sm font-medium text-foreground">
                    {copy.category}
                  </label>
                  <select
                    id="category"
                    name="category"
                    defaultValue={searchParams?.category ?? ""}
                    className="flex h-11 w-full rounded-pill border border-border bg-background px-4 text-sm text-foreground shadow-sm"
                  >
                    <option value="">{copy.all}</option>
                    {categories.map((category) => (
                      <option key={category.id} value={category.id}>
                        {category.name.de}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="space-y-2">
                  <label htmlFor="status" className="text-sm font-medium text-foreground">
                    {copy.status}
                  </label>
                  <select
                    id="status"
                    name="status"
                    defaultValue={selectedStatus}
                    className="flex h-11 w-full rounded-pill border border-border bg-background px-4 text-sm text-foreground shadow-sm"
                  >
                    <option value="all">{copy.all}</option>
                    <option value="draft">{copy.draft}</option>
                    <option value="published">{copy.published}</option>
                  </select>
                </div>

                <div className="flex items-end">
                  <Button type="submit" variant="outline">
                    {copy.filter}
                  </Button>
                </div>
              </form>
            </CardContent>
          </AppCard>
        </MotionFade>

        <div className="grid gap-4">
          {projects.map((project, index) => (
            <MotionFade key={project.id} delay={0.18 + index * 0.03}>
              <AppCard interactive>
                <CardHeader className="flex flex-row items-center justify-between gap-4">
                  <div>
                    <CardTitle>{getLocalizedValue(project.title, "de")}</CardTitle>
                    <p className="mt-1 text-sm text-muted-foreground">
                      {project.category.name.de}
                    </p>
                  </div>
                  <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
                    <span className="rounded-pill border border-border px-3 py-1">
                      {project.isPublished ? copy.published : copy.draft}
                    </span>
                    <span className="rounded-pill border border-border px-3 py-1">
                      {project.projectYear}
                    </span>
                    <span className="rounded-pill border border-border px-3 py-1">
                      {copy.sort} {project.sortOrder}
                    </span>
                  </div>
                </CardHeader>
                <CardContent className="flex flex-wrap items-center justify-between gap-4">
                  <div className="space-y-1 text-sm text-muted-foreground">
                    <p>{project.slug}</p>
                    <p>{project.previewUrl ? copy.previewSet : copy.previewMissing}</p>
                  </div>
                  <div className="flex flex-wrap gap-3">
                    <Button asChild variant="outline">
                      <Link
                        href={getLocalizedPath("de", `/portfolio/${project.slug}`)}
                        target="_blank"
                        rel="noreferrer"
                      >
                        <ExternalLink className="h-4 w-4" />
                        {copy.openProject}
                      </Link>
                    </Button>
                    <Button asChild>
                      <Link href={`/root/portfolio/projects/${project.id}`}>{copy.editProject}</Link>
                    </Button>
                  </div>
                </CardContent>
              </AppCard>
            </MotionFade>
          ))}

          {projects.length === 0 ? (
            <MotionFade delay={0.18}>
              <AppCard>
                <CardContent className="p-6 text-sm text-muted-foreground">
                  {copy.empty}
                </CardContent>
              </AppCard>
            </MotionFade>
          ) : null}
        </div>
      </div>
    </RootDashboardShell>
  );
}
