/* 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 { 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",
};

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 ? (
          <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>
        ) : null}

        {searchParams?.error ? (
          <p className="rounded-nested border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
            {searchParams.error}
          </p>
        ) : null}

        <AppCard>
          <CardHeader>
            <CardTitle>New Media Asset</CardTitle>
            <CardDescription>Upload a file or store an external URL for reuse across the site.</CardDescription>
          </CardHeader>
          <CardContent>
            <form action={createMediaAssetAction} className="grid gap-4 md:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="label">Label</Label>
                <Input id="label" name="label" required />
              </div>

              <div className="space-y-2">
                <Label htmlFor="kind">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">Upload File</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">External URL</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" />
                  Save Media
                </Button>
              </div>
            </form>
          </CardContent>
        </AppCard>

        <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
          {mediaAssets.map((asset) => (
            <AppCard key={asset.id}>
              <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} 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" />
                      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" />
                    Delete
                  </Button>
                </form>
              </CardContent>
            </AppCard>
          ))}
        </div>

        {mediaAssets.length === 0 ? (
          <AppCard>
            <CardContent className="p-6 text-sm text-muted-foreground">
              No media assets found yet.
            </CardContent>
          </AppCard>
        ) : null}
      </div>
    </RootDashboardShell>
  );
}
