import React, { useState } from 'react';
import { useLocation } from 'react-router-dom';

interface PreviewBannerProps {
  token: string | null;
  domain: string | null;
  previewMode: boolean;
  documentationReady: boolean;
  onActivatePreview: () => Promise<void>;
  onDeactivatePreview: () => Promise<void>;
}

const PreviewBanner = ({
  token,
  domain,
  previewMode,
  documentationReady,
  onActivatePreview,
  onDeactivatePreview,
}: PreviewBannerProps): JSX.Element | null => {
  const [loading, setLoading] = useState(false);
  const location = useLocation();

  if (location.pathname !== '/agent-analytics') return null;

  const handleActivate = async () => {
    setLoading(true);
    try {
      await onActivatePreview();
    } finally {
      setLoading(false);
    }
  };

  const handleDeactivate = async () => {
    setLoading(true);
    try {
      await onDeactivatePreview();
    } finally {
      setLoading(false);
    }
  };

  const handleViewPreview = () => {
    if (!domain) return;
    const storeUrl = domain.startsWith('http') ? domain : `https://${domain}`;
    const cleanDomain = domain.replace(/^https?:\/\//, '');
    window.open(`${storeUrl}?recomaze_auth=test_${cleanDomain}`, '_blank');
  };

  const chipBase =
    'inline-flex items-center px-2.5 py-0.5 text-[10px] sm:text-xs font-bold uppercase tracking-wider border';
  const chipActive = `${chipBase} bg-black text-white border-black`;
  const chipInactive = `${chipBase} bg-gray-50 text-gray-500 border-gray-200`;

  const btnBase =
    'inline-flex shrink-0 items-center justify-center gap-2 rounded-lg px-5 py-2.5 text-sm font-bold transition-all focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-black disabled:cursor-not-allowed disabled:opacity-50';
  const primaryBtn = `${btnBase} bg-black text-white hover:bg-gray-800 disabled:bg-gray-200 disabled:text-gray-400`;
  const secondaryBtn = `${btnBase} border border-gray-300 bg-white text-black hover:bg-gray-50`;

  return (
    <div className="w-full mb-8 font-sans text-black selection:bg-gray-200 selection:text-black">
      <div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
        {/* Header & Actions */}
        <div className="border-b border-gray-100 bg-gray-50/50 p-6 sm:p-8 flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
          <div className="min-w-0 flex-1">
            <div className="flex flex-wrap items-center gap-2 mb-4">
              <span className={previewMode ? chipActive : chipInactive}>
                Preview Mode: {previewMode ? 'Active' : 'Disabled'}
              </span>
            </div>
            <h3 className="text-xl font-extrabold tracking-tight text-black">
              Store Preview Environment
            </h3>
            <p className="mt-2 text-sm text-gray-600">
              Test how Recomaze integrates and behaves on your live store safely
              before deploying it to your customers.
            </p>
          </div>

          <div className="flex flex-col gap-3 sm:flex-row sm:items-center shrink-0">
            {!previewMode ? (
              <button
                onClick={handleActivate}
                disabled={loading || !token}
                className={primaryBtn}
              >
                {loading ? (
                  <svg
                    className="h-4 w-4 animate-spin"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                    />
                  </svg>
                ) : (
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"
                    />
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"
                    />
                  </svg>
                )}
                Enable Preview
              </button>
            ) : (
              <>
                <button
                  onClick={handleViewPreview}
                  disabled={!domain}
                  className={primaryBtn}
                >
                  <svg
                    className="h-4 w-4"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
                    />
                  </svg>
                  Open Live Preview
                </button>
                <button
                  onClick={handleDeactivate}
                  disabled={loading || !token}
                  className={secondaryBtn}
                >
                  {loading ? (
                    <svg
                      className="h-4 w-4 animate-spin"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                      />
                    </svg>
                  ) : (
                    <svg
                      className="h-4 w-4"
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                      strokeWidth={2}
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21"
                      />
                    </svg>
                  )}
                  Disable
                </button>
              </>
            )}
          </div>
        </div>

        <div className="p-6 sm:p-8 bg-white space-y-6">
          {/* Warning Notice */}
          <div className="border-l-4 border-black bg-gray-50 p-5">
            <div className="flex items-start gap-4">
              <div className="mt-0.5 shrink-0">
                <svg
                  className="h-5 w-5 text-black"
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                  strokeWidth={2}
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
                  />
                </svg>
              </div>
              <div>
                <p className="text-xs font-bold uppercase tracking-wider text-black">
                  Visibility Restriction
                </p>
                <p className="mt-1 text-sm text-gray-800">
                  Activating Preview Mode immediately hides the widget from live
                  store traffic. Only administrators using the preview link will
                  see the integration. Ensure you disable preview mode to
                  restore public access.
                </p>
              </div>
            </div>
          </div>

          {/* Documentation Status */}
          <div className="rounded-xl border border-gray-200 bg-white p-5">
            <div className="flex items-start gap-4">
              <div className="mt-0.5 shrink-0">
                {documentationReady ? (
                  <svg
                    className="h-5 w-5 text-black"
                    fill="none"
                    viewBox="0 0 24 24"
                    stroke="currentColor"
                    strokeWidth={2}
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
                    />
                  </svg>
                ) : (
                  <svg
                    className="h-5 w-5 animate-spin text-black"
                    fill="none"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                    />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                    />
                  </svg>
                )}
              </div>
              <div className="flex-1 min-w-0">
                {documentationReady ? (
                  <>
                    <p className="text-xs font-bold uppercase tracking-wider text-black">
                      Documentation Ready
                    </p>
                    <p className="mt-1 text-sm text-gray-600">
                      System logic has been compiled successfully. The AI
                      ChatBot is primed to render on your storefront.
                    </p>
                  </>
                ) : (
                  <>
                    <p className="text-xs font-bold uppercase tracking-wider text-black">
                      Generating Documentation
                    </p>
                    <p className="mt-1 text-sm text-gray-600">
                      If the interface is not rendering, system logic is still
                      compiling in the background. Please wait a few moments.
                    </p>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default PreviewBanner;
