/**
 * WooCommerceSyncTab — inline WooCommerce product-sync controls.
 *
 * Mounted inside the Knowledge page tab bar (TenantPage.tsx) when running
 * in WP embed mode and WooCommerce is active on the current WP install.
 * Replaces the standalone WooCommerceSyncModal that used to live in the
 * Tenants list. Only loaded in the WP build (VITE_WP_EMBED=true) via
 * dynamic import — never bundled into the standalone CP dashboard.
 *
 * (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)
 */

import { useEffect, useState } from 'react';
import { AlertTriangle, Loader2, RefreshCcw, ShoppingBag, CheckCircle2 } from 'lucide-react';
import type { WordpressSyncStatusResponse } from '@archer/api-interface';
import { wordpressApi } from '@/infrastructure/http/api/wordpress';
import { isWooCommerceActive } from '@/lib/wp-integration';

interface WooCommerceSyncTabProps {
  tenantId: string;
  tenantDomain: string;
}

const POLL_INTERVAL_MS = 2_000;
const POLL_ACTIVE_STATES: ReadonlyArray<WordpressSyncStatusResponse['jobStatus']> = [
  'queued',
  'running',
];

export default function WooCommerceSyncTab({ tenantId, tenantDomain }: WooCommerceSyncTabProps) {
  const [status, setStatus] = useState<WordpressSyncStatusResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [triggering, setTriggering] = useState(false);

  useEffect(() => {
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout> | undefined;

    const poll = async () => {
      try {
        const next = await wordpressApi.getStatus(tenantId);
        if (cancelled) return;
        setStatus(next);
        setError(null);
        if (next.jobStatus && POLL_ACTIVE_STATES.includes(next.jobStatus)) {
          timer = setTimeout(poll, POLL_INTERVAL_MS);
        }
      } catch (err) {
        if (cancelled) return;
        setError((err as Error).message);
      }
    };

    void poll();
    return () => {
      cancelled = true;
      if (timer) clearTimeout(timer);
    };
  }, [tenantId]);

  if (!isWooCommerceActive()) {
    return (
      <div className="p-6">
        <div className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-4">
          <AlertTriangle className="mt-0.5 h-5 w-5 shrink-0 text-amber-600" />
          <div>
            <h3 className="text-sm font-semibold text-amber-900">WooCommerce not active</h3>
            <p className="mt-1 text-sm text-amber-800">
              Product sync requires WooCommerce. Install and activate WooCommerce to enable
              product knowledge sync.
            </p>
          </div>
        </div>
      </div>
    );
  }

  const handleSync = async () => {
    setTriggering(true);
    setError(null);
    try {
      await wordpressApi.triggerSync(tenantId);
      const next = await wordpressApi.getStatus(tenantId);
      setStatus(next);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setTriggering(false);
    }
  };

  const count = status?.count ?? 0;
  const lastSyncedAt = status?.lastSyncedAt
    ? new Date(status.lastSyncedAt).toLocaleString()
    : '—';
  const jobStatus = status?.jobStatus ?? null;
  const isBusy = triggering || (jobStatus !== null && POLL_ACTIVE_STATES.includes(jobStatus));
  const isIdle = jobStatus === null || jobStatus === 'idle' || jobStatus === 'completed';

  return (
    <div className="p-6 space-y-4">
      {/* Header — site domain + sync trigger */}
      <div className="flex items-center justify-between">
        <p className="text-sm text-gray-600">
          Site: <span className="font-medium text-gray-900">{tenantDomain}</span>
        </p>
        <button
          type="button"
          onClick={handleSync}
          disabled={isBusy}
          className="inline-flex items-center gap-1.5 rounded-lg bg-purple-600 px-4 py-2 text-sm font-medium text-white hover:bg-purple-700 disabled:cursor-not-allowed disabled:opacity-60 transition-colors"
        >
          {isBusy ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <RefreshCcw className="h-4 w-4" />
          )}
          {isBusy ? 'Syncing…' : 'Sync products'}
        </button>
      </div>

      {/* Stats */}
      <dl className="grid grid-cols-3 gap-4">
        <div className="rounded-lg border border-gray-200 bg-gray-50 p-3">
          <dt className="text-xs font-medium text-gray-500">Products synced</dt>
          <dd className="mt-1 flex items-center gap-1.5">
            <ShoppingBag className="h-4 w-4 text-purple-500" />
            <span className="text-lg font-semibold text-gray-900">{count}</span>
          </dd>
        </div>
        <div className="rounded-lg border border-gray-200 bg-gray-50 p-3">
          <dt className="text-xs font-medium text-gray-500">Last sync</dt>
          <dd className="mt-1 text-sm text-gray-700">{lastSyncedAt}</dd>
        </div>
        <div className="rounded-lg border border-gray-200 bg-gray-50 p-3">
          <dt className="text-xs font-medium text-gray-500">Status</dt>
          <dd className="mt-1 flex items-center gap-1.5 text-sm capitalize text-gray-700">
            {isIdle && count > 0 && <CheckCircle2 className="h-4 w-4 text-green-500" />}
            {isBusy && <Loader2 className="h-4 w-4 animate-spin text-purple-500" />}
            {jobStatus ?? '—'}
          </dd>
        </div>
      </dl>

      {/* Progress bar */}
      {status?.progress && (
        <div>
          <div className="mb-1 flex justify-between text-xs text-gray-500">
            <span className="capitalize">{status.progress.phase}</span>
            <span>{status.progress.processed} / {status.progress.total}</span>
          </div>
          <div className="h-2 w-full overflow-hidden rounded-full bg-gray-100">
            <div
              className="h-full bg-purple-600 transition-all"
              style={{ width: `${progressPercent(status.progress.processed, status.progress.total)}%` }}
            />
          </div>
        </div>
      )}

      {/* Error */}
      {status?.lastError && (
        <div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800">
          <strong>Last sync failed ({status.lastError.code}):</strong> {status.lastError.message}
        </div>
      )}
      {error && !status?.lastError && (
        <div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800">
          {error}
        </div>
      )}
    </div>
  );
}

function progressPercent(processed: number, total: number): number {
  if (!total || total <= 0) return 0;
  return Math.min(100, Math.round((processed / total) * 100));
}
