"use client";

import Link from "next/link";
import { useActionState, useState } from "react";
import { sendQuote } from "@/lib/quotes/actions";
import type { ActionState } from "@/lib/auth/actions";
import type { listQuotes } from "@/lib/quotes/queries";
import { QuoteLikeButton } from "@/components/quotes/QuoteLikeButton";

type Quote = Awaited<ReturnType<typeof listQuotes>>[number];

function quoteShareText(quote: Quote) {
  return `"${quote.text}" — ${quote.author ?? "Anonim"}`;
}

function CopyButton({ quote }: { quote: Quote }) {
  const [copied, setCopied] = useState(false);

  return (
    <button
      type="button"
      title="Kopyala"
      onClick={async () => {
        try {
          await navigator.clipboard.writeText(quoteShareText(quote));
          setCopied(true);
          setTimeout(() => setCopied(false), 1800);
        } catch {
          // pano erişimi engellenmiş olabilir — sessizce yok say
        }
      }}
      className="text-text-muted hover:text-accent"
    >
      {copied ? (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" strokeLinejoin="round">
          <path d="M20 6L9 17l-5-5" />
        </svg>
      ) : (
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
          <rect x="9" y="9" width="13" height="13" rx="2" />
          <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
        </svg>
      )}
    </button>
  );
}

function SocialShareMenu({ quote }: { quote: Quote }) {
  const [open, setOpen] = useState(false);
  const text = quoteShareText(quote);
  const shareUrl = () => `${window.location.origin}/sozler/soz/${quote.slug}`;

  function openIntent(url: string) {
    window.open(url, "_blank", "noopener,noreferrer,width=600,height=500");
    setOpen(false);
  }

  async function shareToInstagram() {
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      // yok say
    }
    setOpen(false);
  }

  return (
    <div className="relative">
      <button
        type="button"
        title="Sosyal Medyada Paylaş"
        onClick={() => setOpen((v) => !v)}
        className="text-text-muted hover:text-accent"
      >
        <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
          <circle cx="18" cy="5" r="3" />
          <circle cx="6" cy="12" r="3" />
          <circle cx="18" cy="19" r="3" />
          <path d="M8.6 10.6l6.8-3.9M8.6 13.4l6.8 3.9" />
        </svg>
      </button>

      {open && (
        <>
          <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />
          <div className="absolute bottom-full right-0 z-20 mb-2 flex items-center gap-1.5 rounded-full border border-border bg-surface p-1.5 shadow-lg">
            <button
              type="button"
              title="X'te paylaş"
              onClick={() =>
                openIntent(`https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(shareUrl())}`)
              }
              className="flex h-8 w-8 items-center justify-center rounded-full bg-black text-white hover:opacity-80"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                <path d="M18.9 2H22l-7.6 8.6L23.3 22h-7l-5.5-7.2L4.5 22H1.4l8.2-9.3L1 2h7.2l5 6.6L18.9 2zm-1.2 18h1.7L7.4 4h-1.8l12.1 16z" />
              </svg>
            </button>
            <button
              type="button"
              title="Facebook'ta paylaş"
              onClick={() =>
                openIntent(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(shareUrl())}&quote=${encodeURIComponent(text)}`)
              }
              className="flex h-8 w-8 items-center justify-center rounded-full bg-[#1877f2] text-white hover:opacity-80"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                <path d="M22 12a10 10 0 1 0-11.6 9.9v-7H7.9V12h2.5V9.8c0-2.5 1.5-3.9 3.8-3.9 1.1 0 2.2.2 2.2.2v2.5h-1.3c-1.2 0-1.6.8-1.6 1.6V12h2.8l-.4 2.9h-2.4v7A10 10 0 0 0 22 12z" />
              </svg>
            </button>
            <button
              type="button"
              title="WhatsApp'ta paylaş"
              onClick={() => openIntent(`https://wa.me/?text=${encodeURIComponent(`${text} ${shareUrl()}`)}`)}
              className="flex h-8 w-8 items-center justify-center rounded-full bg-[#25d366] text-white hover:opacity-80"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2a10 10 0 0 0-8.6 15L2 22l5.2-1.4A10 10 0 1 0 12 2zm0 18.2a8.1 8.1 0 0 1-4.2-1.1l-.3-.2-3.1.8.8-3-.2-.3A8.2 8.2 0 1 1 12 20.2zm4.5-6.1c-.2-.1-1.5-.7-1.7-.8-.2-.1-.4-.1-.6.1-.2.2-.7.8-.8.9-.2.2-.3.2-.5.1a6.7 6.7 0 0 1-2-1.2 7.4 7.4 0 0 1-1.4-1.7c-.1-.2 0-.4.1-.5l.4-.4c.1-.1.2-.2.2-.4.1-.1.1-.3 0-.4l-.8-1.8c-.2-.5-.4-.4-.6-.4h-.5c-.2 0-.5.1-.7.3-.2.2-.9.9-.9 2.1s1 2.5 1.1 2.6c.1.2 1.9 2.9 4.7 4 .6.3 1.1.4 1.5.5.6.2 1.2.2 1.6.1.5-.1 1.5-.6 1.7-1.2.2-.6.2-1.1.1-1.2-.1-.1-.2-.2-.4-.3z" />
              </svg>
            </button>
            <button
              type="button"
              title="Instagram için kopyala"
              onClick={shareToInstagram}
              className="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-[#feda75] via-[#d62976] to-[#4f5bd5] text-white hover:opacity-80"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2}>
                <rect x="2" y="2" width="20" height="20" rx="5" />
                <circle cx="12" cy="12" r="4" />
                <circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
              </svg>
            </button>
          </div>
        </>
      )}
    </div>
  );
}

