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

import { useAppStateContext } from '../context/user.data.context';
import Button from '../components/widgets/Button';
import { postWordpressProducts } from '../service/products/products.service';

const ImportIllustration = () => (
  <svg
    viewBox="0 0 400 240"
    className="h-full w-full"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
    role="img"
    aria-label="Animated data sync illustration"
  >
    <style>
      {`
        @keyframes dash {
          to { stroke-dashoffset: -24; }
        }
        @keyframes slideNode {
          0% { transform: translateX(0); opacity: 0; }
          15% { opacity: 1; }
          85% { opacity: 1; }
          100% { transform: translateX(180px); opacity: 0; }
        }
        @keyframes pulseRing {
          0% { transform: scale(0.8); opacity: 0.5; }
          100% { transform: scale(1.4); opacity: 0; }
        }
        .path-line { 
          stroke-dasharray: 6 6; 
          animation: dash 1.5s linear infinite; 
        }
        .node-1 { animation: slideNode 2.5s ease-in-out infinite; }
        .node-2 { animation: slideNode 2.5s ease-in-out infinite 0.8s; }
        .node-3 { animation: slideNode 2.5s ease-in-out infinite 1.6s; }
        .ring { 
          transform-origin: center;
          animation: pulseRing 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; 
        }
      `}
    </style>

    <rect
      x="50"
      y="80"
      width="80"
      height="80"
      rx="16"
      stroke="#E5E7EB"
      strokeWidth="2"
      fill="#F9FAFB"
    />
    <path
      d="M75 110h30M75 130h20"
      stroke="#D1D5DB"
      strokeWidth="2"
      strokeLinecap="round"
    />

    <rect
      x="270"
      y="80"
      width="80"
      height="80"
      rx="16"
      stroke="#E5E7EB"
      strokeWidth="2"
      fill="#F9FAFB"
    />
    <path
      d="M295 105h30M295 120h30M295 135h15"
      stroke="#D1D5DB"
      strokeWidth="2"
      strokeLinecap="round"
    />

    <circle
      cx="310"
      cy="120"
      r="40"
      stroke="#111827"
      strokeWidth="1"
      className="ring"
      opacity="0"
    />

    <path
      d="M140 120h120"
      stroke="#E5E7EB"
      strokeWidth="2"
      className="path-line"
    />

    <g transform="translate(140, 120)">
      <circle cx="0" cy="0" r="4" fill="#111827" className="node-1" />
      <circle cx="0" cy="0" r="4" fill="#111827" className="node-2" />
      <circle cx="0" cy="0" r="4" fill="#111827" className="node-3" />
    </g>
  </svg>
);

