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

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

import { MotionFade } from "@/components/motion-fade";
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 { 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",
  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}>
            <p className="rounded-nested border border-status-success/30 bg-status-success/10 px-4 py-3 text-sm text-status-success">
              {searchParams.success}
            </p>
          </MotionFade>
        ) : null}

        {searchParams?.error ? (
          <MotionFade delay={0.12}>
            <p className="rounded-nested border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
              {searchParams.error}
            </p>
          </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">{copy.label}</Label>
                  <Input id="label" name="label" required />
                </div>

                <div className="space-y-2">
                  <Label htmlFor="kind">{copy.kind}</Label>
                  <select
                    id="kind"
                    name="kind"
                    defaultValue="IMAGE"
                    className="flex h-11 w-full rounded-pill border border-border bg-background px-4 text-sm text-foreground shadow-sm"
                  >
                    <option value="IMAGE">IMAGE</option>
                    <option value="DOCUMENT">DOCUMENT</option>
                  </select>
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="file">{copy.uploadFile}</Label>
                  <Input id="file" name="file" type="file" accept="image/*,.svg,.pdf" />
                </div>

                <div className="space-y-2 md:col-span-2">
                  <Label htmlFor="externalUrl">{copy.externalUrl}</Label>
                  <Input id="externalUrl" name="externalUrl" placeholder="https://example.com/image.jpg" />
                </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-surface border border-border bg-surface-1">
                      <img src={asset.url} alt={asset.label} className="h-48 w-full object-cover" />
                    </div>
                  ) : (
                    <div className="rounded-surface border border-border bg-surface-1 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 border-border bg-surface-1 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>
  );
}
