/**
 * WordpressSyncCard — WP product sync control for the CP dashboard in embed mode.
 *
 * Shown only when:
 *   1. VITE_WP_EMBED === 'true' (embedded in WP admin)
 *   2. archerAi.wooActive === true (WooCommerce is installed + active)
 *   3. The tenant's domain matches archerAi.domain (this is the WP site)
 *
 * When WC is missing, renders an info alert prompting WooCommerce install.
 * When active, renders:
 *   - Product count + last sync timestamp
 *   - "Sync Products" button → wordpressApi.triggerSync → poll status 2s
 *   - Error banner for last failed job (not yet wired — Phase 5+ populates)
 *
 * All HTTP to WP + customer-api is already set up by the auto-connect hook
 * in _authenticated.tsx. This card only reads status + triggers sync jobs.
 *
 * (c) 2026 TWWIM UG. All rights reserved. (www.twwim.com)
 */

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

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

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

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

  // Initial load + polling when a job is active
  useEffect(() => {
    if (!shouldRender(tenantDomain)) return;

    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, tenantDomain]);

  if (!shouldRender(tenantDomain)) return null;

  if (!isWooCommerceActive()) {
    return (
      <div className="rounded-lg border border-amber-200 bg-amber-50 p-4">
        <div className="flex items-start gap-3">
          <AlertTriangle className="mt-0.5 h-5 w-5 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. The TWWIM widget still works without it.
            </p>
          </div>
        </div>
      </div>
    );
  }

  const handleSync = async () => {
    setTriggering(true);
    setError(null);
    try {
      await wordpressApi.triggerSync(tenantId);
      // Poll the new job immediately
      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));

  return (
    <div className="rounded-lg border border-gray-200 bg-white p-4">
      <div className="mb-3 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ShoppingBag className="h-5 w-5 text-cyan-600" />
          <h3 className="text-sm font-semibold text-gray-900">WooCommerce product sync</h3>
        </div>
        <button
          type="button"
          onClick={handleSync}
          disabled={isBusy}
          className="inline-flex items-center gap-1.5 rounded-lg bg-cyan-600 px-3 py-1.5 text-sm font-medium text-white hover:bg-cyan-700 disabled:cursor-not-allowed disabled:opacity-60"
        >
          {isBusy ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <RefreshCcw className="h-4 w-4" />
          )}
          {isBusy ? 'Syncing…' : 'Sync products'}
        </button>
      </div>

      <dl className="grid grid-cols-3 gap-4 text-sm">
        <div>
          <dt className="text-xs font-medium text-gray-500">Products synced</dt>
          <dd className="mt-1 text-lg font-semibold text-gray-900">{count}</dd>
        </div>
        <div>
          <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>
          <dt className="text-xs font-medium text-gray-500">Status</dt>
          <dd className="mt-1 text-sm capitalize text-gray-700">{jobStatus ?? '—'}</dd>
        </div>
      </dl>

      {status?.progress && (
        <div className="mt-3">
          <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-cyan-600 transition-all"
              style={{
                width: `${progressPercent(status.progress.processed, status.progress.total)}%`,
              }}
            />
          </div>
        </div>
      )}

      {status?.lastError && (
        <div className="mt-3 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="mt-3 rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-800">
          {error}
        </div>
      )}
    </div>
  );
}

function shouldRender(tenantDomain: string): boolean {
  if (!isWordpressEmbed()) return false;
  return tenantDomain === getWpDomain();
}

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