const ImportProducts = (): JSX.Element => {
  const [loading, setLoading] = useState<boolean>(false);
  const [isError, setIsError] = useState<string | null>(null);
  const [isSuccess, setIsSuccess] = useState<string | null>(null);

  const { token, user, canUseWpApi, fetchUser } = useAppStateContext();
  const navigate = useNavigate();

  useEffect(() => {
    if (!user && token) fetchUser();
  }, [user, token, fetchUser]);

  useEffect(() => {
    if (isError || isSuccess) {
      const timer: NodeJS.Timeout = setTimeout(() => {
        setIsError(null);
        setIsSuccess(null);
      }, 4500);
      return () => clearTimeout(timer);
    }
  }, [isError, isSuccess]);

  const onProductsImport = async (): Promise<void> => {
    try {
      setLoading(true);
      setIsError(null);
      setIsSuccess(null);

      const response = await postWordpressProducts();

      if (response) {
        setIsSuccess(
          'Your products are being imported. You can leave this page and keep using the plugin.'
        );
      } else {
        setIsError('We could not start the import. Please try again.');
      }
    } catch (error: any) {
      setIsError(error?.message || 'Something went wrong. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="mx-auto w-full max-w-5xl bg-white p-6 md:p-10">
      <header className="mb-8">
        <h1 className="text-xl font-medium tracking-tight text-gray-900 md:text-2xl">
          Import Products
        </h1>
        <p className="mt-2 text-sm text-gray-500">
          Start syncing your store catalog to Recomaze. We’ll handle it in the
          background so you can continue working.
        </p>
      </header>

      <div className="grid grid-cols-1 gap-8 lg:grid-cols-5">
        <div className="flex flex-col space-y-6 lg:col-span-3">
          <div className="space-y-4">
            {loading && (
              <div
                className="rounded-lg border border-gray-200 bg-gray-50 p-5"
                role="alert"
                aria-live="polite"
              >
                <div className="flex items-start gap-4">
                  <svg
                    className="h-5 w-5 animate-spin text-gray-900"
                    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"
                      opacity="0.2"
                    />
                    <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>
                  <div className="flex-1">
                    <p className="text-sm font-medium text-gray-900">
                      Import in progress…
                    </p>
                    <p className="mt-1 text-sm text-gray-500">
                      This may take up to a minute depending on your catalog
                      size.
                    </p>
                    <div className="mt-4 h-1.5 w-full overflow-hidden rounded-full bg-gray-200">
                      <div className="h-full w-1/3 animate-[shimmer_1.5s_infinite_linear] rounded-full bg-gray-900" />
                    </div>
                    <style>{`@keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } }`}</style>
                  </div>
                </div>
              </div>
            )}

            {!loading && isError && (
              <div
                className="rounded-lg border border-red-200 bg-red-50 p-5"
                role="alert"
              >
                <div className="flex items-start gap-3">
                  <svg
                    viewBox="0 0 24 24"
                    className="h-5 w-5 text-red-600"
                    fill="currentColor"
                    aria-hidden="true"
                  >
                    <path d="M12 2a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2Zm1 15h-2v-2h2Zm0-4h-2V7h2Z" />
                  </svg>
                  <div>
                    <p className="text-sm font-medium text-red-900">
                      Import failed
                    </p>
                    <p className="mt-1 text-sm text-red-700">{isError}</p>
                  </div>
                </div>
              </div>
            )}

            {!loading && isSuccess && (
              <div
                className="rounded-lg border border-emerald-200 bg-emerald-50 p-5"
                role="status"
              >
                <div className="flex items-start gap-3">
                  <svg
                    viewBox="0 0 20 20"
                    className="h-5 w-5 text-emerald-600"
                    fill="currentColor"
                    aria-hidden="true"
                  >
                    <path
                      fillRule="evenodd"
                      d="M16.707 5.293a1 1 0 0 1 0 1.414l-7.25 7.25a1 1 0 0 1-1.414 0l-3-3a1 1 0 1 1 1.414-1.414l2.293 2.293 6.543-6.543a1 1 0 0 1 1.414 0z"
                      clipRule="evenodd"
                    />
                  </svg>
                  <div>
                    <p className="text-sm font-medium text-emerald-900">
                      Import started
                    </p>
                    <p className="mt-1 text-sm text-emerald-700">{isSuccess}</p>
                  </div>
                </div>
              </div>
            )}

            {!loading && !isError && !isSuccess && (
              <div className="rounded-lg border border-gray-200 bg-white p-5">
                <p className="text-sm text-gray-600">
                  <strong className="font-medium text-gray-900">Notice:</strong>{' '}
                  Existing products in Recomaze will be replaced with the latest
                  data from your shop.
                </p>
              </div>
            )}
          </div>

          <div className="flex flex-wrap items-center gap-3 pt-2">
            {canUseWpApi ? (
              <Button
                type="button"
                isLoading={loading}
                disabled={loading}
                onClick={onProductsImport}
                className="rounded-md bg-gray-900 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50"
              >
                {loading ? 'Importing…' : 'Start Import'}
              </Button>
            ) : (
              <div className="w-full rounded-lg border border-amber-200 bg-amber-50 p-4">
                <p className="text-sm text-amber-800">
                  You don’t have enough permissions or the WordPress REST API is
                  disabled. Your products may already be synced; otherwise,
                  enable REST API access to use this feature.
                </p>
              </div>
            )}

            <button
              type="button"
              onClick={() => navigate('/')}
              className="rounded-md border border-gray-200 bg-white px-5 py-2.5 text-sm font-medium text-gray-900 transition-colors hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-200 focus:ring-offset-2"
            >
              Cancel
            </button>
          </div>

          <div className="mt-8 flex items-start gap-3 border-t border-gray-100 pt-6">
            <svg
              viewBox="0 0 24 24"
              className="mt-0.5 h-4 w-4 shrink-0 text-gray-400"
              fill="currentColor"
              aria-hidden="true"
            >
              <path d="M12 2a10 10 0 1 0 10 10A10.011 10.011 0 0 0 12 2ZM11 11V7h2v4h-2Zm0 6v-2h2v2h-2Z" />
            </svg>
            <p className="text-sm text-gray-500">
              You can safely leave this page—the import runs in the background.
              Check back later to see updated products in your catalog.
            </p>
          </div>
        </div>

        <div className="hidden lg:col-span-2 lg:block">
          <div className="flex h-full min-h-[300px] w-full items-center justify-center rounded-lg border border-gray-200 bg-white p-6">
            <ImportIllustration />
          </div>
        </div>
      </div>
    </div>
  );
};

export default ImportProducts;
