'use client';

import { useState } from 'react';

export const EXPIRY_OPTIONS = [
  { label: '7 days', value: 7 },
  { label: '30 days', value: 30 },
  { label: '90 days', value: 90 },
];

function formatDate(iso) {
  if (!iso) return '';
  try {
    return new Intl.DateTimeFormat('en', { month: 'short', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(iso));
  } catch { return iso; }
}

function CopyButton({ text }) {
  const [copied, setCopied] = useState(false);
  function handleCopy() {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    });
  }
  return <button type="button" onClick={handleCopy} className="share-panel-copy-button">{copied ? '✓ Copied' : 'Copy link'}</button>;
}

export default function ShareLinkList({ links, expiryDays, setExpiryDays, linkLoading, onCreateLink, onRevokeLink }) {
  const activeLinks = links.filter((l) => !l.revoked);
  if (activeLinks.length === 0) {
    return (
      <section className="share-panel-section">
        <p className="share-panel-section-title">Share link</p>
        <div className="share-panel-create-row">
          <select value={expiryDays} onChange={(e) => setExpiryDays(Number(e.target.value))}>
            {EXPIRY_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
          </select>
          <button type="button" onClick={onCreateLink} disabled={linkLoading} className="share-panel-primary-button">{linkLoading ? 'Creating...' : 'Create link'}</button>
        </div>
      </section>
    );
  }

  return (
    <section className="share-panel-section">
      <p className="share-panel-section-title">Share link</p>
      <div className="share-panel-link-stack">
        {activeLinks.map((link) => {
          const linkUrl = link.token ? `${typeof window !== 'undefined' ? window.location.origin : ''}/share/${link.token}` : null;
          return (
            <div key={link.id} className="share-panel-link-card">
              <div className="share-panel-link-row">
                <span className="share-panel-link-url">{linkUrl || 'Legacy link token unavailable — create a new link'}</span>
                {linkUrl ? <CopyButton text={linkUrl} /> : null}
              </div>
              <div className="share-panel-link-meta">
                <span>{link.access_count} / {link.max_views != null ? link.max_views : 'unlimited'} views</span>
                {link.expires_at ? <span>Expires {formatDate(link.expires_at)}</span> : null}
                {link.require_email_otp === 1 ? <span>Email verification required</span> : null}
              </div>
              <button type="button" onClick={() => onRevokeLink(link.id)} className="share-panel-revoke-button">Revoke link</button>
            </div>
          );
        })}
        <button type="button" onClick={onCreateLink} disabled={linkLoading} className="share-panel-secondary-button">{linkLoading ? 'Creating...' : '+ New link'}</button>
      </div>
    </section>
  );
}
