/* eslint-disable @next/next/no-img-element */

import { ExternalLink, FileType2, ImageIcon, Link2, Tag, Trash2, Upload } from "lucide-react";
import Link from "next/link";
import { redirect } from "next/navigation";

import { MotionFade } from "@/components/motion-fade";
import { FlashMessage } from "@/components/root/flash-message";
import { RootDashboardShell } from "@/components/root/root-dashboard-shell";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { clearAdminSessionCookie, isAdminAuthenticated } from "@/lib/admin-auth";
import { getAdminMediaAssets } from "@/lib/media";

import { createMediaAssetAction, deleteMediaAssetAction } from "./actions";

export const dynamic = "force-dynamic";

const copy = {
  title: "Media Library",
  subtitle: "Zentrale Dateien fuer Portfolio und spaetere Inhaltsbereiche.",
  overview: "Uebersicht",
  maintenance: "Wartungsmodus",
  uiKit: "UI Kit",
  media: "Media",
  siteSettings: "SEO",
  portfolio: "Portfolio",
  logout: "Ausloggen",
  backToSite: "Zur Website",
  createTitle: "Neue Datei",
  createDescription: "Datei hochladen oder externe URL zentral fuer spaetere Wiederverwendung speichern.",
  label: "Bezeichnung",
  kind: "Typ",
  uploadFile: "Datei hochladen",
  externalUrl: "Externe URL",
  saveMedia: "Datei speichern",
  open: "Oeffnen",
  delete: "Loeschen",
  usages: "Verwendungen",
  noAssets: "Noch keine Dateien vorhanden.",
};

type RootMediaPageProps = {
  searchParams?: {
    success?: string;
    error?: string;
  };
};

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

  async function logoutAction() {
    "use server";

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

  const mediaAssets = await getAdminMediaAssets();

  return (
    <RootDashboardShell
      copy={copy}
      active="media"
      logoutAction={logoutAction}
      headerTitle={copy.title}
      headerDescription={copy.subtitle}
    >
      <div className="space-y-6">
        {searchParams?.success ? (
          <MotionFade delay={0.1}>
            <FlashMessage type="success" message={searchParams.success} />
          </MotionFade>
        ) : null}

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

        <MotionFade delay={0.15}>
          <AppCard>
            <CardHeader>
              <CardTitle>{copy.createTitle}</CardTitle>
              <CardDescription>{copy.createDescription}</CardDescription>
            </CardHeader>
            <CardContent>
              <form action={createMediaAssetAction} className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="label" className="sr-only">
                    {copy.label}
                  </Label>
                  <div className="relative">
                    <Tag className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Input id="label" name="label" required placeholder={copy.label} className="pl-9" />
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="kind" className="sr-only">
                    {copy.kind}
                  </Label>
                  <div className="relative">
                    <FileType2 className="pointer-events-none absolute left-3 top-1/2 z-10 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Select name="kind" defaultValue="IMAGE">
                      <SelectTrigger id="kind" className="pl-9">
                        <SelectValue placeholder={copy.kind} />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="IMAGE">IMAGE</SelectItem>
                        <SelectItem value="DOCUMENT">DOCUMENT</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="file" className="sr-only">
                    {copy.uploadFile}
                  </Label>
                  <div className="relative">
                    <Upload className="pointer-events-none absolute left-3 top-1/2 z-10 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Input id="file" name="file" type="file" accept="image/*,.svg,.pdf" className="pl-9 file:mr-3" />
                  </div>
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="externalUrl" className="sr-only">
                    {copy.externalUrl}
                  </Label>
                  <div className="relative">
                    <Link2 className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                    <Input id="externalUrl" name="externalUrl" placeholder={copy.externalUrl} className="pl-9" />
                  </div>
                </div>

                <div className="md:col-span-2">
                  <Button type="submit">
                    <ImageIcon className="h-4 w-4" />
                    {copy.saveMedia}
                  </Button>
                </div>
              </form>
            </CardContent>
          </AppCard>
        </MotionFade>

        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {mediaAssets.map((asset, index) => (
            <MotionFade key={asset.id} delay={0.18 + index * 0.04}>
              <AppCard>
                <CardHeader>
                  <CardTitle className="text-base">{asset.label}</CardTitle>
                  <CardDescription className="flex flex-wrap gap-2">
                    <span>{asset.kind}</span>
                    <span>{asset.source}</span>
                    <span>{asset.usages.length} {copy.usages}</span>
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-4">
                  {asset.kind === "IMAGE" ? (
                    <div className="overflow-hidden rounded-nested border bg-card">
                      <img src={asset.url} alt={asset.label} className="h-48 w-full object-cover" />
                    </div>
                  ) : (
                    <div className="rounded-nested border bg-card px-4 py-6 text-sm text-muted-foreground">
                      {asset.fileName}
                    </div>
                  )}

                  <div className="space-y-2 text-sm text-muted-foreground">
                    <p className="truncate">{asset.url}</p>
                    <div className="flex flex-wrap gap-3">
                      <Link href={asset.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-2 text-foreground">
                        <ExternalLink className="h-4 w-4" />
                        {copy.open}
                      </Link>
                    </div>
                  </div>

                  {asset.usages.length > 0 ? (
                    <div className="space-y-2 rounded-nested border bg-muted/40 px-4 py-3 text-xs text-muted-foreground">
                      {asset.usages.map((usage) => (
                        <p key={usage.id}>
                          {usage.usageType} / {usage.entityType} / {usage.fieldKey}
                        </p>
                      ))}
                    </div>
                  ) : null}

                  <form action={deleteMediaAssetAction}>
                    <input type="hidden" name="assetId" value={asset.id} />
                    <Button type="submit" variant="destructive" disabled={asset.usages.length > 0}>
                      <Trash2 className="h-4 w-4" />
                      {copy.delete}
                    </Button>
                  </form>
                </CardContent>
              </AppCard>
            </MotionFade>
          ))}
        </div>

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