export function QuoteCard({ quote, canSend, canLike = false }: { quote: Quote; canSend: boolean; canLike?: boolean }) {
  const [open, setOpen] = useState(false);
  const action = sendQuote.bind(null, quote.id);
  const [state, formAction, pending] = useActionState<ActionState, FormData>(action, undefined);

  return (
    <div className="card-lift group relative overflow-hidden rounded-2xl bg-surface p-6 shadow-[0_1px_2px_rgba(30,15,8,.04),0_8px_20px_rgba(30,15,8,.05)]">
      <div className="absolute inset-x-0 top-0 h-1.5 bg-gradient-to-r from-accent to-accent-2" />
      <span className="mb-4 inline-block rounded-full bg-accent/10 px-3 py-1 text-[11.5px] font-bold text-accent">
        {quote.category.name}
      </span>
      <Link href={`/sozler/soz/${quote.slug}`} className="block">
        <div className="font-serif-quote mb-1 text-[56px] leading-[0.35] text-accent-2 opacity-70 transition-opacity group-hover:opacity-100">
          &ldquo;
        </div>
        <p className="font-serif-quote text-[16.5px] italic leading-relaxed hover:text-accent">{quote.text}</p>
      </Link>
      <div className="mt-4 flex items-center justify-between">
        <span className="text-[13px] text-text-muted">— {quote.author ?? "Anonim"}</span>
        <div className="flex items-center gap-3">
          <CopyButton quote={quote} />
          <SocialShareMenu quote={quote} />
          {canSend && (
            <button
              type="button"
              onClick={() => setOpen((v) => !v)}
              title="Gönder"
              className="text-accent hover:text-accent-dark"
            >
              <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 2L11 13" />
                <path d="M22 2l-7 20-4-9-9-4 20-7z" />
              </svg>
            </button>
          )}
        </div>
      </div>

      <div className="mt-3 flex items-center gap-4 border-t border-dashed border-border pt-3">
        {canLike ? (
          <QuoteLikeButton quoteId={quote.id} initiallyLiked={quote.likes.length > 0} likeCount={quote._count.likes} />
        ) : (
          <span className="flex items-center gap-1.5 text-[12.5px] font-semibold text-text-muted">
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 20s-7-4.35-9.5-8.5C.5 8 2 4 6 4c2 0 3.5 1.2 4 2.5C10.5 5.2 12 4 14 4c4 0 5.5 4 3.5 7.5C19 15.65 12 20 12 20z" />
            </svg>
            {quote._count.likes > 0 ? quote._count.likes : ""}
          </span>
        )}

        <span className="flex items-center gap-1.5 text-[12.5px] font-semibold text-text-muted">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
            <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z" />
            <circle cx="12" cy="12" r="3" />
          </svg>
          {quote.viewCount}
        </span>

        <span className="flex items-center gap-1.5 text-[12.5px] font-semibold text-text-muted">
          <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
            <path d="M4 5h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H9l-5 4v-4H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z" />
          </svg>
          {quote._count.comments}
        </span>
      </div>

      {open && (
        <form action={formAction} className="mt-3 flex items-center gap-2 border-t border-border pt-3">
          <input
            name="toUsername"
            placeholder="@kullaniciadi"
            required
            className="flex-1 rounded-lg border border-border px-3 py-2 text-[13px] outline-none focus:border-accent"
          />
          <button
            type="submit"
            disabled={pending}
            className="rounded-lg bg-accent px-3.5 py-2 text-[12.5px] font-semibold text-white hover:bg-accent-dark disabled:opacity-60"
          >
            {pending ? "..." : "Gönder"}
          </button>
        </form>
      )}
      {state?.message && <p className="mt-2 text-[12px] text-text-muted">{state.message}</p>}
    </div>
  );
}
