import React, { useEffect, useRef, useState } from 'react';
import {
  LuCheck,
  LuCopy,
  LuFileText,
  LuHelpCircle,
  LuTag,
  LuType,
  LuWand2,
} from 'react-icons/lu';

import { copyToClipboard } from '../../lib/clipboard';
import {
  faqPairsToHtml,
  htmlToPlainText,
  looksLikeHtml,
} from '../../lib/inline-result-html';
import type { ContentCheckerFixResult } from '../../service/content-generator/content-generator.interface';

/** Rendered-description styling (mirrors the catalog-quality result card). */
const RENDERED_CLASS =
  'space-y-2 text-sm leading-relaxed text-gray-900 [&_h1]:text-lg [&_h1]:font-semibold [&_h2]:mt-3 [&_h2]:font-semibold [&_h3]:mt-3 [&_h3]:font-semibold [&_h4]:font-semibold [&_p]:my-1 [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_strong]:font-semibold';

/** How long the "Copied" state stays on a copy chip. */
const COPIED_FLASH_MS = 2000;

/** Props for {@link CheckerFixCard}. */
interface CheckerFixCardProps {
  result: ContentCheckerFixResult;
}

/** Props for the small copy button used across the card's sections. */
interface CopyChipProps {
  label: string;
  copied: boolean;
  onCopy: () => void;
}

/**
 * Small outline copy button with a timed "Copied" state.
 *
 * @param {CopyChipProps} props - Label, copied flag, and click handler.
 * @return {JSX.Element} The copy button.
 */
const CopyChip = ({ label, copied, onCopy }: CopyChipProps): JSX.Element => (
  <button
    type="button"
    onClick={onCopy}
    className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-gray-200 bg-white px-2 py-1 text-xs font-medium text-gray-700 hover:bg-gray-50"
  >
    {copied ? (
      <LuCheck className="h-3 w-3 text-emerald-600" aria-hidden />
    ) : (
      <LuCopy className="h-3 w-3" aria-hidden />
    )}
    {copied ? 'Copied' : label}
  </button>
);

/**
 * Full result of the Content Checker "Fix with AI" action: improved title,
 * rendered description, SEO fields, tags, and FAQ - each with its own copy
 * action so the merchant can paste fields straight into their store admin.
 *
 * @param {CheckerFixCardProps} props - The generated content row.
 * @return {JSX.Element} The fix result card.
 */
