import React, { useCallback, useMemo, useState } from 'react';

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

const AgenticFeedPage = () => {
  const { clientId, user } = useAppStateContext();
  const [isCopied, setIsCopied] = useState(false);

  const isReady = user?.feed_status === 'COMPLETED';

  const feedUrl = useMemo(() => {
    if (!clientId) return '';
    return `https://storage.googleapis.com/feeds-recomaze/openai/${clientId}/openai_product_feed_v1.csv`;
  }, [clientId]);

  const prettyUrl = useMemo(() => {
    if (!feedUrl) return '';
    try {
      const u = new URL(feedUrl);
      const parts = u.pathname.split('/').filter(Boolean);
      const tail = parts.slice(-1)[0] ?? '';
      return `${u.host}/…/${tail}`;
    } catch {
      return feedUrl;
    }
  }, [feedUrl]);

  const copy = useCallback(async () => {
    if (!feedUrl) return;
    try {
      await navigator.clipboard.writeText(feedUrl);
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 2000);
    } catch {
      const ta = document.createElement('textarea');
      ta.value = feedUrl;
      document.body.appendChild(ta);
      ta.select();
      try {
        document.execCommand('copy');
        setIsCopied(true);
        setTimeout(() => setIsCopied(false), 2000);
      } finally {
        document.body.removeChild(ta);
      }
    }
  }, [feedUrl]);

  return (
    <div className="mx-auto w-full max-w-[1600px] 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">
          Agentic Commerce Feed
        </h1>
        <p className="mt-2 text-sm text-gray-500">
          Your product catalog is automatically formatted to meet the{' '}
          <a
            href="https://developers.openai.com/commerce/specs/feed/"
            target="_blank"
            rel="noreferrer noopener"
            className="font-medium text-gray-900 underline underline-offset-4 transition-colors hover:text-gray-600"
          >
            OpenAI Commerce Feed Specification
          </a>
          .
        </p>
      </header>

      <section className="overflow-hidden rounded-lg border border-gray-200 bg-white">
        <header className="flex items-center justify-between border-b border-gray-100 bg-gray-50/50 px-6 py-4">
          <div>
            <h2 className="text-sm font-medium text-gray-900">
              Feed Status & URL
            </h2>
            <p className="mt-0.5 text-xs text-gray-500">
              Use this secure link to connect your store to ChatGPT Shopping.
            </p>
          </div>
          {isReady ? (
            <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">
              <svg
                className="h-3.5 w-3.5"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              Active & Synced
            </span>
          ) : (
            <span className="inline-flex items-center gap-1.5 rounded-md bg-amber-50 px-2.5 py-1 text-xs font-medium text-amber-700 ring-1 ring-inset ring-amber-600/20">
              <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>
              Generating
            </span>
          )}
        </header>

        <div className="p-6">
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center">
            <div className="flex-1 overflow-hidden rounded-md border border-gray-200 bg-gray-50 px-4 py-2.5">
              <p
                className={`truncate text-sm font-mono ${isReady ? 'text-gray-900' : 'text-gray-400'}`}
              >
                {isReady ? prettyUrl : 'Processing feed generation...'}
              </p>
            </div>

            <div className="flex shrink-0 items-center gap-3">
              <a
                href={isReady ? feedUrl : undefined}
                target="_blank"
                rel="noreferrer noopener"
                className={`inline-flex items-center justify-center rounded-md border border-gray-200 bg-white px-4 py-2 text-sm font-medium transition-colors ${
                  isReady
                    ? 'text-gray-900 hover:bg-gray-50'
                    : 'pointer-events-none cursor-not-allowed text-gray-400'
                }`}
              >
                Open in Browser
              </a>
              <Button
                type="button"
                onClick={copy}
                disabled={!isReady}
                className="w-[120px] justify-center rounded-md bg-gray-900 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-gray-800 disabled:cursor-not-allowed disabled:opacity-50"
              >
                {isCopied ? 'Copied!' : 'Copy URL'}
              </Button>
            </div>
          </div>
        </div>
      </section>

      <div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
        <section className="rounded-lg border border-gray-200 bg-white p-6">
          <div className="mb-4 flex items-center gap-3">
            <div className="flex h-8 w-8 items-center justify-center rounded-md bg-gray-50 text-gray-900 ring-1 ring-inset ring-gray-200">
              <svg
                className="h-4 w-4"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M13 10V3L4 14h7v7l9-11h-7z"
                />
              </svg>
            </div>
            <h3 className="text-base font-medium text-gray-900">
              What{`'`}s Next?
            </h3>
          </div>
          <ol className="space-y-4 text-sm text-gray-600">
            <li className="flex gap-3">
              <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-gray-100 text-xs font-medium text-gray-900">
                1
              </span>
              <div>
                Apply for ChatGPT Shopping via the{' '}
                <a
                  href="https://chatgpt.com/merchants"
                  target="_blank"
                  rel="noreferrer noopener"
                  className="font-medium text-gray-900 underline underline-offset-4 hover:text-gray-600"
                >
                  Merchant Application
                </a>
                .
              </div>
            </li>
            <li className="flex gap-3">
              <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-gray-100 text-xs font-medium text-gray-900">
                2
              </span>
              <div>
                Follow updates on the{' '}
                <a
                  href="https://www.shopify.com/chatgpt"
                  target="_blank"
                  rel="noreferrer noopener"
                  className="font-medium text-gray-900 underline underline-offset-4 hover:text-gray-600"
                >
                  Shopify ChatGPT page
                </a>
                .
              </div>
            </li>
            <li className="flex gap-3">
              <span className="flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-gray-100 text-xs font-medium text-gray-900">
                3
              </span>
              <div>
                Once approved, paste your copied feed URL to connect instantly.
              </div>
            </li>
          </ol>
        </section>

        <section className="rounded-lg border border-gray-200 bg-white p-6">
          <div className="mb-4 flex items-center gap-3">
            <div className="flex h-8 w-8 items-center justify-center rounded-md bg-gray-50 text-gray-900 ring-1 ring-inset ring-gray-200">
              <svg
                className="h-4 w-4"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
                />
              </svg>
            </div>
            <h3 className="text-base font-medium text-gray-900">
              Why this matters
            </h3>
          </div>
          <ul className="space-y-3 text-sm text-gray-600">
            <li className="flex items-start gap-2.5">
              <svg
                className="mt-0.5 h-4 w-4 shrink-0 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              <span>
                OpenAI and Shopify are rolling out ChatGPT commerce natively.
              </span>
            </li>
            <li className="flex items-start gap-2.5">
              <svg
                className="mt-0.5 h-4 w-4 shrink-0 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              <span>
                To appear in ChatGPT shopping results, a strictly structured
                feed is required.
              </span>
            </li>
            <li className="flex items-start gap-2.5">
              <svg
                className="mt-0.5 h-4 w-4 shrink-0 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
                strokeWidth={2}
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M5 13l4 4L19 7"
                />
              </svg>
              <span>
                Recomaze creates and hosts this for you automatically so your
                store is prepared ahead of the rollout.
              </span>
            </li>
          </ul>
        </section>
      </div>
    </div>
  );
};

export default AgenticFeedPage;
