import React, { useCallback, useEffect, useState } from 'react';
import { LuRefreshCw } from 'react-icons/lu';

import { recomaze_ai_personalization_env } from '../env';
import { useAppStateContext } from '../context/user.data.context';
import {
  isRecomazeAgentConnected,
  syncRecomazeAgentConnector,
} from '../service/connectors/connectors.service';
import type { IConnectorSyncResult } from '../service/connectors/connectors.interface';

const ACCENT: string = '#b7007c';

const Connectors = (): JSX.Element => {
  const { token, clientId } = useAppStateContext();

  const [connected, setConnected] = useState<boolean>(false);
  const [statusLoading, setStatusLoading] = useState<boolean>(true);
  const [syncing, setSyncing] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);

  const logo: string | undefined = recomaze_ai_personalization_env?.plugin_icon;

  const refreshStatus = useCallback(async (): Promise<void> => {
    if (!token || !clientId) {
      setStatusLoading(false);
      return;
    }

    setStatusLoading(true);
    const isConnected: boolean = await isRecomazeAgentConnected(
      token,
      clientId
    );
    setConnected(isConnected);
    setStatusLoading(false);
  }, [token, clientId]);

  useEffect(() => {
    refreshStatus();
  }, [refreshStatus]);

  const onConnect = useCallback(async (): Promise<void> => {
    setSyncing(true);
    setError(null);
    setSuccess(null);

    const result: IConnectorSyncResult = await syncRecomazeAgentConnector();

    if (result.ok) {
      setSuccess('Recomaze Agent connector synced successfully.');
      await refreshStatus();
    } else {
      setError(
        result.error || 'We could not sync the connector. Please try again.'
      );
    }

    setSyncing(false);
  }, [refreshStatus]);

  return (
    <div className="mx-auto w-full max-w-5xl space-y-8 bg-white p-6 md:p-10">
      <header>
        <h1 className="text-xl font-medium tracking-tight text-gray-900 md:text-2xl">
          Connectors
        </h1>
        <p className="mt-2 text-sm text-gray-500">
          Connect Recomaze to the services it works with. Reconnect at any time
          without deactivating the plugin.
        </p>
      </header>

      <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
        <div className="flex flex-col gap-4 p-6 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-4">
            {logo ? (
              <img
                src={logo}
                alt="Recomaze Agent"
                className="h-11 w-11 shrink-0 rounded-lg"
              />
            ) : (
              <div
                className="flex h-11 w-11 shrink-0 items-center justify-center rounded-lg text-lg font-semibold text-white"
                style={{ backgroundColor: ACCENT }}
              >
                R
              </div>
            )}

            <div>
              <div className="flex items-center gap-2">
                <h2 className="text-sm font-medium text-gray-900">
                  Recomaze Agent
                </h2>
                <span
                  className="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold"
                  style={{
                    color: ACCENT,
                    backgroundColor: 'rgba(183, 0, 124, 0.1)',
                  }}
                >
                  MCP
                </span>
              </div>
              <p className="mt-0.5 text-xs text-gray-500">
                Lets the Recomaze Agent reach your store to publish content and
                act on your behalf.
              </p>
            </div>
          </div>

          <div className="flex shrink-0 items-center gap-3">
            {statusLoading ? (
              <span className="inline-flex items-center gap-1.5 rounded-md bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-500 ring-1 ring-inset ring-gray-200">
                <svg
                  className="h-3.5 w-3.5 animate-spin"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <circle
                    cx="12"
                    cy="12"
                    r="10"
                    stroke="currentColor"
                    strokeWidth="3"
                    className="opacity-20"
                  />
                  <path
                    fill="currentColor"
                    d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                  />
                </svg>
                Checking…
              </span>
            ) : connected ? (
              <span className="inline-flex items-center gap-1.5 rounded-md bg-emerald-50 px-2.5 py-1 text-xs font-medium text-emerald-700 ring-1 ring-inset ring-emerald-600/20">
                <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" />
                Connected
              </span>
            ) : (
              <span className="inline-flex items-center gap-1.5 rounded-md bg-gray-50 px-2.5 py-1 text-xs font-medium text-gray-600 ring-1 ring-inset ring-gray-300">
                <span className="h-1.5 w-1.5 rounded-full bg-gray-400" />
                Not connected
              </span>
            )}

            <button
              type="button"
              onClick={onConnect}
              disabled={syncing || statusLoading}
              className="inline-flex items-center justify-center gap-2 rounded-md px-4 py-2 text-sm font-medium text-white transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
              style={{ backgroundColor: ACCENT }}
            >
              <LuRefreshCw
                className={`h-4 w-4 ${syncing ? 'animate-spin' : ''}`}
                aria-hidden
              />
              {syncing ? 'Syncing…' : connected ? 'Reconnect' : 'Connect'}
            </button>
          </div>
        </div>

        {(error || success) && (
          <div className="border-t border-gray-100 px-6 py-3">
            {error && <p className="text-sm text-red-600">{error}</p>}
            {success && <p className="text-sm text-emerald-600">{success}</p>}
          </div>
        )}
      </section>
    </div>
  );
};

export default Connectors;
