import React, { useEffect, useMemo, useState } from "react";
import ModalShell from "./ModalShell";

const SHARE_DURATION_OPTIONS = [
  { label: "نامحدود", value: "" },
  { label: "1 ساعت", value: "1h" },
  { label: "3 ساعت", value: "3h" },
  { label: "6 ساعت", value: "6h" },
  { label: "12 ساعت", value: "12h" },
  { label: "24 ساعت", value: "24h" },
  { label: "1 روز", value: "1d" },
  { label: "3 روز", value: "3d" },
  { label: "7 روز", value: "7d" },
  { label: "14 روز", value: "14d" },
  { label: "30 روز", value: "30d" },
];

async function copyText(text) {
  const value = String(text || "");
  if (!value) return false;

  // Modern clipboard
  try {
    if (navigator?.clipboard?.writeText) {
      await navigator.clipboard.writeText(value);
      return true;
    }
  } catch (_) {}

  // Fallback (execCommand)
  try {
    const ta = document.createElement("textarea");
    ta.value = value;
    ta.setAttribute("readonly", "");
    ta.style.position = "fixed";
    ta.style.top = "-9999px";
    ta.style.left = "-9999px";
    document.body.appendChild(ta);
    ta.select();
    const ok = document.execCommand("copy");
    document.body.removeChild(ta);
    return ok;
  } catch (_) {
    return false;
  }
}

