"use client";

import {
  useScraperHealth,
  useRotateIp,
} from "@/components/scrapers/ProxyHealthCard";

// ── Per-provider proxy section (inside provider tab) ───────────────────────

interface ProviderProxySectionProps {
  source: string;
}

export function ProviderProxySection({ source }: ProviderProxySectionProps) {
  const healthQ = useScraperHealth();
  const rotateMut = useRotateIp(source);

  const provider = healthQ.data?.providers.find((p) => p.source === source);

  if (healthQ.isPending) {
    return (
      <section className="scraper-section">
        <h2>Прокси</h2>
        <p className="scraper-hint">Загрузка…</p>
      </section>
    );
  }

  if (healthQ.isError || !provider) {
    return (
      <section className="scraper-section">
        <h2>Прокси</h2>
        <p
          className="scraper-result scraper-result--error"
          style={{ marginBottom: 0 }}
        >
          {healthQ.isError
            ? `Ошибка: ${healthQ.error.message}`
            : "Провайдер не найден в health-ответе"}
        </p>
      </section>
    );
  }

  const proxyStr =
    provider.proxy_host && provider.proxy_port
      ? `${provider.proxy_host}:${provider.proxy_port}`
      : null;

  return (
    <section className="scraper-section">
      <h2>Прокси</h2>

      <div className="schedule-status" style={{ marginBottom: 12 }}>
        <div className="schedule-status__row">
          <span className="schedule-status__label">Прокси:</span>
          <span>
            {proxyStr ? (
              <code style={{ fontSize: "0.85rem" }}>{proxyStr}</code>
            ) : (
              <span style={{ color: "var(--fg-tertiary, #73767e)" }}>
                не настроен
              </span>
            )}
          </span>
        </div>
        <div className="schedule-status__row">
          <span className="schedule-status__label">Текущий IP:</span>
          <span>
            {provider.current_ip ? (
              <code style={{ fontSize: "0.85rem" }}>
                {provider.current_ip}
              </code>
            ) : (
              <span style={{ color: "var(--fg-tertiary, #73767e)" }}>—</span>
            )}
          </span>
        </div>
        <div className="schedule-status__row">
          <span className="schedule-status__label">Режим:</span>
          <span
            style={{
              fontSize: "0.85rem",
              color: "var(--fg-secondary, #5b6066)",
            }}
          >
            {provider.rotate_supported ? "rotate-поддержка" : "статический"}
          </span>
        </div>
      </div>

      {provider.rotate_supported && (
        <div>
          <button
            type="button"
            disabled={rotateMut.isPending}
            onClick={() => rotateMut.mutate()}
          >
            {rotateMut.isPending ? "Ротируем…" : "Сменить IP"}
          </button>

          {rotateMut.isSuccess && (
            <div
              className="scraper-result"
              style={{ marginTop: 8 }}
            >
              {rotateMut.data.ok ? (
                <>
                  Новый IP: <strong>{rotateMut.data.new_ip ?? "обновлён"}</strong>
                </>
              ) : (
                <span style={{ color: "var(--danger, #b3261e)" }}>
                  {rotateMut.data.reason ?? "ошибка ротации"}
                </span>
              )}
            </div>
          )}

          {rotateMut.isError && (
            <div className="scraper-result scraper-result--error" style={{ marginTop: 8 }}>
              Ошибка: {rotateMut.error.message}
            </div>
          )}
        </div>
      )}

      {!provider.rotate_supported && (
        <p
          className="scraper-hint"
          style={{ margin: 0 }}
        >
          Ротация IP не поддерживается для этого провайдера.
        </p>
      )}
    </section>
  );
}
