"use client";

import { motion, AnimatePresence } from "framer-motion";
import BoldIcon from "@/components/ui/BoldIcon";
import toast from "react-hot-toast";

interface SharePostModalProps {
  open: boolean;
  onClose: () => void;
  url: string;
  title?: string;
}

export default function SharePostModal({
  open,
  onClose,
  url,
  title = "پست مادستاگرام",
}: SharePostModalProps) {
  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(url);
      toast.success("لینک کپی شد");
    } catch {
      toast.error("کپی لینک ناموفق بود");
    }
  };

  const nativeShare = async () => {
    if (navigator.share) {
      try {
        await navigator.share({ title, text: "این پست را ببین:", url });
      } catch {
        /* cancelled */
      }
    } else {
      await copyLink();
    }
  };

  return (
    <AnimatePresence>
      {open && (
        <>
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 z-[200] bg-black/40 backdrop-blur-sm"
            onClick={onClose}
          />
          <motion.div
            initial={{ y: "100%" }}
            animate={{ y: 0 }}
            exit={{ y: "100%" }}
            transition={{ type: "spring", damping: 28, stiffness: 320 }}
            className="glass-panel-strong fixed bottom-0 left-0 right-0 z-[201] rounded-t-3xl p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))]"
          >
            <div className="mb-4 flex items-center justify-between">
              <h3 className="font-bold">اشتراک‌گذاری</h3>
              <button type="button" onClick={onClose} className="rounded-full p-2">
                <BoldIcon name="close-circle" size={20} tinted className="text-current" />
              </button>
            </div>
            <div className="glass-chat-input mb-4 flex items-center gap-2 rounded-2xl px-3 py-2.5">
              <span className="flex-1 truncate text-xs text-neutral-600 dark:text-neutral-300" dir="ltr">
                {url}
              </span>
              <button
                type="button"
                onClick={copyLink}
                className="chat-action-btn gentle-transition flex h-9 w-9 shrink-0 items-center justify-center rounded-full active:scale-90"
                aria-label="کپی"
              >
                <BoldIcon name="copy" size={16} tinted className="text-white" />
              </button>
            </div>
            <button
              type="button"
              onClick={nativeShare}
              className="ig-dm-send-btn gentle-transition flex w-full items-center justify-center gap-2 rounded-full py-3 text-sm font-semibold text-white active:scale-[0.98]"
            >
              <BoldIcon name="share" size={18} tinted className="text-white" />
              اشتراک‌گذاری سیستمی
            </button>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
