"use client";

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

import type { MediaKind } from "@prisma/client";
import { FileType2, Grid2x2, ImageIcon, LayoutList, LoaderCircle, Trash2, Upload } from "lucide-react";
import Link from "next/link";
import { useEffect, useMemo, useState } from "react";
import { useFormStatus } from "react-dom";
import { useSearchParams } from "next/navigation";

import type { MediaAssetView } from "@/lib/media";
import { MotionFade } from "@/components/motion-fade";
import { AppCard } from "@/components/ui/app-card";
import { Button } from "@/components/ui/button";
import { CardContent } from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table";
import { cn } from "@/lib/utils";

import { createMediaAssetAction, deleteMediaAssetAction } from "@/app/_admin/media/actions";

const copy = {
  addMedia: "Upload Media File",
  addMediaDescription: "Datei hochladen und direkt in die Media Library uebernehmen.",
  addMediaHint: "PNG, JPG, GIF oder PDF bis 5 MB",
  label: "Bezeichnung",
  kind: "Typ",
  image: "Image",
  document: "Document",
  upload: "Upload",
  uploading: "Uploading...",
  selectFile: "Datei auswaehlen",
  empty: "Noch keine Bilder vorhanden.",
  grid: "Grid",
  list: "List",
  detailsButton: "Details",
  open: "Open",
  delete: "Delete",
  deleteConfirm: "Delete this media file?",
  usages: "Verwendungen",
  source: "Quelle",
  fileName: "Dateiname",
  url: "URL",
  mimeType: "MIME Type",
  size: "Dateigroesse",
  createdAt: "Erstellt",
  close: "Close",
  details: "Bilddetails",
  detailsDescription: "Metadaten und Verwendungen der ausgewaehlten Datei.",
};

