import { useCallback, useEffect, useRef, useState } from 'react';
import { deleteSubscriber, deleteWaitlist, fetchSubscribers, fetchWaitlists } from '../api';
import { formatAdminDate, getNotificationStatus } from '../utils';
import type { AdminData, Subscriber, WaitlistProduct } from '../types';
import { ContextualUpsell } from './ContextualUpsell';
import { __, _n, sprintf } from "@wordpress/i18n";
function getStockBadge(status?: string) {
  switch ((status || '').toLowerCase()) {
    case 'instock':
      return {
        label: __('In stock', 'stockbeacon-product-waitlists-for-woocommerce'),
        className: 'is-instock'
      };
    case 'outofstock':
      return {
        label: __('Out of stock', 'stockbeacon-product-waitlists-for-woocommerce'),
        className: 'is-outofstock'
      };
    case 'onbackorder':
      return {
        label: __('On backorder', 'stockbeacon-product-waitlists-for-woocommerce'),
        className: 'is-onbackorder'
      };
    default:
      return status ? {
        label: status.replace(/[_-]+/g, ' '),
        className: 'is-unknown'
      } : null;
  }
}
export function SubscribersTab() {
  const adminData: Partial<AdminData> = window.stockbeaconAdmin ?? {};
  const [signups, setSignups] = useState<Subscriber[]>([]);
  const [products, setProducts] = useState<WaitlistProduct[]>([]);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [dateFromFilter, setDateFromFilter] = useState('');
  const [dateToFilter, setDateToFilter] = useState('');
  const [tableStatus, setTableStatus] = useState('');
  const [exportProductId, setExportProductId] = useState('0');
  const [exportStatus, setExportStatus] = useState('');
  const [exportDateFrom, setExportDateFrom] = useState('');
  const [exportDateTo, setExportDateTo] = useState('');
  const [clearProductId, setClearProductId] = useState('0');
  const [isLoadingSubscribers, setIsLoadingSubscribers] = useState(true);
  const requestIdRef = useRef(0);
  const loadSubscribers = useCallback(async (searchVal = '', statusVal = '', fromVal = '', toVal = '') => {
    const rid = ++requestIdRef.current;
    const trimmed = searchVal.trim();
    const hasFilters = Boolean(trimmed || statusVal || fromVal || toVal);
    setIsLoadingSubscribers(true);
    setTableStatus(hasFilters ? __('Filtering subscribers…', 'stockbeacon-product-waitlists-for-woocommerce') : __('Loading subscribers…', 'stockbeacon-product-waitlists-for-woocommerce'));
    try {
      const rows = await fetchSubscribers(trimmed, 50, statusVal, fromVal, toVal);
      if (rid !== requestIdRef.current) return;
      setSignups(rows);
      setTableStatus(hasFilters ? sprintf(_n('Showing %d matching signup', 'Showing %d matching signups', rows.length, 'stockbeacon-product-waitlists-for-woocommerce'), rows.length) : '');
    } catch {
      if (rid !== requestIdRef.current) return;
      setTableStatus(__('Could not load subscribers.', 'stockbeacon-product-waitlists-for-woocommerce'));
    } finally {
      if (rid === requestIdRef.current) setIsLoadingSubscribers(false);
    }
  }, []);
  const loadProducts = useCallback(async () => {
    try {
      const rows = await fetchWaitlists(100, 1);
      setProducts(rows);
    } catch {
      setProducts([]);
    }
  }, []);
  useEffect(() => {
    loadProducts();
  }, [loadProducts]);
  useEffect(() => {
    const timer = setTimeout(() => loadSubscribers(search, statusFilter, dateFromFilter, dateToFilter), search.trim() ? 250 : 0);
    return () => clearTimeout(timer);
  }, [dateFromFilter, dateToFilter, loadSubscribers, search, statusFilter]);
  const handleSearchChange = (val: string) => {
    setSearch(val);
  };
  const handleClearTableFilters = () => {
    setSearch('');
    setStatusFilter('');
    setDateFromFilter('');
    setDateToFilter('');
  };
  const handleDeleteSubscriber = async (sub: Subscriber) => {
    if (!window.confirm(sprintf(__('Delete %s from the waitlist?', 'stockbeacon-product-waitlists-for-woocommerce'), sub.email || ''))) return;
    setTableStatus(__('Deleting subscriber…', 'stockbeacon-product-waitlists-for-woocommerce'));
    try {
      await deleteSubscriber(sub.id);
      await loadSubscribers(search, statusFilter, dateFromFilter, dateToFilter);
      await loadProducts();
      setTableStatus(__('Subscriber deleted.', 'stockbeacon-product-waitlists-for-woocommerce'));
    } catch {
      setTableStatus(__('Could not delete subscriber.', 'stockbeacon-product-waitlists-for-woocommerce'));
    }
  };
  const handleClearData = async () => {
    const pid = Number(clearProductId);
    const opt = products.find(p => p.product_id === pid)?.product_name || __('this product', 'stockbeacon-product-waitlists-for-woocommerce');
    const msg = pid === 0
      ? __('This permanently deletes every waitlist signup for all products. Continue?', 'stockbeacon-product-waitlists-for-woocommerce')
      : sprintf(__('This permanently deletes every waitlist signup for “%s”. Continue?', 'stockbeacon-product-waitlists-for-woocommerce'), opt);
    if (!window.confirm(msg)) return;
    setTableStatus(__('Clearing waitlist data…', 'stockbeacon-product-waitlists-for-woocommerce'));
    try {
      let total = 0;
      if (pid === 0) {
        let rounds = 0;
        while (true) {
          if (++rounds > 500) throw new Error('clear_limit');
          const rows = await fetchWaitlists(100, 1);
          if (!rows.length) break;
          for (const row of rows) {
            if (!row.product_id) continue;
            const res = await deleteWaitlist(row.product_id);
            total += Number(res.deleted || 0);
          }
        }
      } else {
        const res = await deleteWaitlist(pid);
        total = Number(res.deleted || 0);
      }
      setTableStatus(sprintf(_n('Removed %d signup record.', 'Removed %d signup records.', total, 'stockbeacon-product-waitlists-for-woocommerce'), total));
      await loadSubscribers(search, statusFilter, dateFromFilter, dateToFilter);
      await loadProducts();
    } catch {
      setTableStatus(__('Could not clear waitlist data.', 'stockbeacon-product-waitlists-for-woocommerce'));
    }
  };
  const handleExport = () => {
    if (!adminData.ajaxUrl || !adminData.exportNonce) return;
    const q = new URLSearchParams({
      action: 'stockbeacon_export_csv',
      nonce: adminData.exportNonce,
      product_id: exportProductId
    });
    if (exportStatus) q.set('status', exportStatus);
    if (exportDateFrom) q.set('date_from', exportDateFrom);
    if (exportDateTo) q.set('date_to', exportDateTo);
    window.location.href = adminData.ajaxUrl + '?' + q.toString();
  };
  const productOptions = [<option key="0" value="0">{__("All products", "stockbeacon-product-waitlists-for-woocommerce")}</option>, ...products.map(p => <option key={p.product_id} value={String(p.product_id)}>
				{p.product_name || sprintf(__('Product #%d', 'stockbeacon-product-waitlists-for-woocommerce'), p.product_id)}
			</option>)];
  const hasTableFilters = Boolean(search.trim() || statusFilter || dateFromFilter || dateToFilter);
  return <div id="stockbeacon-tab-subscribers" className="stockbeacon-tab-panel">
			<div className="stockbeacon-section">
				<div className="stockbeacon-section-header">
					<div>
						<strong>{__("Export subscribers (CSV)", "stockbeacon-product-waitlists-for-woocommerce")}</strong>
						<p>{__("Download waitlist subscribers by product, status, and signup date.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
					</div>
				</div>
				<p className="stockbeacon-export-row">
					<label>{__("Product", "stockbeacon-product-waitlists-for-woocommerce")}<br />
						<select className="regular-text" value={exportProductId} onChange={e => setExportProductId(e.target.value)}>
							{productOptions}
						</select>
					</label>
					<label>{__("Status", "stockbeacon-product-waitlists-for-woocommerce")}<br />
						<select className="regular-text" value={exportStatus} onChange={e => setExportStatus(e.target.value)}>
							<option value="">{__("All statuses", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="active">{__("Waiting", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="pending">{__("Pending confirmation", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="notified">{__("Notified", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="purchased">{__("Purchased", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="unsubscribed">{__("Unsubscribed", "stockbeacon-product-waitlists-for-woocommerce")}</option>
						</select>
					</label>
					<label>{__("From", "stockbeacon-product-waitlists-for-woocommerce")}<br />
						<input type="date" className="regular-text" value={exportDateFrom} onChange={e => setExportDateFrom(e.target.value)} />
					</label>
					<label>{__("To", "stockbeacon-product-waitlists-for-woocommerce")}<br />
						<input type="date" className="regular-text" value={exportDateTo} onChange={e => setExportDateTo(e.target.value)} />
					</label>
					<button type="button" className="button button-primary" onClick={handleExport}>{__("Download CSV", "stockbeacon-product-waitlists-for-woocommerce")}</button>
				</p>
				{!adminData.isPremium && <ContextualUpsell title={__("Sync exported subscribers automatically", "stockbeacon-product-waitlists-for-woocommerce")}>{__("Upgrade to sync new subscribers to your email marketing platform with restock tags so CSV export becomes a backup instead of a routine task.", "stockbeacon-product-waitlists-for-woocommerce")}</ContextualUpsell>}
			</div>

			<div className="stockbeacon-section stockbeacon-section--table">
				<div className="stockbeacon-section-header">
					<div>
						<strong>{__("Subscribers", "stockbeacon-product-waitlists-for-woocommerce")}</strong>
						<p>{__("Search, review, and remove waitlist subscribers across products.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
					</div>
					<label className="stockbeacon-search">
						<span>{__("Search email", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<input type="search" className="regular-text" placeholder={__("customer@example.com", "stockbeacon-product-waitlists-for-woocommerce")} autoComplete="off" value={search} onChange={e => handleSearchChange(e.target.value)} />
					</label>
				</div>
				<div className="stockbeacon-subscriber-filters">
					<label>
						<span>{__("Status", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<select className="regular-text" value={statusFilter} onChange={e => setStatusFilter(e.target.value)}>
							<option value="">{__("All statuses", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="active">{__("Waiting", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="pending">{__("Pending confirmation", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="notified">{__("Notified", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="purchased">{__("Purchased", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="unsubscribed">{__("Unsubscribed", "stockbeacon-product-waitlists-for-woocommerce")}</option>
						</select>
					</label>
					<label>
						<span>{__("Date from", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<input type="date" className="regular-text" value={dateFromFilter} onChange={e => setDateFromFilter(e.target.value)} />
					</label>
					<label>
						<span>{__("Date to", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<input type="date" className="regular-text" value={dateToFilter} onChange={e => setDateToFilter(e.target.value)} />
					</label>
					<button type="button" className="button" onClick={handleClearTableFilters} disabled={!hasTableFilters}>{__("Clear filters", "stockbeacon-product-waitlists-for-woocommerce")}</button>
				</div>
				<div className="stockbeacon-clear-data-row">
					<label>{__("Product", "stockbeacon-product-waitlists-for-woocommerce")}<br />
						<select className="regular-text" value={clearProductId} onChange={e => setClearProductId(e.target.value)}>
							{productOptions}
						</select>
					</label>
					<button type="button" className="button" onClick={handleClearData}>{__("Clear data", "stockbeacon-product-waitlists-for-woocommerce")}</button>
				</div>
				<p className="stockbeacon-danger-help">{__("Permanently deletes every waitlist signup for the selected product. Use CSV export first when you need a backup.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
				{tableStatus && <div className="stockbeacon-table-status" role="status">{tableStatus}</div>}
				<div className={`stockbeacon-table-wrap stockbeacon-table-wrap--steady${isLoadingSubscribers && signups.length > 0 ? ' is-refreshing' : ''}`} aria-busy={isLoadingSubscribers ? 'true' : 'false'}>
					{isLoadingSubscribers && signups.length > 0 && <div className="stockbeacon-table-loading-overlay" aria-hidden="true">
							<span className="spinner is-active" />
						</div>}
					<table className="widefat striped stockbeacon-signups-table">
						<thead>
							<tr>
								<th>{__("Email", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Product", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Product Status", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Signed Up", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Last Email", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Status", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th className="column-action"><span className="screen-reader-text">{__("Actions", "stockbeacon-product-waitlists-for-woocommerce")}</span></th>
							</tr>
						</thead>
						<tbody>
							{isLoadingSubscribers && signups.length === 0 ? Array.from({
              length: 6
            }).map((_, index) => <tr key={`subscriber-skeleton-${index}`} className="stockbeacon-skeleton-row">
										<td><span className="stockbeacon-skeleton stockbeacon-skeleton--email" /></td>
										<td><span className="stockbeacon-skeleton stockbeacon-skeleton--product" /></td>
										<td><span className="stockbeacon-skeleton stockbeacon-skeleton--badge" /></td>
										<td><span className="stockbeacon-skeleton stockbeacon-skeleton--date" /></td>
										<td><span className="stockbeacon-skeleton stockbeacon-skeleton--date" /></td>
										<td><span className="stockbeacon-skeleton stockbeacon-skeleton--badge" /></td>
										<td className="column-action"><span className="stockbeacon-skeleton stockbeacon-skeleton--icon" /></td>
									</tr>) : signups.length === 0 ? <tr className="stockbeacon-empty-row">
									<td colSpan={7}>
										<p style={{
                  margin: '0 0 4px',
                  fontWeight: 600,
                  color: '#1d2327'
                }}>
											{hasTableFilters ? 'No matching signups' : 'No waitlist signups yet'}
										</p>
										<p style={{
                  margin: 0,
                  color: '#646970',
                  fontSize: 13
                }}>
											{hasTableFilters ? 'Try changing the status, date range, or search term.' : 'New subscriber activity will appear here once customers join product waitlists.'}
										</p>
									</td>
								</tr> : signups.map(row => {
              const notif = getNotificationStatus(row.status);
              const stockBadge = getStockBadge(row.product_stock_status);
              return <tr key={row.id} data-subscriber-id={row.id}>
										<td>
											{row.edit_user_url ? <a className="stockbeacon-email-link" href={row.edit_user_url} target="_blank" rel="noopener noreferrer" title={__("View WooCommerce customer", "stockbeacon-product-waitlists-for-woocommerce")}><strong>{row.email}</strong></a> : <strong>{row.email}</strong>}
										</td>
										<td>
											<div>
												{row.product_url ? <a className="stockbeacon-product-link" href={row.product_url} target="_blank" rel="noopener noreferrer">{row.product_name || 'Product'}</a> : row.product_name || 'Product'}
												{row.variation_id ? <span className="stockbeacon-variation-id"> #{row.variation_id}</span> : null}
											</div>
										</td>
										<td>
											{stockBadge && <span className={`stockbeacon-stock-badge ${stockBadge.className}`}>
													{stockBadge.label}
												</span>}
											{!stockBadge && <span style={{
                    color: '#9ca3af'
                  }}>—</span>}
										</td>
										<td>
											<time dateTime={row.created_at || ''} title={row.created_at || ''}>
												{formatAdminDate(row.created_at)}
											</time>
										</td>
										<td>
											{row.notified_at ? <time dateTime={row.notified_at} title={row.notified_at}>{formatAdminDate(row.notified_at)}</time> : <span style={{
                    color: '#9ca3af'
                  }}>—</span>}
										</td>
										<td><span className={`stockbeacon-status-pill ${notif.className}`}>{notif.label}</span></td>
										<td className="column-action">
											<button type="button" className="button stockbeacon-delete-subscriber" aria-label={sprintf(__('Delete subscriber %s', 'stockbeacon-product-waitlists-for-woocommerce'), row.email)} title={__("Delete subscriber", "stockbeacon-product-waitlists-for-woocommerce")} onClick={() => handleDeleteSubscriber(row)}>
												<span className="dashicons dashicons-trash" aria-hidden="true" />
											</button>
										</td>
									</tr>;
            })}
						</tbody>
					</table>
				</div>
			</div>
		</div>;
}