export default function ShareModal({ state, onClose, onCopy, onRevoke, onCreate }) {
  const open = !!state?.open;
  const file = state?.file || null;
  const apiData = state?.data || null;

  // ✅ اولویت: download_url -> share_url -> state.downloadLink
  const effectiveLink = apiData?.download_url || apiData?.share_url || state?.downloadLink || "";
  const hasLink = !!effectiveLink;

  const creating = !!state?.creating;
  const revoking = !!state?.revoking;
  const copying = !!state?.copying;

  // ✅ defaults
  const [permission, setPermission] = useState("view"); // view | edit
  const [duration, setDuration] = useState("7d"); // default

  // وقتی مودال باز شد برای فایل جدید، ریست کن
  const fileKey = useMemo(
    () => String(file?.id || file?.file_id || file?.uuid || file?.name || ""),
    [file]
  );

  useEffect(() => {
    if (!open) return;
    setPermission("view");
    setDuration("7d");
  }, [open, fileKey]);

  const handleCreate = async () => {
    if (!file) return;
    onCreate?.({ permission, duration, file });
  };

  const handleCopy = async () => {
    if (!hasLink) return;

    // ✅ اگر والد onCopy داده، لینک رو بهش بده (نه event!)
    if (typeof onCopy === "function") {
      onCopy(effectiveLink);
      return;
    }

    // ✅ در غیر اینصورت خود کامپوننت کپی کن
    const ok = await copyText(effectiveLink);
    if (!ok) alert("کپی انجام نشد. لطفاً دستی کپی کنید.");
  };

  return (
    <ModalShell open={open} title="اشتراک‌گذاری فایل" onClose={onClose}>
      <div className="space-y-4">
        {/* File name */}
        <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-3">
          <div className="text-xs text-black/60 dark:text-white/70">فایل</div>
          <div className="font-extrabold text-sm sm:text-base truncate">
            {file?.name || "—"}
          </div>
        </div>

        {/* Controls */}
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
          {/* Permission */}
          <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-3">
            <div className="text-xs text-black/60 dark:text-white/70 mb-2">
              سطح دسترسی
            </div>
            <div className="flex gap-2">
              <button
                type="button"
                onClick={() => setPermission("view")}
                className={`flex-1 rounded-xl px-3 py-2 text-sm font-bold border transition ${
                  permission === "view"
                    ? "bg-[#A1E3F980] dark:bg-[#A1E3F919] border-[#A1E3F919] text-black dark:text-[#43BEFF]"
                    : "border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
                }`}
              >
                فقط مشاهده
              </button>
              <button
                type="button"
                onClick={() => setPermission("edit")}
                className={`flex-1 rounded-xl px-3 py-2 text-sm font-bold border transition ${
                  permission === "edit"
                    ? "bg-[#A1E3F980] dark:bg-[#A1E3F919] border-[#A1E3F919] text-black dark:text-[#43BEFF]"
                    : "border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
                }`}
              >
                ویرایش
              </button>
            </div>
          </div>

          {/* Duration */}
          <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-3">
            <div className="text-xs text-black/60 dark:text-white/70 mb-2">
              مدت اعتبار لینک
            </div>
            <select
              value={duration}
              onChange={(e) => setDuration(e.target.value)}
              className="w-full rounded-xl px-3 py-2 text-sm border border-black/10 dark:border-white/10 bg-white/70 dark:bg-[#0b1f35] outline-none"
            >
              {SHARE_DURATION_OPTIONS.map((o) => (
                <option key={o.value} value={o.value}>
                  {o.label}
                </option>
              ))}
            </select>
          </div>
        </div>

        {/* Create button */}
        <div className="flex items-center gap-2">
          <button
            type="button"
            onClick={handleCreate}
            disabled={creating || !file}
            className={`flex-1 rounded-xl px-4 py-2 text-sm font-extrabold transition ${
              creating || !file
                ? "opacity-60 cursor-not-allowed bg-black/10 dark:bg-white/10"
                : "bg-[#43BEFF] text-black hover:opacity-90"
            }`}
          >
            {creating ? "در حال ساخت لینک..." : hasLink ? "ساخت لینک جدید" : "ایجاد لینک"}
          </button>

          <button
            type="button"
            onClick={onClose}
            className="rounded-xl px-4 py-2 text-sm font-bold border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
          >
            بستن
          </button>
        </div>

        {/* Link area */}
        <div className="rounded-xl border border-black/10 dark:border-white/10 bg-white/60 dark:bg-white/5 p-3 space-y-2">
          <div className="text-xs text-black/60 dark:text-white/70">لینک دانلود</div>

          <div className="flex gap-2">
            <input
              value={effectiveLink}
              readOnly
              placeholder="اول لینک را ایجاد کنید..."
              className="flex-1 rounded-xl px-3 py-2 text-xs sm:text-sm border border-black/10 dark:border-white/10 bg-white/70 dark:bg-[#0b1f35] outline-none"
            />
            <button
              type="button"
              onClick={handleCopy}
              disabled={!hasLink || copying}
              className={`rounded-xl px-3 py-2 text-sm font-bold border transition ${
                !hasLink || copying
                  ? "opacity-60 cursor-not-allowed border-black/10 dark:border-white/10"
                  : "border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
              }`}
            >
              {copying ? "..." : "کپی"}
            </button>
          </div>

          {/* Actions */}
          <div className="flex gap-2">
            <button
              type="button"
              onClick={onRevoke}
              disabled={!state?.data?.token || revoking}
              className={`flex-1 rounded-xl px-3 py-2 text-sm font-extrabold transition ${
                !state?.data?.token || revoking
                  ? "opacity-60 cursor-not-allowed bg-black/10 dark:bg-white/10"
                  : "bg-red-500/90 text-white hover:bg-red-500"
              }`}
            >
              {revoking ? "در حال لغو..." : "لغو اشتراک‌گذاری"}
            </button>

            {hasLink && (
              <a
                href={effectiveLink}
                target="_blank"
                rel="noreferrer"
                className="flex-1 text-center rounded-xl px-3 py-2 text-sm font-extrabold border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
              >
                باز کردن لینک
              </a>
            )}
          </div>
        </div>

        <div className="text-[11px] text-black/50 dark:text-white/50 leading-5">
          بعد از ساخت لینک، می‌تونی کپی کنی یا لغوش کنی. مدت اعتبار و سطح دسترسی هنگام ساخت لینک ارسال می‌شه.
        </div>
      </div>
    </ModalShell>
  );
}