function formatFileSize(size: number | null) {
  if (!size) {
    return "—";
  }

  if (size < 1024) {
    return `${size} B`;
  }

  if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(1)} KB`;
  }

  return `${(size / (1024 * 1024)).toFixed(1)} MB`;
}

function formatCreatedAt(value: string | Date) {
  const date = value instanceof Date ? value : new Date(value);

  return new Intl.DateTimeFormat("de-DE", {
    dateStyle: "medium",
    timeStyle: "short",
  }).format(date);
}

function getAbsoluteUrl(path: string) {
  if (/^https?:\/\//.test(path)) {
    return path;
  }

  if (typeof window === "undefined") {
    return path;
  }

  return new URL(path, window.location.origin).toString();
}

function UploadSubmitButton() {
  const { pending } = useFormStatus();

  return (
    <Button type="submit" disabled={pending} className="w-full sm:w-auto">
      {pending ? <LoaderCircle className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />}
      {pending ? copy.uploading : copy.upload}
    </Button>
  );
}

function MediaUploadDialog({
  open,
  onOpenChange,
}: {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  const [kind, setKind] = useState<MediaKind>("IMAGE");
  const [label, setLabel] = useState("");
  const [isLabelDirty, setIsLabelDirty] = useState(false);

  useEffect(() => {
    if (!open) {
      setKind("IMAGE");
      setLabel("");
      setIsLabelDirty(false);
    }
  }, [open]);

  function handleFileChange(event: React.ChangeEvent<HTMLInputElement>) {
    const file = event.target.files?.[0];

    if (!file || isLabelDirty) {
      return;
    }

    setLabel(file.name.replace(/\.[^.]+$/, ""));
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogTrigger asChild>
        <button
          type="button"
          className="group block w-full rounded-surface border-2 border-dashed border-border/80 bg-surface-2 p-3 text-left transition-colors hover:border-primary/50 hover:bg-accent/30"
        >
          <div className="flex min-h-[240px] flex-col items-center justify-center rounded-nested border border-border/60 bg-background px-6 py-10 text-center">
            <div className="flex h-16 w-16 items-center justify-center rounded-nested bg-muted text-muted-foreground">
              <ImageIcon className="h-8 w-8" />
            </div>
            <p className="mt-6 text-2xl font-semibold text-foreground">{copy.addMedia}</p>
            <p className="mt-2 text-sm text-muted-foreground">{copy.addMediaHint}</p>
            <span className="mt-6 inline-flex h-11 items-center justify-center rounded-nested bg-primary px-5 text-sm font-medium text-primary-foreground shadow-sm transition-colors group-hover:bg-primary/92">
              {copy.addMedia}
            </span>
          </div>
        </button>
      </DialogTrigger>

      <DialogContent className="max-h-[calc(100vh-1.5rem)] w-[calc(100vw-1rem)] max-w-2xl overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{copy.addMedia}</DialogTitle>
          <DialogDescription>{copy.addMediaDescription}</DialogDescription>
        </DialogHeader>

        <form action={createMediaAssetAction} className="space-y-6">
          <div className="space-y-2">
            <Label htmlFor="media-label">{copy.label}</Label>
            <Input
              id="media-label"
              name="label"
              value={label}
              onChange={(event) => {
                setLabel(event.target.value);
                setIsLabelDirty(true);
              }}
              placeholder={copy.label}
            />
          </div>

          <div className="space-y-3">
            <Label>{copy.kind}</Label>
            <div className="flex flex-wrap gap-2">
              {[
                { value: "IMAGE" as const, label: copy.image, icon: ImageIcon },
                { value: "DOCUMENT" as const, label: copy.document, icon: FileType2 },
              ].map((option) => {
                const Icon = option.icon;
                const isActive = kind === option.value;

                return (
                  <button
                    key={option.value}
                    type="button"
                    onClick={() => setKind(option.value)}
                    className={cn(
                      "inline-flex items-center gap-2 rounded-nested border px-4 py-2 text-sm transition-colors",
                      isActive
                        ? "border-input bg-primary text-primary-foreground"
                        : "border-input bg-background text-foreground/75 hover:bg-accent hover:text-accent-foreground",
                    )}
                  >
                    <Icon className="h-4 w-4" />
                    {option.label}
                  </button>
                );
              })}
            </div>
            <input type="hidden" name="kind" value={kind} />
          </div>

          <div className="space-y-2">
            <Label htmlFor="media-file">{copy.selectFile}</Label>
            <Input
              id="media-file"
              name="file"
              type="file"
              required
              accept={kind === "IMAGE" ? "image/png,image/jpeg,image/gif,image/webp,image/svg+xml" : "application/pdf"}
              className="file:mr-3"
              onChange={handleFileChange}
            />
            <p className="text-xs text-muted-foreground">{copy.addMediaHint}</p>
          </div>

          <DialogFooter className="sm:justify-start">
            <UploadSubmitButton />
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}

function MediaDetailsDialog({
  asset,
  open,
  onOpenChange,
}: {
  asset: MediaAssetView | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
}) {
  if (!asset) {
    return null;
  }

  const absoluteUrl = getAbsoluteUrl(asset.url);

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-h-[calc(100vh-1.5rem)] w-[calc(100vw-1rem)] max-w-5xl overflow-y-auto p-0">
        <div className="grid gap-0 md:grid-cols-[minmax(0,1.3fr)_minmax(320px,0.9fr)]">
          <div className="border-b border-border/70 bg-muted/30 md:border-b-0 md:border-r">
            <div className="flex h-full items-center justify-center p-4 sm:p-6">
              <Link href={asset.url} target="_blank" rel="noreferrer" className="block w-full">
                <img
                  src={asset.url}
                  alt={asset.label}
                  className="max-h-[55vh] w-full rounded-nested object-contain transition-transform duration-300 hover:scale-[1.02] md:max-h-[75vh]"
                />
              </Link>
            </div>
          </div>

            <div className="space-y-6 p-4 sm:p-6">
            <DialogHeader className="space-y-2 text-left">
              <DialogTitle className="pr-8">{asset.label}</DialogTitle>
              <DialogDescription>{copy.detailsDescription}</DialogDescription>
            </DialogHeader>

            <div className="rounded-nested border">
              <Table>
                <TableBody>
                  <TableRow>
                    <TableCell className="w-36 font-medium text-muted-foreground">{copy.kind}</TableCell>
                    <TableCell>{asset.kind}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="w-36 font-medium text-muted-foreground">{copy.source}</TableCell>
                    <TableCell>{asset.source}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="w-36 font-medium text-muted-foreground">{copy.fileName}</TableCell>
                    <TableCell className="break-all">{asset.fileName || "—"}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="w-36 font-medium text-muted-foreground">{copy.mimeType}</TableCell>
                    <TableCell className="break-all">{asset.mimeType || "—"}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="w-36 font-medium text-muted-foreground">{copy.size}</TableCell>
                    <TableCell>{formatFileSize(asset.size)}</TableCell>
                  </TableRow>
                  <TableRow>
                    <TableCell className="w-36 font-medium text-muted-foreground">{copy.createdAt}</TableCell>
                    <TableCell>{formatCreatedAt(asset.createdAt)}</TableCell>
                  </TableRow>
                </TableBody>
              </Table>
            </div>

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

            <div className="space-y-2 rounded-nested border bg-muted/20 p-4 text-sm">
              <p className="font-medium text-foreground">{copy.url}</p>
              <p className="break-all text-muted-foreground">{absoluteUrl}</p>
            </div>

            <DialogFooter className="items-stretch sm:items-center sm:justify-between">
              <Button asChild variant="outline" className="w-full sm:w-auto">
                <Link href={asset.url} target="_blank" rel="noreferrer">
                  {copy.open}
                </Link>
              </Button>

              <form action={deleteMediaAssetAction} className="w-full sm:w-auto">
                <input type="hidden" name="assetId" value={asset.id} />
                <Button
                  type="submit"
                  variant="destructive"
                  disabled={asset.usages.length > 0}
                  className="w-full sm:w-auto"
                  onClick={(event) => {
                    if (!window.confirm(copy.deleteConfirm)) {
                      event.preventDefault();
                    }
                  }}
                >
                  <Trash2 className="h-4 w-4" />
                  {copy.delete}
                </Button>
              </form>
            </DialogFooter>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

export function MediaLibraryManager({
  mediaAssets,
}: {
  mediaAssets: MediaAssetView[];
}) {
  const searchParams = useSearchParams();
  const [isUploadDialogOpen, setIsUploadDialogOpen] = useState(false);
  const [selectedAssetId, setSelectedAssetId] = useState<string | null>(null);
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const imageAssets = useMemo(
    () => mediaAssets.filter((asset) => asset.kind === "IMAGE"),
    [mediaAssets],
  );
  const selectedAsset = imageAssets.find((asset) => asset.id === selectedAssetId) ?? null;

  useEffect(() => {
    if (searchParams.has("success")) {
      setIsUploadDialogOpen(false);
      setSelectedAssetId(null);
    }
  }, [searchParams]);

  return (
    <div className="space-y-6">
      <MotionFade delay={0.15}>
        <MediaUploadDialog open={isUploadDialogOpen} onOpenChange={setIsUploadDialogOpen} />
      </MotionFade>

      {imageAssets.length > 0 ? (
        <div className="flex justify-end">
          <div className="inline-flex rounded-nested border border-input bg-background p-1">
            <button
              type="button"
              onClick={() => setViewMode("grid")}
              className={cn(
                "inline-flex items-center gap-2 rounded-nested px-3 py-2 text-sm transition-colors",
                viewMode === "grid"
                  ? "bg-primary text-primary-foreground"
                  : "text-foreground/75 hover:bg-accent hover:text-accent-foreground",
              )}
            >
              <Grid2x2 className="h-4 w-4" />
              {copy.grid}
            </button>
            <button
              type="button"
              onClick={() => setViewMode("list")}
              className={cn(
                "inline-flex items-center gap-2 rounded-nested px-3 py-2 text-sm transition-colors",
                viewMode === "list"
                  ? "bg-primary text-primary-foreground"
                  : "text-foreground/75 hover:bg-accent hover:text-accent-foreground",
              )}
            >
              <LayoutList className="h-4 w-4" />
              {copy.list}
            </button>
          </div>
        </div>
      ) : null}

      {imageAssets.length > 0 ? (
        viewMode === "grid" ? (
          <div className="grid grid-cols-[repeat(auto-fill,minmax(160px,1fr))] gap-4 sm:grid-cols-[repeat(auto-fill,minmax(180px,1fr))] xl:grid-cols-[repeat(auto-fill,minmax(210px,1fr))]">
            {imageAssets.map((asset, index) => (
              <MotionFade key={asset.id} delay={0.18 + index * 0.02}>
                <button
                  type="button"
                  onClick={() => setSelectedAssetId(asset.id)}
                  className="group text-left"
                >
                  <AppCard
                    layer="single"
                    padding="none"
                    interactive
                    className="overflow-hidden"
                  >
                    <div className="aspect-square overflow-hidden bg-muted/30">
                      <img
                        src={asset.url}
                        alt={asset.label}
                        className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-110"
                      />
                    </div>
                  </AppCard>
                </button>
              </MotionFade>
            ))}
          </div>
        ) : (
          <div className="space-y-3">
            {imageAssets.map((asset, index) => (
              <MotionFade key={asset.id} delay={0.18 + index * 0.02}>
                <AppCard layer="single" padding="none" className="overflow-hidden">
                  <div className="flex flex-col gap-4 p-4 sm:flex-row sm:items-center">
                    <button
                      type="button"
                      onClick={() => setSelectedAssetId(asset.id)}
                      className="group h-24 w-full overflow-hidden rounded-nested border bg-muted/30 sm:w-24"
                    >
                      <img
                        src={asset.url}
                        alt={asset.label}
                        className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-110"
                      />
                    </button>

                    <div className="min-w-0 flex-1 space-y-1">
                      <p className="truncate font-medium text-foreground">{asset.label}</p>
                      <p className="text-sm text-muted-foreground">{formatFileSize(asset.size)}</p>
                      <p className="truncate text-sm text-muted-foreground">{formatCreatedAt(asset.createdAt)}</p>
                    </div>

                    <div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
                      <Button
                        type="button"
                        variant="outline"
                        className="w-full sm:w-auto"
                        onClick={() => setSelectedAssetId(asset.id)}
                      >
                        {copy.detailsButton}
                      </Button>
                      <Button asChild variant="outline" className="w-full sm:w-auto">
                        <Link href={asset.url} target="_blank" rel="noreferrer">
                          {copy.open}
                        </Link>
                      </Button>
                    </div>
                  </div>
                </AppCard>
              </MotionFade>
            ))}
          </div>
        )
      ) : (
        <MotionFade delay={0.18}>
          <AppCard layer="single">
            <CardContent className="p-6 text-sm text-muted-foreground">
              {copy.empty}
            </CardContent>
          </AppCard>
        </MotionFade>
      )}

      <MediaDetailsDialog
        asset={selectedAsset}
        open={Boolean(selectedAsset)}
        onOpenChange={(open) => {
          if (!open) {
            setSelectedAssetId(null);
          }
        }}
      />
    </div>
  );
}