const CheckerFixCard = ({ result }: CheckerFixCardProps): JSX.Element => {
  const [copiedKey, setCopiedKey] = useState<string | null>(null);
  const cardRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    cardRef.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }, []);

  const copy = async (value: string, key: string): Promise<void> => {
    if (await copyToClipboard(value)) {
      setCopiedKey(key);
      window.setTimeout(() => setCopiedKey(null), COPIED_FLASH_MS);
    }
  };

  const descriptionIsHtml = looksLikeHtml(result.improved_description);
  const descriptionText = descriptionIsHtml
    ? htmlToPlainText(result.improved_description)
    : result.improved_description;
  const faqHtml =
    result.faq_pairs.length > 0 ? faqPairsToHtml(result.faq_pairs) : '';
  const faqText = result.faq_pairs
    .map(pair => `Q: ${pair.q}\nA: ${pair.a}`)
    .join('\n\n');
  const tagsText = result.tags.join(', ');
  const seoRows = [
    { key: 'seo_title', label: 'SEO title', value: result.seo_title },
    {
      key: 'seo_description',
      label: 'SEO description',
      value: result.seo_description,
    },
    {
      key: 'short_description',
      label: 'Short description',
      value: result.short_description,
    },
  ].filter(row => row.value.trim().length > 0);

  return (
    <div
      ref={cardRef}
      className="scroll-mt-6 rounded-xl border border-emerald-300 bg-white p-5 shadow-sm"
    >
      <div className="flex flex-col gap-1">
        <h2 className="flex items-center gap-2 text-base font-semibold text-gray-900">
          <LuWand2 className="h-4 w-4 text-emerald-600" aria-hidden />
          AI Fix
          <span className="rounded-full border border-emerald-200 bg-emerald-50 px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider text-emerald-700">
            Ready to copy
          </span>
        </h2>
        <p className="text-xs text-gray-500">
          Generated with your Product Content pipeline. Copy each field into
          your store admin.
        </p>
      </div>

      <div className="mt-5 space-y-5">
        {result.improved_title && (
          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0 flex-1">
                <p className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                  <LuType className="h-3 w-3" aria-hidden />
                  Title
                </p>
                <p className="mt-1 text-base font-semibold text-gray-900">
                  {result.improved_title}
                </p>
              </div>
              <CopyChip
                label="Copy"
                copied={copiedKey === 'title'}
                onCopy={() => void copy(result.improved_title, 'title')}
              />
            </div>
          </div>
        )}

        {result.improved_description && (
          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="flex items-center justify-between gap-3">
              <p className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                <LuFileText className="h-3 w-3" aria-hidden />
                Description
              </p>
              <div className="flex items-center gap-1.5">
                {descriptionIsHtml && (
                  <CopyChip
                    label="Copy HTML"
                    copied={copiedKey === 'description-html'}
                    onCopy={() =>
                      void copy(result.improved_description, 'description-html')
                    }
                  />
                )}
                <CopyChip
                  label="Copy text"
                  copied={copiedKey === 'description-text'}
                  onCopy={() => void copy(descriptionText, 'description-text')}
                />
              </div>
            </div>
            {descriptionIsHtml ? (
              <div
                className={`mt-3 ${RENDERED_CLASS}`}
                dangerouslySetInnerHTML={{
                  __html: result.improved_description,
                }}
              />
            ) : (
              <p className="mt-3 whitespace-pre-wrap text-sm leading-relaxed text-gray-900">
                {result.improved_description}
              </p>
            )}
          </div>
        )}

        {seoRows.length > 0 && (
          <div className="grid gap-3 md:grid-cols-3">
            {seoRows.map(row => (
              <div
                key={row.key}
                className="rounded-lg border border-gray-200 bg-gray-50 p-3"
              >
                <div className="flex items-center justify-between gap-2">
                  <p className="text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                    {row.label}
                  </p>
                  <CopyChip
                    label="Copy"
                    copied={copiedKey === row.key}
                    onCopy={() => void copy(row.value, row.key)}
                  />
                </div>
                <p className="mt-1.5 text-xs leading-relaxed text-gray-900">
                  {row.value}
                </p>
              </div>
            ))}
          </div>
        )}

        {result.tags.length > 0 && (
          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="flex items-center justify-between gap-3">
              <p className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                <LuTag className="h-3 w-3" aria-hidden />
                Tags
              </p>
              <CopyChip
                label="Copy"
                copied={copiedKey === 'tags'}
                onCopy={() => void copy(tagsText, 'tags')}
              />
            </div>
            <div className="mt-2 flex flex-wrap gap-1.5">
              {result.tags.map((tag, tagIndex) => (
                <span
                  key={tagIndex}
                  className="inline-flex items-center rounded-full border border-gray-300 bg-white px-2 py-0.5 text-[10px] font-medium text-gray-700"
                >
                  {tag}
                </span>
              ))}
            </div>
          </div>
        )}

        {result.faq_pairs.length > 0 && (
          <div className="rounded-lg border border-gray-200 bg-gray-50 p-4">
            <div className="flex items-center justify-between gap-3">
              <p className="flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-gray-500">
                <LuHelpCircle className="h-3 w-3" aria-hidden />
                FAQ
              </p>
              <div className="flex items-center gap-1.5">
                <CopyChip
                  label="Copy HTML"
                  copied={copiedKey === 'faq-html'}
                  onCopy={() => void copy(faqHtml, 'faq-html')}
                />
                <CopyChip
                  label="Copy text"
                  copied={copiedKey === 'faq-text'}
                  onCopy={() => void copy(faqText, 'faq-text')}
                />
              </div>
            </div>
            <div className="mt-3 space-y-3">
              {result.faq_pairs.map((pair, pairIndex) => (
                <div key={pairIndex}>
                  <p className="text-sm font-medium text-gray-900">{pair.q}</p>
                  <p className="mt-0.5 text-sm leading-relaxed text-gray-600">
                    {pair.a}
                  </p>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

export default CheckerFixCard;
