// HWID Reset Portal & Link Management Component
window.HwidLinksPage = function HwidLinksPage({ user, apps, showToast }) {
  const [links, setLinks] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [showCreateModal, setShowCreateModal] = React.useState(false);
  const [copiedToken, setCopiedToken] = React.useState('');

  // Form State
  const [linkTitle, setLinkTitle] = React.useState('');
  const [targetAppId, setTargetAppId] = React.useState('all');
  const [maxResets, setMaxResets] = React.useState(0);
  const [durationDays, setDurationDays] = React.useState('');
  const [linkNote, setLinkNote] = React.useState('');
  const [submitting, setSubmitting] = React.useState(false);

  // History modal
  const [selectedLinkHistory, setSelectedLinkHistory] = React.useState(null);

  const fetchLinks = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/hwid-links', {
        headers: { 'Authorization': `Bearer ${localStorage.getItem('icex_token')}` }
      });
      const data = await res.json();
      if (data.success) {
        setLinks(data.links || []);
      }
    } catch (err) {
      console.error('Fetch HWID links error:', err);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    fetchLinks();
  }, []);

  const handleCreateLink = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      const res = await fetch('/api/hwid-links/create', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({
          title: linkTitle,
          app_id: targetAppId,
          max_resets: maxResets,
          duration_days: durationDays,
          note: linkNote
        })
      });
      const data = await res.json();
      if (data.success) {
        showToast('สร้างลิงก์ Reset HWID สำเร็จแล้ว!', 'success');
        setShowCreateModal(false);
        setLinkTitle('');
        setMaxResets(0);
        setDurationDays('');
        setLinkNote('');
        fetchLinks();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error creating link: ' + err.message, 'error');
    } finally {
      setSubmitting(false);
    }
  };

  const handleToggleStatus = async (id) => {
    try {
      const res = await fetch('/api/hwid-links/toggle-status', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ id })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchLinks();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error toggling status', 'error');
    }
  };

  const handleDeleteLink = async (id, title) => {
    if (!confirm(`ลบลิงก์ Reset HWID '${title}' ถาวรหรือไม่?`)) return;
    try {
      const res = await fetch('/api/hwid-links/delete', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('icex_token')}`
        },
        body: JSON.stringify({ id })
      });
      const data = await res.json();
      if (data.success) {
        showToast(data.message, 'success');
        fetchLinks();
      } else {
        showToast(data.message, 'error');
      }
    } catch (err) {
      showToast('Error deleting link', 'error');
    }
  };

  const getDirectUrl = (token) => {
    return `${window.location.origin}/reset-hwid.html?token=${encodeURIComponent(token)}`;
  };

  return (
    <div className="space-y-6 animate-card-in">
      {/* Header */}
      <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 pb-4 border-b border-[#1E2D4A]">
        <div>
          <h2 className="text-xl font-bold text-white font-brand flex items-center gap-2.5">
            <i className="fa-solid fa-link text-cyan-400"></i>
            <span>ระบบสร้างลิงก์ Reset HWID (HWID Reset Portal Links)</span>
          </h2>
          <p className="text-xs text-slate-400 mt-0.5">
            สร้างลิงก์เฉพาะส่งให้ตัวแทนหรือลูกค้า เพื่อให้สามารถกดรีเซ็ต HWID ด้วยตนเองได้โดยไม่ต้องเข้าพาเนล
          </p>
        </div>

        <div className="flex items-center gap-2.5 w-full sm:w-auto">
          <button
            onClick={() => setShowCreateModal(true)}
            className="flex-1 sm:flex-initial px-4 py-2.5 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white font-semibold text-xs transition flex items-center justify-center gap-2 border border-[#1D63FF] cyber-btn-interactive"
          >
            <i className="fa-solid fa-plus text-xs"></i>
            <span>สร้างลิงก์ Reset HWID ใหม่</span>
          </button>
          <button
            onClick={fetchLinks}
            className="p-2.5 rounded-none bg-[#131D31] hover:bg-[#18243D] border border-[#1E2D4A] text-slate-300 text-xs transition"
            title="รีเฟรช"
          >
            <i className={`fa-solid fa-rotate-right text-xs ${loading ? 'fa-spin text-cyan-400' : ''}`}></i>
          </button>
        </div>
      </div>

      {/* Info Banner */}
      <div className="p-4 rounded-none bg-[#0E1626] border border-cyan-500/30 flex items-start gap-3 text-xs text-slate-300 shadow-xl">
        <i className="fa-solid fa-circle-info text-cyan-400 text-base mt-0.5 shrink-0"></i>
        <div className="space-y-1">
          <div className="font-bold text-white font-mono">วิธีใช้งานลิงก์ Reset HWID สาธารณะ:</div>
          <p className="text-slate-400">
            เมื่อกด "สร้างลิงก์" คุณจะได้ URL เฉพาะ เช่น <code className="text-cyan-300 bg-[#080C14] px-1.5 py-0.5 border border-[#1E2D4A]">https://icexmodz.duckdns.org/reset-hwid.html?token=...</code> สามารถส่งลิงก์นี้ให้ตัวแทนหรือลูกค้า เมื่อเปิดแล้วเพียงกรอก Username หรือ License Key แล้วกดรีเซ็ต ระบบจะปลดล็อคเครื่องให้อัตโนมัติทันที
          </p>
        </div>
      </div>

      {/* Links Grid */}
      <div className="grid grid-cols-1 gap-4">
        {links && links.length > 0 ? (
          links.map((link) => {
            const directUrl = getDirectUrl(link.token);
            const isCopied = copiedToken === link.token;
            const now = Date.now();
            const isExpired = link.expires_at && now > link.expires_at;

            return (
              <div
                key={link.id}
                className="p-5 rounded-none bg-[#0E1626] border border-[#1E2D4A] flex flex-col lg:flex-row lg:items-center justify-between gap-4 hover:border-cyan-500/40 transition shadow-xl"
              >
                {/* Left info */}
                <div className="space-y-2.5 flex-1 min-w-0">
                  <div className="flex items-center gap-2.5 flex-wrap">
                    <span className="font-bold text-white text-base font-brand">{link.title}</span>
                    <span className={`text-[10px] font-mono px-2 py-0.5 rounded-none ${
                      isExpired
                        ? 'bg-rose-500/10 text-rose-400 border border-rose-500/20'
                        : link.status === 'active'
                        ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20'
                        : 'bg-amber-500/10 text-amber-400 border border-amber-500/20'
                    }`}>
                      {isExpired ? 'EXPIRED' : link.status.toUpperCase()}
                    </span>
                    <span className="text-[10px] font-mono px-2 py-0.5 rounded-none bg-blue-500/10 text-blue-400 border border-blue-500/20">
                      แอป: {link.app_name}
                    </span>
                  </div>

                  {/* URL copy box */}
                  <div className="flex items-center gap-2 max-w-2xl">
                    <input
                      type="text"
                      readOnly
                      value={directUrl}
                      className="flex-1 px-3 py-1.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-xs text-slate-300 font-mono outline-none select-all"
                    />
                    <button
                      onClick={() => {
                        navigator.clipboard.writeText(directUrl);
                        setCopiedToken(link.token);
                        setTimeout(() => setCopiedToken(''), 2000);
                        showToast('คัดลอกลิงก์ Reset HWID แล้ว!', 'success');
                      }}
                      className="px-3 py-1.5 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white text-xs font-mono shrink-0 transition flex items-center gap-1.5 cyber-btn-interactive"
                    >
                      <i className={`fa-solid ${isCopied ? 'fa-check text-emerald-300' : 'fa-copy'} text-xs`}></i>
                      <span>{isCopied ? 'Copied' : 'Copy'}</span>
                    </button>
                    <a
                      href={directUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="p-1.5 px-2.5 rounded-none bg-[#131D31] hover:bg-[#18243D] text-cyan-400 border border-[#1E2D4A] text-xs font-mono shrink-0 transition"
                      title="เปิดหน้าเว็บในแท็บใหม่"
                    >
                      <i className="fa-solid fa-arrow-up-right-from-square text-xs"></i>
                    </a>
                  </div>

                  <div className="flex items-center gap-4 text-[11px] text-slate-400 font-mono flex-wrap">
                    <span>ผู้สร้าง: <strong className="text-white">{link.created_by}</strong></span>
                    <span>ใช้ไปแล้ว: <strong className="text-cyan-400">{link.used_resets}</strong> {link.max_resets > 0 ? `/ ${link.max_resets}` : '(ไม่จำกัด)'}</span>
                    {link.expires_at && (
                      <span>หมดอายุ: <strong className="text-amber-400">{new Date(link.expires_at).toLocaleDateString()}</strong></span>
                    )}
                    {link.note && <span>โน้ต: <em>{link.note}</em></span>}
                  </div>
                </div>

                {/* Actions */}
                <div className="flex items-center gap-2 border-t lg:border-t-0 lg:border-l border-[#1E2D4A] pt-3 lg:pt-0 lg:pl-5 shrink-0">
                  <button
                    onClick={() => setSelectedLinkHistory(link)}
                    className="px-3 py-2 rounded-none bg-[#080C14] hover:bg-[#131D31] border border-[#1E2D4A] text-slate-300 hover:text-white text-xs font-mono transition flex items-center gap-1.5"
                    title="ดูประวัติคนที่มารีเซ็ต"
                  >
                    <i className="fa-solid fa-clock-rotate-left text-cyan-400 text-xs"></i>
                    <span>ประวัติ ({link.history?.length || 0})</span>
                  </button>

                  <button
                    onClick={() => handleToggleStatus(link.id)}
                    className={`p-2 rounded-none border text-xs font-mono transition ${
                      link.status === 'active'
                        ? 'bg-[#080C14] border-[#1E2D4A] text-slate-300 hover:text-amber-400'
                        : 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'
                    }`}
                    title={link.status === 'active' ? 'พักการใช้งานลิงก์' : 'เปิดใช้งานลิงก์'}
                  >
                    <i className={`fa-solid ${link.status === 'active' ? 'fa-pause' : 'fa-play'} text-xs`}></i>
                  </button>

                  <button
                    onClick={() => handleDeleteLink(link.id, link.title)}
                    className="p-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-400 hover:text-rose-400 transition"
                    title="ลบลิงก์นี้"
                  >
                    <i className="fa-solid fa-trash text-xs"></i>
                  </button>
                </div>
              </div>
            );
          })
        ) : (
          <div className="text-center py-12 rounded-none bg-[#0E1626] border border-[#1E2D4A] text-slate-500 font-mono text-xs">
            ยังไม่มีลิงก์ Reset HWID ในระบบ &mdash; กดปุ่ม "สร้างลิงก์ Reset HWID ใหม่" ด้านบนเพื่อเริ่มสร้าง
          </div>
        )}
      </div>

      {/* CREATE LINK MODAL */}
      <window.Modal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        title="สร้างลิงก์ Reset HWID ใหม่ (Generate HWID Portal Link)"
        icon="fa-link"
      >
        <form onSubmit={handleCreateLink} className="space-y-4">
          <div>
            <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
              ชื่อลิงก์ / หมายเหตุจำแนก *
            </label>
            <input
              type="text"
              required
              value={linkTitle}
              onChange={(e) => setLinkTitle(e.target.value)}
              placeholder="เช่น ลิงก์รีเซ็ตตัวแทน A, ลิงก์ลูกค้ากลุ่ม VIP"
              className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
            />
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                แอปพลิเคชันที่อนุญาต *
              </label>
              <select
                value={targetAppId}
                onChange={(e) => setTargetAppId(e.target.value)}
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
              >
                {user.role === 'owner' && (
                  <option value="all">ทุกแอปพลิเคชัน (All Apps)</option>
                )}
                {apps && apps.map(app => (
                  <option key={app.id} value={app.id}>{app.name}</option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                จำกัดจำนวนครั้งที่รีเซ็ตได้ (0 = ไม่จำกัด)
              </label>
              <input
                type="number"
                min="0"
                value={maxResets}
                onChange={(e) => setMaxResets(parseInt(e.target.value) || 0)}
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
              />
            </div>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3.5">
            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                อายุการใช้งานลิงก์ (วัน) (ว่างไว้ = ถาวร)
              </label>
              <input
                type="number"
                min="1"
                value={durationDays}
                onChange={(e) => setDurationDays(e.target.value)}
                placeholder="เช่น 7 หรือ 30"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none font-mono"
              />
            </div>

            <div>
              <label className="block text-xs font-medium text-slate-300 mb-1 font-mono">
                โน้ตเพิ่มเติม
              </label>
              <input
                type="text"
                value={linkNote}
                onChange={(e) => setLinkNote(e.target.value)}
                placeholder="บันทึกข้อความภายใน"
                className="w-full px-3.5 py-2.5 rounded-none bg-[#080C14] border border-[#1E2D4A] text-sm text-white focus:border-[#1D63FF] outline-none"
              />
            </div>
          </div>

          <div className="flex justify-end gap-2.5 pt-3 border-t border-[#1E2D4A]">
            <button
              type="button"
              onClick={() => setShowCreateModal(false)}
              className="px-4 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300 text-xs font-mono"
            >
              ยกเลิก
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="px-5 py-2 rounded-none bg-[#1D63FF] hover:bg-[#3878FF] text-white text-xs font-semibold font-mono border border-[#1D63FF] cyber-btn-interactive disabled:opacity-50"
            >
              {submitting ? 'กำลังสร้าง...' : 'สร้างลิงก์ทันที'}
            </button>
          </div>
        </form>
      </window.Modal>

      {/* HISTORY MODAL */}
      <window.Modal
        isOpen={Boolean(selectedLinkHistory)}
        onClose={() => setSelectedLinkHistory(null)}
        title={`ประวัติการรีเซ็ตของ: ${selectedLinkHistory?.title}`}
        icon="fa-clock-rotate-left"
        maxWidth="max-w-2xl"
      >
        <div className="space-y-3 font-mono text-xs">
          {selectedLinkHistory?.history && selectedLinkHistory.history.length > 0 ? (
            <div className="max-h-72 overflow-y-auto border border-[#1E2D4A] divide-y divide-[#1E2D4A]/50 bg-[#080C14] custom-scroll">
              {selectedLinkHistory.history.map((h, idx) => (
                <div key={idx} className="p-3 flex items-center justify-between gap-3 text-xs">
                  <div>
                    <div className="text-white font-bold">{h.username}</div>
                    <div className="text-[11px] text-slate-500">{new Date(h.timestamp).toLocaleString()}</div>
                  </div>
                  <div className="text-right">
                    <div className="text-cyan-400">{h.ip}</div>
                    <div className="text-[10px] text-slate-500">HWID เก่า: {h.previous_hwid || 'None'}</div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="text-center py-8 text-slate-500">
              ยังไม่มีประวัติการกดรีเซ็ตผ่านลิงก์นี้
            </div>
          )}

          <div className="flex justify-end pt-2">
            <button
              type="button"
              onClick={() => setSelectedLinkHistory(null)}
              className="px-4 py-2 rounded-none bg-[#080C14] border border-[#1E2D4A] text-slate-300 text-xs"
            >
              ปิดหน้าต่าง
            </button>
          </div>
        </div>
      </window.Modal>
    </div>
  );
};
