"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import Image from "next/image";
import {
  updateTestimonialAction,
  deleteTestimonialAction,
  setTestimonialVisibleAction,
  moveTestimonialAction,
} from "@/lib/actions/testimonials";

export function TestimonialRow({
  item,
}: {
  item: {
    id: string;
    authorName: string;
    realName: string;
    quote: string;
    quoteEn: string;
    context: string;
    contextEn: string;
    imagePath: string;
    source: "manual" | "google";
    rating: number;
    reviewUrl: string;
    visible: boolean;
  };
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

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

  return (
    <details className="bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5">
      <summary className="flex items-center justify-between gap-3 cursor-pointer list-none">
        <div className="flex items-center gap-3 min-w-0">
          {item.source === "google" ? (
            <div className="w-10 h-10 rounded-full border border-white/15 bg-white/5 flex items-center justify-center text-xs shrink-0" style={{ color: "#f5c518" }}>
              {item.rating}★
            </div>
          ) : item.imagePath ? (
            <Image
              src={item.imagePath}
              alt=""
              width={40}
              height={40}
              className="rounded-full object-cover border border-white/15 shrink-0"
            />
          ) : (
            <div className="w-10 h-10 rounded-full border border-white/15 bg-white/5 shrink-0" />
          )}
          <div className="min-w-0">
            <p className="text-sm truncate">
              {item.realName ? `${item.realName} „${item.authorName}"` : item.authorName}
              {item.context && <span className="text-[var(--rk-ink-muted)]"> · {item.context}</span>}
              {item.source === "google" && (
                <span className="ml-2 text-[0.65rem] uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] border border-white/15 rounded-full px-2 py-0.5">
                  Google
                </span>
              )}
            </p>
            <p className="text-xs text-[var(--rk-ink-muted)] truncate">„{item.quote}" · Bearbeiten ▾</p>
          </div>
        </div>
        <div className="flex items-center gap-3 shrink-0" onClick={(e) => e.stopPropagation()}>
          <div className="flex flex-col gap-0.5">
            <button
              disabled={pending}
              onClick={() => startTransition(async () => { await moveTestimonialAction(item.id, "up"); router.refresh(); })}
              className="text-xs text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] disabled:opacity-50"
              title="Nach oben"
            >
              ▲
            </button>
            <button
              disabled={pending}
              onClick={() => startTransition(async () => { await moveTestimonialAction(item.id, "down"); router.refresh(); })}
              className="text-xs text-[var(--rk-ink-muted)] hover:text-[var(--rk-ink)] disabled:opacity-50"
              title="Nach unten"
            >
              ▼
            </button>
          </div>
          <label className="flex items-center gap-1.5 text-xs">
            <input
              type="checkbox"
              checked={item.visible}
              disabled={pending}
              onChange={(e) => startTransition(async () => { await setTestimonialVisibleAction(item.id, e.target.checked); router.refresh(); })}
              className="h-3.5 w-3.5"
            />
            Sichtbar
          </label>
          <button
            disabled={pending}
            onClick={() => {
              if (confirm("Diese Kundenstimme wirklich löschen?")) {
                startTransition(async () => {
                  await deleteTestimonialAction(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="authorName"
            defaultValue={item.authorName}
            placeholder="Name/Handle"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
          <input
            name="realName"
            defaultValue={item.realName}
            placeholder={'Echter Name (optional, steht davor: Max „Zoneks")'}
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
          />
          <input
            name="context"
            defaultValue={item.context}
            placeholder="Kontext (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="quote"
          defaultValue={item.quote}
          placeholder="Zitat (Deutsch)"
          rows={3}
          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"
        />
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          <textarea
            name="quoteEn"
            defaultValue={item.quoteEn}
            placeholder="Zitat (Englisch, optional)"
            rows={3}
            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"
          />
          <input
            name="contextEn"
            defaultValue={item.contextEn}
            placeholder="Kontext (Englisch, optional)"
            className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50 h-fit"
          />
        </div>

        {item.source === "google" ? (
          <div className="flex flex-col gap-3">
            <div>
              <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-1.5">Sternebewertung</p>
              <select
                name="rating"
                defaultValue={item.rating}
                className="bg-[var(--rk-bg)] border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
              >
                {[1, 2, 3, 4, 5].map((n) => (
                  <option key={n} value={n}>
                    {n} ★
                  </option>
                ))}
              </select>
            </div>
            <input
              name="reviewUrl"
              defaultValue={item.reviewUrl}
              placeholder="Link zur echten Google-Bewertung (optional)"
              className="bg-transparent border border-white/15 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-white/50"
            />
          </div>
        ) : (
          <label className="flex flex-col gap-1.5 text-sm">
            <span className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)]">
              Rundes Profilbild {item.imagePath ? "ersetzen" : "hinzufügen"} (optional)
            </span>
            <input name="image" type="file" accept="image/jpeg,image/png,image/webp" className="text-sm" />
            <span className="text-xs text-[var(--rk-ink-muted)]">
              Am besten ein Bild der Kundin/des Kunden selbst oder eines der beim Shooting entstandenen Fotos.
            </span>
          </label>
        )}

        <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>
  );
}
