import React, { useMemo } from "react";
import {
  LuCheck,
  LuClock,
  LuCopy,
  LuShieldCheck,
  LuStar,
  LuTrash2,
  LuX,
} from "react-icons/lu";
import { cn, fmtDate } from "../../utils/domains";

function statusBadge(domain) {
  const verified = !!domain?.is_verified;
  const active = domain?.is_active === true;
  const prov = String(domain?.provision_status || "").toLowerCase();

  if (verified) {
    return {
      label: "تاییدشده",
      cls: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-200",
      icon: <LuShieldCheck className="w-4 h-4" />,
    };
  }

  if (!active) {
    return {
      label: "غیرفعال",
      cls: "border-yellow-500/30 bg-yellow-500/10 text-yellow-800 dark:text-yellow-200",
      icon: <LuClock className="w-4 h-4" />,
    };
  }

  if (prov === "pending") {
    return {
      label: "در انتظار",
      cls: "border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-200",
      icon: <LuClock className="w-4 h-4" />,
    };
  }

  return {
    label: "تأیید نشده",
    cls: "border-black/10 bg-black/5 text-black/60 dark:border-white/10 dark:bg-white/10 dark:text-white/70",
    icon: <LuX className="w-4 h-4" />,
  };
}

function MiniIconBtn({ title, onClick, children }) {
  return (
    <button
      type="button"
      onClick={onClick}
      title={title}
      className="p-2 rounded-xl shadow border border-black/10 dark:border-white/10 bg-white/70 dark:bg-white/10 hover:dark:bg-white/20 hover:bg-white transition"
    >
      {children}
    </button>
  );
}

function ActionBtn({ title, onClick, disabled, className, children }) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      title={title}
      className={cn(
        "w-full px-3 py-2 rounded-xl shadow border text-xs flex items-center justify-center gap-2 transition",
        "disabled:opacity-50 disabled:cursor-not-allowed disabled:pointer-events-none",
        className
      )}
    >
      {children}
    </button>
  );
}

export default function DomainRow({
  domain,
  isSelected,
  onSelect,

  onCopyTxtName,
  onCopyTxtValue,

  onVerify,
  verifyLeftSec,
  verifyInFlight,

  onToggleActive,
  onTogglePrimary,
  onDelete,
  patchBusy,
  deleteBusy,
  deleteArmedLeftSec,
}) {
  const badge = useMemo(() => statusBadge(domain), [domain]);
  const left = verifyLeftSec || 0;

  const verified = !!domain?.is_verified;
  const active = domain?.is_active === true;

  // پشتیبانی از هر دو حالت خروجی API
  const primary = domain?.primary === true || domain?.is_primary === true;

  const armed = (deleteArmedLeftSec || 0) > 0;

  const primaryBtnDisabled = !verified || patchBusy || primary;

  return (
    <button
      type="button"
      onClick={onSelect}
      className={cn(
        "w-full text-right p-4 rounded-2xl shadow border transition",
        isSelected
          ? "border-[#43BEFF] bg-[#43BEFF10]"
          : "border-black/10 dark:border-white/10 bg-[#f2f2f2] dark:bg-[#001F3F] hover:bg-black/5 dark:hover:bg-white/10"
      )}
    >
      <div className="flex flex-col md:flex-row gap-4 md:justify-between">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2 flex-wrap">
            <div className="font-extrabold text-sm truncate text-black dark:text-white">
              {domain?.hostname}
            </div>

            <span
              className={cn(
                "inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs border",
                badge.cls
              )}
            >
              {badge.icon}
              {badge.label}
            </span>

            {primary && (
              <span className="inline-flex items-center gap-1 text-[11px] px-2.5 py-1 rounded-full border border-yellow-500/25 bg-yellow-500/15 text-yellow-800 dark:text-yellow-200">
                <LuStar className="w-4 h-4 text-yellow-500 fill-current" />
                دامنه اصلی
              </span>
            )}
          </div>

          <div className="mt-2 text-xs text-black/60 dark:text-white/70 flex flex-wrap gap-3">
            <span>تاریخ ثبت: {fmtDate(domain?.created_at)}</span>
            <span>تاریخ تأیید: {fmtDate(domain?.verified_at)}</span>
          </div>
        </div>

        <div
          className="w-full md:w-[380px]"
          onClick={(e) => e.stopPropagation()}
        >
          <div className="flex justify-end gap-2">
            <MiniIconBtn title="کپی نام TXT" onClick={onCopyTxtName}>
              <LuCopy className="w-4 h-4" />
            </MiniIconBtn>

            <MiniIconBtn title="کپی مقدار TXT" onClick={onCopyTxtValue}>
              <LuCopy className="w-4 h-4" />
            </MiniIconBtn>
          </div>

          <div className="mt-2 grid grid-cols-2 lg:grid-cols-4 gap-2">
            <ActionBtn
              onClick={onVerify}
              disabled={verifyInFlight || left > 0 || verified}
              title={verified ? "قبلاً تأیید شده" : "تأیید دامنه"}
              className="bg-white/70 dark:bg-white/10 border-black/10 dark:border-white/10"
            >
              <LuCheck className="w-4 h-4 text-[#43BEFF]" />
              {verified
                ? "تأییدشده"
                : verifyInFlight
                ? "در حال بررسی…"
                : left > 0
                ? `صبر (${left}s)`
                : "تأیید"}
            </ActionBtn>

            <ActionBtn
              onClick={onToggleActive}
              disabled={!verified || patchBusy}
              title={
                !verified
                  ? "ابتدا دامنه را تأیید کن"
                  : patchBusy
                  ? "در حال انجام..."
                  : active
                  ? "غیرفعال کردن دامنه"
                  : "فعال کردن دامنه"
              }
              className={
                active
                  ? "bg-green-500/15 border-green-500/30 text-green-700 dark:text-green-200"
                  : "bg-white/70 dark:bg-white/10 border-black/10 dark:border-white/10"
              }
            >
              {patchBusy ? "…" : active ? "فعال" : "فعالسازی"}
            </ActionBtn>

            <ActionBtn
              onClick={onTogglePrimary}
              disabled={primaryBtnDisabled}
              title={
                primary
                  ? "این دامنه در حال حاضر دامنه اصلی است"
                  : !verified
                  ? "ابتدا دامنه را تأیید کن"
                  : patchBusy
                  ? "در حال انجام..."
                  : "انتخاب به عنوان دامنه اصلی"
              }
              className={
                primary
                  ? "bg-yellow-500/15 border-yellow-500/30 text-yellow-700 dark:text-yellow-200"
                  : "bg-white/70 dark:bg-white/10 border-black/10 dark:border-white/10"
              }
            >
              <LuStar
                className={cn(
                  "w-4 h-4 transition",
                  primary
                    ? "text-yellow-500 fill-current"
                    : "text-black/70 dark:text-white/80"
                )}
              />
              {patchBusy ? "…" : primary ? "اصلی" : "اصلی"}
            </ActionBtn>

            <ActionBtn
              onClick={onDelete}
              disabled={deleteBusy}
              title="حذف دامنه"
              className={
                armed
                  ? "bg-red-500/15 border-red-500/30 text-red-700 dark:text-red-200"
                  : "bg-white/70 dark:bg-white/10 border-black/10 dark:border-white/10"
              }
            >
              <LuTrash2 className="w-4 h-4" />
              {deleteBusy ? "در حال حذف…" : armed ? "تأیید حذف" : "حذف"}
            </ActionBtn>
          </div>
        </div>
      </div>
    </button>
  );
}
