import { useEffect, useState } from 'react';
import { fetchActivityLogs } from '../api';
import { formatAdminDate } from '../utils';
import type { ActivityLogRow } from '../types';
import { __, _n, sprintf } from "@wordpress/i18n";
type ActivityMeta = {
  email?: string;
  email_type?: string;
  subject?: string;
  delivery_status?: string;
  delivery_error?: string;
  product_name?: string;
  product_url?: string;
  product_id?: number | string;
};
const EVENT_LABELS: Record<string, string> = {
  subscribed: __('Subscribed', 'stockbeacon-product-waitlists-for-woocommerce'),
  notified: __('Restock email sent', 'stockbeacon-product-waitlists-for-woocommerce'),
  purchased: __('Purchased', 'stockbeacon-product-waitlists-for-woocommerce'),
  unsubscribed: __('Unsubscribed', 'stockbeacon-product-waitlists-for-woocommerce'),
  confirmed: __('Confirmed', 'stockbeacon-product-waitlists-for-woocommerce')
};
const EMAIL_TYPE_LABELS: Record<string, string> = {
  restock: __('Restock email', 'stockbeacon-product-waitlists-for-woocommerce'),
  confirmation: __('Confirmation email', 'stockbeacon-product-waitlists-for-woocommerce'),
  test: __('Test email', 'stockbeacon-product-waitlists-for-woocommerce')
};
const PAGE_SIZE = 25;
const STATUS_PILLS: Record<string, {
  label: string;
  className: string;
}> = {
  active: {
    label: __('Waiting', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-waiting'
  },
  waiting: {
    label: __('Waiting', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-waiting'
  },
  pending: {
    label: __('Pending', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-pending'
  },
  confirmed: {
    label: __('Confirmed', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-delivered'
  },
  notified: {
    label: __('Notified', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-notified'
  },
  delivered: {
    label: __('Delivered', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-delivered'
  },
  purchased: {
    label: __('Purchased', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-purchased'
  },
  unsubscribed: {
    label: __('Unsubscribed', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-unsubscribed'
  },
  failed: {
    label: __('Delivery issue', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-delivery-issue'
  },
  error: {
    label: __('Delivery issue', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: 'is-delivery-issue'
  }
};
function parseMeta(row: ActivityLogRow): ActivityMeta {
  if (!row.metadata_json) return {};
  try {
    const parsed = JSON.parse(row.metadata_json) as unknown;
    return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed as ActivityMeta : {};
  } catch {
    return {};
  }
}
function isEmailEvent(eventType: string) {
  return eventType.startsWith('email_');
}
function getEmailType(row: ActivityLogRow, meta: ActivityMeta) {
  if (meta.email_type) return meta.email_type;
  if (row.event_type.includes('confirm')) return 'confirmation';
  if (row.event_type.includes('test')) return 'test';
  return 'restock';
}
function getEventLabel(row: ActivityLogRow, meta: ActivityMeta) {
  if (!isEmailEvent(row.event_type)) return EVENT_LABELS[row.event_type] || row.event_type;
  return EMAIL_TYPE_LABELS[getEmailType(row, meta)] || __('Email', 'stockbeacon-product-waitlists-for-woocommerce');
}
function getDeliveryStatus(row: ActivityLogRow, meta: ActivityMeta) {
  if (!isEmailEvent(row.event_type)) return null;
  const failed = meta.delivery_status === 'failed' || row.event_type.endsWith('_failed') || row.event_type.endsWith('_fail');
  return {
    label: failed ? __('Delivery issue', 'stockbeacon-product-waitlists-for-woocommerce') : __('Delivered', 'stockbeacon-product-waitlists-for-woocommerce'),
    className: failed ? 'is-delivery-issue' : 'is-delivered',
    detail: failed ? meta.delivery_error || __('WordPress mailer reported a problem.', 'stockbeacon-product-waitlists-for-woocommerce') : ''
  };
}
function getStatusPill(status?: string) {
  const raw = String(status || '').trim();
  if (!raw) return null;
  const normalized = raw.toLowerCase().replace(/[\s-]+/g, '_');
  const mapped = STATUS_PILLS[normalized];
  if (mapped) return mapped;
  return {
    label: raw.replace(/[_-]+/g, ' ').replace(/\b\w/g, char => char.toUpperCase()),
    className: 'is-neutral'
  };
}
export function ActivityLogTab() {
  const [rows, setRows] = useState<ActivityLogRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState('');
  const [search, setSearch] = useState('');
  const [typeFilter, setTypeFilter] = useState('');
  const [deliveryFilter, setDeliveryFilter] = useState('');
  const [page, setPage] = useState(1);
  const [hasNextPage, setHasNextPage] = useState(false);
  useEffect(() => {
    setPage(1);
  }, [search, typeFilter, deliveryFilter]);
  useEffect(() => {
    let cancelled = false;
    const timer = window.setTimeout(() => {
      setLoading(true);
      setStatus(__('Loading activity…', 'stockbeacon-product-waitlists-for-woocommerce'));
      fetchActivityLogs(PAGE_SIZE + 1, page, search, typeFilter, deliveryFilter).then(data => {
        if (cancelled) return;
        const nextRows = Array.isArray(data) ? data : [];
        setHasNextPage(nextRows.length > PAGE_SIZE);
        setRows(nextRows.slice(0, PAGE_SIZE));
        setStatus('');
      }).catch(() => {
        if (cancelled) return;
        setRows([]);
        setHasNextPage(false);
        setStatus(__('Could not load activity.', 'stockbeacon-product-waitlists-for-woocommerce'));
      }).finally(() => {
        if (!cancelled) setLoading(false);
      });
    }, search.trim() ? 250 : 0);
    return () => {
      cancelled = true;
      window.clearTimeout(timer);
    };
  }, [page, search, typeFilter, deliveryFilter]);
  return <div id="stockbeacon-tab-activity" className="stockbeacon-tab-panel">
			<div className="stockbeacon-section stockbeacon-section--table">
				<div className="stockbeacon-section-header">
					<div>
						<strong>{__("Activity Log", "stockbeacon-product-waitlists-for-woocommerce")}</strong>
						<p>{__("Recent waitlist events, including signups, email delivery, confirmations, purchases, and unsubscribes.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
					</div>
				</div>
				<div className="stockbeacon-activity-controls">
					<label className="stockbeacon-search-field">
						<span>{__("Search activity", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<input type="search" value={search} onChange={event => setSearch(event.target.value)} placeholder={__("Email, product, subject, or event", "stockbeacon-product-waitlists-for-woocommerce")} />
					</label>
					<label>
						<span>{__("Event type", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<select value={typeFilter} onChange={event => setTypeFilter(event.target.value)}>
							<option value="">{__("All events", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="email">{__("Email activity", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="subscription">{__("Subscriptions", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="restock">{__("Restocks", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="purchase">{__("Purchases", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="test">{__("Test emails", "stockbeacon-product-waitlists-for-woocommerce")}</option>
						</select>
					</label>
					<label>
						<span>{__("Email status", "stockbeacon-product-waitlists-for-woocommerce")}</span>
						<select value={deliveryFilter} onChange={event => setDeliveryFilter(event.target.value)}>
							<option value="">{__("Any status", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="delivered">{__("Delivered", "stockbeacon-product-waitlists-for-woocommerce")}</option>
							<option value="failed">{__("Delivery issue", "stockbeacon-product-waitlists-for-woocommerce")}</option>
						</select>
					</label>
				</div>
				{status && <div className="stockbeacon-table-status">{status}</div>}
				<div className="stockbeacon-table-wrap">
					<table className="widefat striped stockbeacon-signups-table stockbeacon-activity-table">
						<thead>
							<tr>
								<th>{__("Event", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Email", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Product", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Status", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Date", "stockbeacon-product-waitlists-for-woocommerce")}</th>
							</tr>
						</thead>
						<tbody>
							{!loading && rows.length === 0 ? <tr className="stockbeacon-empty-row">
									<td colSpan={5}>
										<p style={{
                  margin: '0 0 4px',
                  fontWeight: 600,
                  color: '#1d2327'
                }}>{__("No activity yet", "stockbeacon-product-waitlists-for-woocommerce")}</p>
										<p style={{
                  margin: 0,
                  color: '#646970',
                  fontSize: 13
                }}>{__("Try adjusting the search or filters, or send a test email to add a delivery record.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
									</td>
								</tr> : rows.map(row => {
              const meta = parseMeta(row);
              const delivery = getDeliveryStatus(row, meta);
              const statusPill = getStatusPill(row.status);
              const email = meta.email || row.email || '-';
              const productId = meta.product_id || row.product_id;
              const productName = meta.product_name || row.product_name || (productId ? sprintf(__('Product #%s', 'stockbeacon-product-waitlists-for-woocommerce'), productId) : '-');
              const productUrl = meta.product_url || row.product_url || '';
              return <tr key={row.id}>
										<td>
											<strong>{getEventLabel(row, meta)}</strong>
											{meta.subject && <span className="stockbeacon-activity-detail" title={meta.subject}>{meta.subject}</span>}
										</td>
										<td>{email}</td>
										<td>
											{productUrl && productName !== '-' ? <a className="stockbeacon-product-link" href={productUrl} target="_blank" rel="noopener noreferrer">{productName}</a> : productName}
										</td>
										<td>
											{delivery ? <>
													<span className={`stockbeacon-status-pill ${delivery.className}`}>{delivery.label}</span>
													{delivery.detail && <span className="stockbeacon-activity-detail" title={delivery.detail}>{delivery.detail}</span>}
												</> : statusPill ? <span className={`stockbeacon-status-pill ${statusPill.className}`}>{statusPill.label}</span> : '-'}
										</td>
										<td><time dateTime={row.created_at || ''}>{formatAdminDate(row.created_at)}</time></td>
									</tr>;
            })}
						</tbody>
					</table>
				</div>
				<div className="stockbeacon-table-pagination" aria-label={__("Activity log pagination", "stockbeacon-product-waitlists-for-woocommerce")}>
					<span>{__("Page", "stockbeacon-product-waitlists-for-woocommerce") + " "}{page}
						{rows.length > 0 ? ` | ${sprintf(_n('%d shown', '%d shown', rows.length, 'stockbeacon-product-waitlists-for-woocommerce'), rows.length)}` : ''}
					</span>
					<div>
						<button type="button" className="button" onClick={() => setPage(current => Math.max(1, current - 1))} disabled={loading || page <= 1}>{__("Previous", "stockbeacon-product-waitlists-for-woocommerce")}</button>
						<button type="button" className="button" onClick={() => setPage(current => current + 1)} disabled={loading || !hasNextPage}>{__("Next", "stockbeacon-product-waitlists-for-woocommerce")}</button>
					</div>
				</div>
			</div>
		</div>;
}
