"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import { updateBlogPostAction, deleteBlogPostAction, setBlogPostVisibleAction } from "@/lib/actions/blog";
import { formatDateDE } from "@/lib/orderConstants";
import { toDatetimeLocal } from "@/lib/datetimeLocal";
import { TagInput } from "@/components/admin/TagInput";

export function BlogPostRow({
  item,
}: {
  item: {
    id: string;
    title: string;
    titleEn: string;
    slug: string;
    excerpt: string;
    excerptEn: string;
    content: string;
    contentEn: string;
    coverImage: string;
    tags: string[];
    publishedAt: string;
    visible: boolean;
  };
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();
  const scheduled = new Date(item.publishedAt).getTime() > Date.now();

  function submit(form: HTMLFormElement) {
    const data = new FormData(form);
    startTransition(async () => {
      await updateBlogPostAction(item.id, data);
      router.refresh();
    });
  }

  return (
    <details className={`bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 ${item.visible ? "" : "opacity-60"}`}>
      <summary className="flex items-center justify-between gap-3 cursor-pointer list-none">
        <div className="flex items-center gap-3 min-w-0">
          {item.coverImage ? (
            <Image
              src={item.coverImage}
              alt=""
              width={56}
              height={40}
              className="rounded-lg object-cover border border-white/15 shrink-0 w-14 h-10"
            />
          ) : (
            <div className="w-14 h-10 rounded-lg border border-white/15 bg-white/5 shrink-0" />
          )}
          <div className="min-w-0">
            <p className="flex items-center gap-2 text-sm truncate">
              {item.title}
              {scheduled && item.visible && (
                <span className="shrink-0 rounded-full border border-[var(--rk-accent)]/40 px-2 py-0.5 text-[0.65rem] uppercase tracking-[0.08em] text-[var(--rk-accent)]">
                  ⏳ Geplant
                </span>
              )}
            </p>
            <p className="text-xs text-[var(--rk-ink-muted)] truncate">
              {scheduled ? "geplant für " : ""}
              {formatDateDE(new Date(item.publishedAt))}
              {scheduled
                ? " " + new Date(item.publishedAt).toLocaleTimeString("de-DE", { hour: "2-digit", minute: "2-digit" })
                : ""}
              {" · /blog/"}
              {item.slug} · Bearbeiten ▾
            </p>
          </div>
        </div>
        <div className="flex items-center gap-3 shrink-0" onClick={(e) => e.stopPropagation()}>
          <label className="flex items-center gap-1.5 text-xs">
            <input
              type="checkbox"
              checked={item.visible}
              disabled={pending}
              onChange={(e) => startTransition(async () => { await setBlogPostVisibleAction(item.id, e.target.checked); router.refresh(); })}
              className="h-3.5 w-3.5"
            />
            {scheduled ? "Freigegeben" : "Veröffentlicht"}
          </label>
          <button
            disabled={pending}
            onClick={() => {
              if (confirm(`Beitrag „${item.title}" wirklich löschen?`)) {
                startTransition(async () => { await deleteBlogPostAction(item.id); router.refresh(); });
              }
            }}
            className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
          >
            Löschen
          </button>
        </div>
      </summary>

      <form
        onSubmit={(e) => {
          e.preventDefault();
          submit(e.currentTarget);
        }}
        encType="multipart/form-data"
        className="mt-4 flex flex-col gap-3"
      >
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <input
            name="title"
            defaultValue={item.title}
            placeholder="Titel"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
          <input
            name="titleEn"
            defaultValue={item.titleEn}
            placeholder="Titel (Englisch, optional)"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
        </div>
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <input
            name="excerpt"
            defaultValue={item.excerpt}
            placeholder="Kurzbeschreibung (optional)"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
          <input
            name="excerptEn"
            defaultValue={item.excerptEn}
            placeholder="Kurzbeschreibung (Englisch, optional)"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
        </div>
        <textarea
          name="content"
          defaultValue={item.content}
          placeholder="Text (Deutsch)"
          rows={6}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-white/50 resize-y"
        />
        <textarea
          name="contentEn"
          defaultValue={item.contentEn}
          placeholder="Text (Englisch, optional)"
          rows={6}
          className="bg-transparent border border-white/15 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-white/50 resize-y"
        />
        <TagInput name="tags" defaultValue={(item.tags || []).join(", ")} placeholder="Tag eingeben, dann Enter" />
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <label className="flex flex-col gap-1.5 text-sm">
            <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
              Titelbild {item.coverImage ? "ersetzen" : "hinzufügen"} (optional)
            </span>
            <input name="coverImage" type="file" accept="image/jpeg,image/png,image/webp" className="text-sm" />
          </label>
          <label className="flex flex-col gap-1.5 text-sm">
            <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
              Veröffentlichen am <span className="normal-case tracking-normal">(Zukunft = geplant)</span>
            </span>
            <input
              name="publishedAt"
              type="datetime-local"
              defaultValue={toDatetimeLocal(item.publishedAt)}
              className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50 [color-scheme:dark]"
            />
          </label>
        </div>
        <button
          type="submit"
          disabled={pending}
          className="self-start border border-white/30 rounded-lg px-4 py-2 text-xs uppercase tracking-[0.15em] hover:border-white disabled:opacity-50"
        >
          Speichern
        </button>
      </form>
    </details>
  );
}
