import React, { useEffect, useState } from 'react';
import { CopyOutlined } from '@ant-design/icons';
import { Button, Input, notification, Typography } from 'antd';
import { SMS_WHATSAPP_BUSINESS_NUMBER, SMS_WHATSAPP_MESSAGE_PATTERN } from '../constant';
import { saveSMSKeyFrame } from '../service';

const { Text, Link } = Typography;

// Copies text to the clipboard, with a fallback for browsers/contexts where the modern API doesn't work.
async function copyToClipboard(text: string): Promise<boolean> {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text);
      return true;
    }
  } catch {
    // fall through to the manual fallback below
  }
  try {
    const textarea = document.createElement('textarea');
    textarea.value = text;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);
    textarea.focus();
    textarea.select();
    const ok = document.execCommand('copy');
    document.body.removeChild(textarea);
    return ok;
  } catch {
    return false;
  }
}

// Fills in the message template with the real campaign name, launch name, and key frame.
function buildDefaultMessage(campaignName: string, launchName: string, keyFrame: string): string {
  return SMS_WHATSAPP_MESSAGE_PATTERN
    .replace('{{campaign_name}}', campaignName)
    .replace('{{launch_name}}', launchName || '')
    .replace('{{key_frame}}', keyFrame);
}

interface SMSKeyFrameBoxProps {
  campaignName: string;
  /** The selected launch's name. */
  launchName?: string;
  value: string;
  onChange: (value: string) => void;
  readOnly?: boolean;
  /** The saved campaign's id. Missing for a campaign that hasn't been saved yet. */
  campaignId?: string | number;
  /** The key frame currently stored in the database for this campaign. */
  savedKeyFrame?: string | null;
  /** Called after Copy has saved a changed key frame, so the parent knows what's now stored. */
  onKeyFrameSaved?: (keyFrame: string) => void;
}

// Key frame input plus a live preview of the WhatsApp message and link. The message auto-fills as you type, but stops updating once you edit it yourself.
const SMSKeyFrameBox: React.FC<SMSKeyFrameBoxProps> = ({ campaignName, launchName, value, onChange, readOnly, campaignId, savedKeyFrame, onKeyFrameSaved }) => {
  const trimmed = value.trim();
  const [message, setMessage] = useState('');
  const [messageTouched, setMessageTouched] = useState(false);
  const [copying, setCopying] = useState(false);

  useEffect(() => {
    if (messageTouched) return;
    setMessage(trimmed ? buildDefaultMessage(campaignName, launchName || '', trimmed) : '');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [trimmed, launchName, campaignName, messageTouched]);

  const whatsappLink = message.trim()
    ? `https://wa.me/${SMS_WHATSAPP_BUSINESS_NUMBER}?text=${encodeURIComponent(message)}`
    : '';

  // eslint-disable-next-line spellcheck/spell-checker
  // Gallabox pulls the key frame out from between quotes in the message — if someone edits the message and the quotes go missing, replies for this campaign stop being recognized.
  const keyFrameInQuotes = !trimmed || message.includes(`"${trimmed}"`);

  const handleCopy = async(): Promise<void> => {
    if (!keyFrameInQuotes) {
      notification.error({
        message: 'Key frame is missing its quotes',
        description: `Gallabox won't be able to read this reply. Put "${trimmed}" back in quotes in the message before copying.`,
      });
      return;
    }

    // eslint-disable-next-line spellcheck/spell-checker
    // The link carries this key frame, and Gallabox sends it back to the webhook, which looks it up in the database.
    // If it was edited since the last save, store it first (key frame only — the rotation is untouched), otherwise the link would never match.
    // A campaign that isn't saved yet has nothing to update; its key frame is stored when the rotation is saved.
    const keyFrameChanged = !readOnly && !!campaignId && trimmed !== (savedKeyFrame || '').trim();
    if (keyFrameChanged) {
      setCopying(true);
      try {
        await saveSMSKeyFrame(campaignId as string | number, trimmed);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      } catch (err: any) {
        notification.error({
          message: 'Key frame not updated — link not copied',
          description: err?.response?.data?.message || 'Could not save the key frame. Please try again.',
        });
        return;
      } finally {
        setCopying(false);
      }
      onKeyFrameSaved?.(trimmed);
    }

    const ok = await copyToClipboard(whatsappLink);
    if (ok) {
      notification.success({
        message: keyFrameChanged ? 'Key frame updated and link copied' : 'Link copied',
        // eslint-disable-next-line spellcheck/spell-checker
        description: 'Paste it into Bitly to shorten it before sending.',
      });
    } else {
      notification.error({
        message: keyFrameChanged ? 'Key frame updated, but the link could not be copied' : 'Could not copy',
        description: 'Select the link and copy it manually.',
      });
    }
  };

  return (
    <div>
      <div className="mb-4" style={{ maxWidth: 420 }}>
        <Text type="secondary" style={{ fontSize: 11 }}>
          KEY FRAME <span style={{ color: '#ff4d4f' }}>*</span>
        </Text>
        <Input
          className="block mt-1"
          disabled={readOnly}
          placeholder="e.g. Vantage"
          value={value}
          onChange={(e) => onChange(e.target.value)}
        />
      </div>

      {trimmed && (
        <div>
          <Text type="secondary" style={{ fontSize: 11 }}>WHATSAPP MESSAGE</Text>
          <Input.TextArea
            className="block mt-1"
            rows={3}
            disabled={readOnly}
            value={message}
            onChange={(e) => {
              setMessageTouched(true);
              setMessage(e.target.value);
            }}
          />
          {keyFrameInQuotes ? (
            <Text type="secondary" style={{ fontSize: 12, display: 'block', marginTop: 4, marginBottom: 12 }}>
              Gallabox reads &ldquo;{trimmed}&rdquo; from inside the quotes &mdash; keep it in quotes somewhere in the message.
            </Text>
          ) : (
            <Text type="danger" style={{ fontSize: 12, display: 'block', marginTop: 4, marginBottom: 12 }}>
              &ldquo;{trimmed}&rdquo; needs to be in quotes in the message, or Gallabox won&apos;t recognize replies for this campaign.
            </Text>
          )}

          <Text type="secondary" style={{ fontSize: 11 }}>CLICK-TO-WHATSAPP LINK</Text>
          <div className="flex gap-2 mt-1">
            <Input readOnly value={whatsappLink} status={keyFrameInQuotes ? undefined : 'error'} />
            <Button danger={!keyFrameInQuotes} icon={<CopyOutlined />} loading={copying} onClick={handleCopy}>
              Copy
            </Button>
          </div>
          <Text type="secondary" style={{ fontSize: 12 }}>
            Paste this into your{' '}
            <Link href="https://bitly.com" target="_blank" rel="noopener noreferrer">
              Bitly link generator
            </Link>
            , then send the shortened link via SMS.
          </Text>
        </div>
      )}
    </div>
  );
};

export default SMSKeyFrameBox;
