import { useCallback, useEffect, useState } from 'react';
import { fetchOverview, fetchWaitlists, updateWaitlistProductVisibility } from '../api';

import type { AdminData, OverviewData, WaitlistProduct } from '../types';
import { ContextualUpsell } from './ContextualUpsell';
import { GeneralSettingsPanel } from './settings/GeneralSettingsPanel';
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 OverviewTab() {
  const adminData: Partial<AdminData> = window.stockbeaconAdmin ?? {};
  const [overview, setOverview] = useState<OverviewData | null>(null);
  
  const [productRows, setProductRows] = useState<WaitlistProduct[]>([]);
  const [loading, setLoading] = useState(true);
  const [updatingProductId, setUpdatingProductId] = useState<number | null>(null);
  const [productTableStatus, setProductTableStatus] = useState('');
  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchOverview('');
      setOverview(data);
    } catch {
      setOverview({
        total_active: 0,
        total_notified: 0,
        products_count: 0
      });
    }
    try {
      const rows = await fetchWaitlists(25, 1, 'outofstock');
      setProductRows(Array.isArray(rows) ? rows : []);
    } catch {
      setProductRows([]);
    }
    
    setLoading(false);
  }, [adminData.isPremium]);
  useEffect(() => {
    load();
  }, [load]);
  const active = Number(overview?.total_active || 0);
  const notified = Number(overview?.total_notified || 0);
  const products = Number(overview?.products_count || 0);
  const conversion = Number(overview?.conversion_rate || 0);
  const visibleOutOfStockForms = productRows.filter(row => row.waitlist_form_visible !== false && !row.waitlist_hidden).length;
  
  const handleToggleProductForm = async (row: WaitlistProduct, visible: boolean) => {
    setUpdatingProductId(row.product_id);
    const productName = row.product_name || sprintf(__('Product #%d', 'stockbeacon-product-waitlists-for-woocommerce'), row.product_id);
    setProductTableStatus(sprintf(__('Updating %s…', 'stockbeacon-product-waitlists-for-woocommerce'), productName));
    setProductRows(rows => rows.map(item => item.product_id === row.product_id ? {
      ...item,
      waitlist_form_visible: visible,
      waitlist_hidden: !visible
    } : item));
    try {
      const updated = await updateWaitlistProductVisibility(row.product_id, visible);
      setProductRows(rows => rows.map(item => item.product_id === row.product_id ? {
        ...item,
        ...updated
      } : item));
      setProductTableStatus(visible ? __('Waitlist form enabled for this product.', 'stockbeacon-product-waitlists-for-woocommerce') : __('Waitlist form hidden for this product.', 'stockbeacon-product-waitlists-for-woocommerce'));
    } catch {
      setProductRows(rows => rows.map(item => item.product_id === row.product_id ? {
        ...item,
        waitlist_form_visible: row.waitlist_form_visible,
        waitlist_hidden: row.waitlist_hidden
      } : item));
      setProductTableStatus(__('Could not update the waitlist form setting.', 'stockbeacon-product-waitlists-for-woocommerce'));
    } finally {
      setUpdatingProductId(null);
    }
  };
  return <div id="stockbeacon-tab-overview" className="stockbeacon-tab-panel">
			<div className="stockbeacon-stats-grid">
				<div className="stockbeacon-stat-card">
					<div className="stockbeacon-stat-card__label">{__("Active subscribers", "stockbeacon-product-waitlists-for-woocommerce")}</div>
					<div className="stockbeacon-stat-card__value">{loading ? '-' : String(active)}</div>
					<div className="stockbeacon-stat-card__help">{__("Customers currently waiting", "stockbeacon-product-waitlists-for-woocommerce")}</div>
				</div>
				<div className="stockbeacon-stat-card">
					<div className="stockbeacon-stat-card__label">{__("New today", "stockbeacon-product-waitlists-for-woocommerce")}</div>
					<div className="stockbeacon-stat-card__value">{loading ? '-' : String(overview?.subscribers_today ?? 0)}</div>
					<div className="stockbeacon-stat-card__help">{__("Fresh waitlist demand", "stockbeacon-product-waitlists-for-woocommerce")}</div>
				</div>
				<div className="stockbeacon-stat-card">
					<div className="stockbeacon-stat-card__label">{__("Last 7 days", "stockbeacon-product-waitlists-for-woocommerce")}</div>
					<div className="stockbeacon-stat-card__value">{loading ? '-' : String(overview?.subscribers_7d ?? 0)}</div>
					<div className="stockbeacon-stat-card__help">{__("Recent subscriber growth", "stockbeacon-product-waitlists-for-woocommerce")}</div>
				</div>
				<div className="stockbeacon-stat-card">
					<div className="stockbeacon-stat-card__label">{__("Products tracked", "stockbeacon-product-waitlists-for-woocommerce")}</div>
					<div className="stockbeacon-stat-card__value">{loading ? '-' : String(products)}</div>
					<div className="stockbeacon-stat-card__help">{__("Products with waitlist records", "stockbeacon-product-waitlists-for-woocommerce")}</div>
				</div>
				<div className="stockbeacon-stat-card">
					<div className="stockbeacon-stat-card__label">{__("Conversion rate", "stockbeacon-product-waitlists-for-woocommerce")}</div>
					<div className="stockbeacon-stat-card__value">{loading ? '-' : conversion + '%'}</div>
					<div className="stockbeacon-stat-card__help">{__("% of notified subscribers who purchased", "stockbeacon-product-waitlists-for-woocommerce")}</div>
				</div>
				<div className="stockbeacon-stat-card">
					<div className="stockbeacon-stat-card__label">{__("Emails sent", "stockbeacon-product-waitlists-for-woocommerce")}</div>
					<div className="stockbeacon-stat-card__value">{loading ? '-' : String(notified)}</div>
					<div className="stockbeacon-stat-card__help">{__("Subscribers marked notified", "stockbeacon-product-waitlists-for-woocommerce")}</div>
				</div>
			</div>

			<div className="stockbeacon-overview-layout">
				<GeneralSettingsPanel />
				<section className="stockbeacon-settings-card" aria-labelledby="stockbeacon-analytics-summary-title">
					<div className="stockbeacon-settings-card__head">
						<h3 id="stockbeacon-analytics-summary-title">{__("Analytics summary", "stockbeacon-product-waitlists-for-woocommerce")}</h3>
						<p>{__("High-level waitlist performance for demand planning and restock decisions.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
					</div>
					<div className="stockbeacon-settings-card__body">
						<div className="stockbeacon-metric-list">
							<div><span>{__("Waiting customers", "stockbeacon-product-waitlists-for-woocommerce")}</span><strong>{active}</strong></div>
							<div><span>{__("Notified customers", "stockbeacon-product-waitlists-for-woocommerce")}</span><strong>{notified}</strong></div>
							<div><span>{__("Monthly signups", "stockbeacon-product-waitlists-for-woocommerce")}</span><strong>{Number(overview?.subscribers_1m || 0)}</strong></div>
							
						</div>
						
						{!adminData.isPremium && <ContextualUpsell title={__("Product demand rankings", "stockbeacon-product-waitlists-for-woocommerce")}>{__("See which products have the most waiting, notified, and purchased customers so you can prioritize restocks.", "stockbeacon-product-waitlists-for-woocommerce")}</ContextualUpsell>}
					</div>
				</section>
			</div>

			<div className="stockbeacon-section stockbeacon-section--table">
				<div className="stockbeacon-section-header">
					<div>
						<strong>{__("Out-of-stock products", "stockbeacon-product-waitlists-for-woocommerce")}</strong>
						<p>{__("Control which sold-out products show a waitlist form, and see current demand at a glance.", "stockbeacon-product-waitlists-for-woocommerce")}</p>
					</div>
				</div>
				{productTableStatus && <div className="stockbeacon-table-status">{productTableStatus}</div>}
				<div className="stockbeacon-table-wrap stockbeacon-products-table-wrap">
					<table className="widefat striped stockbeacon-products-table">
						<thead>
							<tr>
								<th>{__("Product", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Stock", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Waitlist form", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Subscribers", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Pending", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Notified", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Inventory", "stockbeacon-product-waitlists-for-woocommerce")}</th>
								<th>{__("Actions", "stockbeacon-product-waitlists-for-woocommerce")}</th>
							</tr>
						</thead>
						<tbody>
							{productRows.length === 0 ? <tr className="stockbeacon-empty-row">
									<td colSpan={8}>{__("No out-of-stock products found.", "stockbeacon-product-waitlists-for-woocommerce")}</td>
								</tr> : productRows.map(row => {
              const stockBadge = getStockBadge(row.product_stock_status);
              const visible = row.waitlist_form_visible !== false && !row.waitlist_hidden;
              const waiting = Number(row.active_count || 0);
              const pending = Number(row.pending_count || 0);
              const total = Number(row.total_count || 0);
              return <tr key={row.product_id}>
										<td>
											{row.product_url ? <a className="stockbeacon-product-link" href={row.product_url} target="_blank" rel="noopener noreferrer">{row.product_name || sprintf(__('Product #%d', 'stockbeacon-product-waitlists-for-woocommerce'), row.product_id)}</a> : row.product_name || sprintf(__('Product #%d', 'stockbeacon-product-waitlists-for-woocommerce'), row.product_id)}
										</td>
										<td>
											{stockBadge ? <span className={`stockbeacon-stock-badge ${stockBadge.className}`}>{stockBadge.label}</span> : <span style={{
                    color: '#9ca3af'
                  }}>-</span>}
										</td>
										<td>
											<label className="stockbeacon-table-switch">
												<span className="stockbeacon-switch">
													<input type="checkbox" checked={visible} disabled={updatingProductId === row.product_id} onChange={e => handleToggleProductForm(row, e.target.checked)} />
													<span />
												</span>
												<span>{visible ? __('Shown', 'stockbeacon-product-waitlists-for-woocommerce') : __('Hidden', 'stockbeacon-product-waitlists-for-woocommerce')}</span>
											</label>
										</td>
										<td>
											<strong>{waiting}</strong>
											<span className="stockbeacon-muted-count"> / {total}{" " + __("total", "stockbeacon-product-waitlists-for-woocommerce")}</span>
										</td>
										<td>{pending}</td>
										<td>{Number(row.notified_count || 0)}</td>
										<td>
											{row.manage_stock ? sprintf(_n('%d in stock', '%d in stock', Number(row.stock_quantity ?? 0), 'stockbeacon-product-waitlists-for-woocommerce'), Number(row.stock_quantity ?? 0)) : row.sku ? sprintf(__('SKU %s', 'stockbeacon-product-waitlists-for-woocommerce'), row.sku) : <span style={{
                    color: '#9ca3af'
                  }}>-</span>}
										</td>
										<td>
											{row.edit_url ? <a className="button button-small" href={row.edit_url}>{__("Edit", "stockbeacon-product-waitlists-for-woocommerce")}</a> : <span style={{
                    color: '#9ca3af'
                  }}>-</span>}
										</td>
									</tr>;
            })}
						</tbody>
					</table>
				</div>
			</div>
		</div>;
}
