import React, { useEffect, useRef, useState } from 'react';

import { MirrorBlock } from '../../service/company-id/company-id.interface';

import { GRADIENT, MONO, SANS } from './theme';

const ENGINE_DOT: Record<string, string> = {
  chatgpt: 'bg-[#10a37f]',
  gemini: 'bg-[#4285f4]',
};

export interface AnswerBlockProps {
  block: MirrorBlock;
  value: string;
  confirmed: boolean;
  populating: boolean;
  onChange: (value: string) => void;
  onConfirm: () => void;
  onReopen: () => void;
}

export function AnswerBlock({
  block,
  value,
  confirmed,
  populating,
  onChange,
  onConfirm,
  onReopen,
}: AnswerBlockProps): JSX.Element {
  const hasValue = value.trim().length > 0;
  const localRef = useRef<HTMLTextAreaElement | null>(null);
  const wasConfirmed = useRef(confirmed);
  useEffect(() => {
    const node = localRef.current;
    if (!node) return;
    node.style.height = 'auto';
    node.style.height = `${node.scrollHeight}px`;
  }, [value]);
  // Reopening a confirmed answer puts the cursor straight in the box: with no
  // Edit button, the textarea itself is the only edit affordance.
  useEffect(() => {
    if (wasConfirmed.current && !confirmed) localRef.current?.focus();
    wasConfirmed.current = confirmed;
  }, [confirmed]);

  return (
    <div
      className={`bg-white border rounded-[14px] p-[18px] flex flex-col transition-colors ${
        confirmed ? 'border-[rgba(34,197,94,0.4)]' : 'border-[#e1e3e5]'
      }`}
    >
      <div className="flex items-center justify-between gap-2">
        <div
          className={`${MONO} text-[10px] tracking-[0.08em] uppercase text-[#6d7175] font-medium`}
        >
          {block.label}
        </div>
        {confirmed && (
          <span className="h-[22px] w-[22px] rounded-full flex items-center justify-center flex-none bg-[#22c55e] border border-[#22c55e]">
            <CheckIcon />
          </span>
        )}
      </div>

      <div className="mt-3 flex flex-col gap-1.5">
        {block.engines.map(engine => (
          <EngineRow
            key={engine.engine}
            engine={engine}
            onUse={text => {
              if (!confirmed) onChange(text);
            }}
          />
        ))}
      </div>

      <div className="mt-3 pt-3 border-t border-[#e1e3e5] flex flex-col flex-1">
        {confirmed ? (
          <button
            type="button"
            onClick={onReopen}
            title="Tap to edit"
            className="mt-1.5 w-full text-left text-[13.5px] text-[#202223] cursor-pointer rounded-[9px] px-3 py-2 border border-[rgba(34,197,94,0.3)] bg-[#f3faf6] hover:border-[rgba(34,197,94,0.5)]"
          >
            {value}
          </button>
        ) : (
          <>
            {block.silent && !hasValue && (
              <div className="mt-1 text-[12px] text-[#8c9196]">
                Your site doesn&apos;t say. Add your official version.
              </div>
            )}
            <div className="relative mt-1.5 flex flex-col">
              <textarea
                value={value}
                onChange={event => onChange(event.target.value)}
                ref={localRef}
                placeholder={populating ? '' : 'Type your official answer'}
                className={`w-full min-h-[62px] box-border overflow-hidden bg-white text-[#202223] placeholder:text-[#babec3] border border-[#e1e3e5] rounded-[9px] px-3 py-2 ${SANS} text-[13.5px] leading-[1.45] resize-none outline-none focus:border-[#C8175D] focus:shadow-[0_0_0_3px_rgba(200,23,93,0.18)]`}
              />
              {populating && !hasValue && (
                <div className="pointer-events-none absolute inset-0 px-3 py-2 text-[13.5px] leading-[1.45] text-[#8c9196] blur-[3px] animate-pulse select-none">
                  AI is reading your site to draft this...
                </div>
              )}
            </div>
            {/* Pinned to the bottom of the card so the CTA lines up with the
                one beside it, whatever height the answers above take. */}
            <div className="mt-auto pt-2">
              <div className="text-[11.5px] font-semibold leading-[1.4] text-[#15803d]">
                * Type straight in the box to change it.
              </div>
              <button
                type="button"
                onClick={onConfirm}
                disabled={!hasValue}
                className={`w-full min-h-[40px] mt-2.5 ${GRADIENT} text-white border-none rounded-[9px] px-4 py-2 ${SANS} text-[13px] font-semibold cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed hover:enabled:shadow-[0_4px_14px_rgba(200,23,93,0.28)] active:enabled:translate-y-px`}
              >
                Looks right
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

/**
 * A single engine's read. Tapping a resolved answer copies it into the
 * merchant's input (and expands it), so a suggestion that already looks
 * right is one tap from confirming.
 */
function EngineRow({
  engine,
  onUse,
}: {
  engine: MirrorBlock['engines'][number];
  onUse: (text: string) => void;
}): JSX.Element {
  const [expanded, setExpanded] = useState(false);
  const dot =
    engine.pending || engine.empty
      ? 'bg-[#c9cccf]'
      : (ENGINE_DOT[engine.engine] ?? 'bg-[#c9cccf]');
  const canExpand = !engine.pending && !engine.empty;

  return (
    <div className="flex items-baseline gap-2.5 min-w-0">
      <span
        className={`w-1.5 h-1.5 rounded-full flex-none -translate-y-px ${dot}`}
      />
      <span
        className={`${MONO} text-[10px] tracking-[0.08em] text-[#6d7175] flex-none w-[70px]`}
      >
        {engine.label}
      </span>
      {engine.pending ? (
        <span className="text-[13px] text-[#6d7175] animate-pulse">
          {engine.scan_text}
        </span>
      ) : (
        <button
          type="button"
          onClick={() => {
            if (!canExpand) return;
            setExpanded(true);
            onUse(engine.text);
          }}
          title={canExpand ? 'Use this answer' : undefined}
          className={`text-left text-[13px] transition-all ${
            canExpand ? 'cursor-pointer' : 'cursor-default'
          } ${expanded ? '' : 'line-clamp-2'} ${
            engine.empty ? 'text-[#8c9196]' : 'text-[#42474c] italic'
          }`}
        >
          {engine.empty ? 'No answer found' : `"${engine.text}"`}
        </button>
      )}
    </div>
  );
}

function CheckIcon(): JSX.Element {
  return (
    <svg
      width="13"
      height="13"
      viewBox="0 0 24 24"
      fill="none"
      stroke="#ffffff"
      strokeWidth="3"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M20 6 9 17l-5-5" />
    </svg>
  );
}
