"use client";

import { useEffect, useState } from "react";
import { MessageCircle, Send, X, MessageSquare, ShieldCheck, Zap, Scissors, Wrench, Droplets } from "lucide-react";
import Image from "next/image";

type WAOption = { id: string; title: string; subtitle: string; icon: string };

type WASettings = {
  number: string;
  title: string;
  subtitle: string;
  intro: string;
  options: WAOption[];
};

const DEFAULT_SETTINGS: WASettings = {
  number: "908503057245",
  title: "PetMarketim Destek",
  subtitle: "Sorularınız için buradayız",
  intro: "Merhaba! Evcil dostunuz için nasıl yardımcı olabiliriz? Aşağıdaki seçeneklerden birini seçebilir veya yazabilirsiniz.",
  options: [
    { id: "siparis", title: "Sipariş Takibi", subtitle: "Siparişim nerede?", icon: "package" },
    { id: "mama", title: "Mama Önerisi", subtitle: "Hangi mamayı seçmeliyim?", icon: "dog" },
    { id: "iade", title: "İade / Değişim", subtitle: "Ürün iade süreci", icon: "refresh" },
  ],
};

export function WhatsAppWidget() {
  const [open, setOpen] = useState(false);
  const [msg, setMsg] = useState("");
  const [settings, setSettings] = useState<WASettings>(DEFAULT_SETTINGS);

  useEffect(() => {
    fetch("/api/settings")
      .then((r) => r.json())
      .then((data) => {
        if (data?.whatsapp) {
          setSettings((prev) => ({
            ...prev,
            number: data.whatsapp.number || prev.number,
            title: data.whatsapp.title || prev.title,
            subtitle: data.whatsapp.subtitle || prev.subtitle,
            intro: data.whatsapp.intro || prev.intro,
            options: Array.isArray(data.whatsapp.options) && data.whatsapp.options.length > 0
              ? data.whatsapp.options
              : prev.options,
          }));
        }
      })
      .catch(() => {});
  }, []);

  const handleSend = (text?: string) => {
    const finalMsg = text || msg;
    if (!finalMsg) return;
    const cleanNumber = settings.number.replace(/\D/g, "");
    const url = `https://wa.me/${cleanNumber}?text=${encodeURIComponent(finalMsg)}`;
    window.open(url, "_blank");
    setMsg("");
    setOpen(false);
  };

  return (
    <div data-pet5-id="site.whatsapp" className="fixed bottom-6 right-6 z-[100] font-sans">
      {/* Balon */}
      <button
        onClick={() => setOpen(!open)}
        className="group relative flex size-14 items-center justify-center rounded-full bg-[#25D366] text-white shadow-2xl transition-transform hover:scale-110 active:scale-95"
        aria-label="WhatsApp Destek"
      >
        {open ? <X className="size-7" /> : <MessageCircle className="size-8" />}
        {!open && (
          <span className="absolute -left-32 top-2 rounded-lg bg-white px-3 py-1.5 text-xs font-bold text-ink shadow-lg ring-1 ring-sand-dark group-hover:block hidden">
            Yardım mı lazım? 🐾
          </span>
        )}
      </button>

      {/* Panel */}
      {open && (
        <div className="absolute bottom-20 right-0 w-[360px] animate-pop-in overflow-hidden rounded-[2rem] bg-white shadow-2xl ring-1 ring-sand-dark/50">
          {/* Header */}
          <div className="bg-[#075E54] p-5 text-white">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-3">
                <div className="relative size-12 overflow-hidden rounded-2xl bg-white p-1.5 shadow-md">
                   <div className="grid h-full w-full place-items-center rounded-xl bg-brand-500 text-white">
                      <MessageSquare className="size-6" />
                   </div>
                </div>
                <div>
                  <h3 className="font-extrabold leading-none">{settings.title}</h3>
                  <p className="mt-1 text-xs font-medium text-white/80">{settings.subtitle}</p>
                </div>
              </div>
              <button onClick={() => setOpen(false)} className="rounded-full p-1 hover:bg-white/10">
                <X className="size-5" />
              </button>
            </div>
          </div>

          {/* İçerik */}
          <div className="max-h-[450px] overflow-y-auto bg-[#F0F2F5] p-5">
            <div className="rounded-2xl bg-white p-4 text-sm font-semibold leading-relaxed text-cocoa shadow-sm">
              {settings.intro}
            </div>

            <div className="mt-4 space-y-2.5">
              <p className="flex items-center gap-1.5 text-[10px] font-extrabold uppercase tracking-widest text-mocha">
                <Zap className="size-3 text-brand-500" /> Hızlı Seçenekler
              </p>
              
              {settings.options.map((opt) => (
                <button
                  key={opt.id}
                  onClick={() => handleSend(opt.title)}
                  className="flex w-full items-center gap-3 rounded-2xl border-b-2 border-sand-dark bg-white p-3 text-left transition-all hover:bg-brand-50 hover:shadow-md active:translate-y-0.5"
                >
                  <span className="grid size-10 place-items-center rounded-xl bg-sand text-brand-600">
                     <MessageSquare className="size-5" />
                  </span>
                  <div className="flex-1">
                    <p className="text-sm font-extrabold text-ink">{opt.title}</p>
                    <p className="text-[11px] font-bold text-mocha">{opt.subtitle}</p>
                  </div>
                  <Send className="size-4 text-brand-300" />
                </button>
              ))}
            </div>
          </div>

          {/* Input */}
          <div className="bg-white p-4">
            <div className="relative flex items-end gap-2">
              <textarea
                value={msg}
                onChange={(e) => setMsg(e.target.value)}
                placeholder="Mesajınızı buraya yazın..."
                className="w-full resize-none rounded-2xl border-2 border-sand-dark bg-cream/50 px-4 py-3 pr-12 text-sm font-bold text-ink outline-none transition-colors focus:border-[#25D366] focus:bg-white"
                rows={2}
              />
              <button
                onClick={() => handleSend()}
                className="absolute bottom-2 right-2 flex size-9 items-center justify-center rounded-full bg-[#25D366] text-white shadow-lg transition-transform hover:scale-105 active:scale-95"
              >
                <Send className="size-4.5" />
              </button>
            </div>
            <p className="mt-3 flex items-center justify-center gap-1.5 text-[10px] font-bold text-mocha">
              <ShieldCheck className="size-3.5 text-emerald-600" />
              Mesajınız WhatsApp üzerinden iletilir.
            </p>
          </div>
        </div>
      )}
    </div>
  );
}
