import { useEffect, useRef, useState } from "react";
import { FIRMA } from "@/lib/site";

function WhatsAppIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" className={className}>
      <path d="M17.47 14.38c-.3-.15-1.76-.87-2.03-.97-.27-.1-.47-.15-.67.15-.2.3-.77.97-.94 1.17-.17.2-.35.22-.65.07-.3-.15-1.26-.46-2.4-1.48-.89-.79-1.49-1.76-1.66-2.06-.17-.3-.02-.46.13-.61.13-.13.3-.35.45-.52.15-.17.2-.3.3-.5.1-.2.05-.37-.02-.52-.08-.15-.67-1.61-.92-2.2-.24-.58-.49-.5-.67-.51h-.57c-.2 0-.52.07-.79.37-.27.3-1.04 1.02-1.04 2.48 0 1.46 1.07 2.87 1.22 3.07.15.2 2.1 3.2 5.08 4.49.71.31 1.26.49 1.69.63.71.23 1.36.2 1.87.12.57-.09 1.76-.72 2.01-1.41.25-.7.25-1.29.17-1.41-.07-.13-.27-.2-.57-.35zM12.04 21.79h-.01a9.87 9.87 0 0 1-5.03-1.38l-.36-.21-3.74.98 1-3.65-.24-.37a9.86 9.86 0 0 1-1.51-5.26c0-5.45 4.44-9.88 9.89-9.88 2.64 0 5.12 1.03 6.99 2.9a9.82 9.82 0 0 1 2.9 6.99c0 5.45-4.44 9.88-9.89 9.88zM20.52 3.49A11.82 11.82 0 0 0 12.04 0C5.46 0 .1 5.35.1 11.93c0 2.1.55 4.15 1.6 5.96L0 24l6.24-1.64a11.88 11.88 0 0 0 5.8 1.48h.01c6.58 0 11.94-5.35 11.94-11.93 0-3.19-1.24-6.19-3.47-8.42z" />
    </svg>
  );
}

export function WhatsAppChat() {
  const [deschis, setDeschis] = useState(false);
  const [mesaj, setMesaj] = useState(FIRMA.whatsappMesaj);
  const zona = useRef<HTMLDivElement>(null);
  const camp = useRef<HTMLTextAreaElement>(null);

  useEffect(() => {
    if (!deschis) return;
    camp.current?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setDeschis(false);
    };
    const onClick = (e: MouseEvent) => {
      if (zona.current && !zona.current.contains(e.target as Node)) setDeschis(false);
    };
    document.addEventListener("keydown", onKey);
    document.addEventListener("mousedown", onClick);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("mousedown", onClick);
    };
  }, [deschis]);

  const trimite = () => {
    const text = mesaj.trim() || FIRMA.whatsappMesaj;
    window.open(
      `https://wa.me/${FIRMA.whatsapp}?text=${encodeURIComponent(text)}`,
      "_blank",
      "noopener,noreferrer",
    );
    setDeschis(false);
  };

  return (
    <div ref={zona} className="fixed bottom-6 right-6 z-30 flex flex-col items-end gap-3">
      {deschis && (
        <div className="w-[min(21rem,calc(100vw-3rem))] overflow-hidden rounded-lg border bg-card shadow-card">
          <div className="bg-navy px-5 py-4 text-navy-foreground">
            <p className="font-serif text-lg">{FIRMA.nume}</p>
            <p className="mt-1 text-sm opacity-80">Scrie-ne pe WhatsApp — răspundem în scurt timp.</p>
          </div>
          <div className="p-5">
            <label htmlFor="whatsapp-mesaj" className="text-sm font-medium text-foreground">
              Mesajul tău
            </label>
            <textarea
              id="whatsapp-mesaj"
              ref={camp}
              rows={4}
              value={mesaj}
              onChange={(e) => setMesaj(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && !e.shiftKey) {
                  e.preventDefault();
                  trimite();
                }
              }}
              className="mt-2 w-full resize-none rounded-md border bg-background p-3 text-sm text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring"
              placeholder="Scrie un mesaj..."
            />
            <button
              type="button"
              onClick={trimite}
              className="mt-3 flex w-full items-center justify-center gap-2 rounded-md bg-whatsapp px-4 py-3 font-medium text-whatsapp-foreground hover:opacity-90"
            >
              <WhatsAppIcon className="h-5 w-5" />
              Trimite pe WhatsApp
            </button>
            <p className="mt-3 text-xs text-muted-foreground">
              Se deschide WhatsApp cu mesajul scris de tine, către {FIRMA.telefon}.
            </p>
          </div>
        </div>
      )}
      <button
        type="button"
        onClick={() => setDeschis((d) => !d)}
        aria-expanded={deschis}
        aria-label={deschis ? "Închide chatul WhatsApp" : "Deschide chatul WhatsApp"}
        className="flex h-14 w-14 items-center justify-center rounded-full bg-whatsapp text-whatsapp-foreground shadow-card transition-transform hover:scale-105"
      >
        {deschis ? (
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={2} strokeLinecap="round" aria-hidden="true" className="h-6 w-6">
            <path d="M6 6l12 12M18 6L6 18" />
          </svg>
        ) : (
          <WhatsAppIcon className="h-7 w-7" />
        )}
      </button>
    </div>
  );
}
