import React, { useEffect, useState } from 'react';
import { CopyOutlined } from '@ant-design/icons';
import { Button, Input, notification, Spin, Tag, Typography } from 'antd';
import { getSmsTemplate } from '../service';

const { Text } = Typography;

interface SmsTemplateBoxProps {
  projectId?: number;
  disabled?: boolean;
  /* The edited template text — lifted to the parent so Save can send it. */
  value: string;
  onChange: (value: string) => void;
}

/*
  navigator.clipboard requires a secure context — it's undefined on a plain
  http:// origin (works on localhost and on HTTPS prod, but not on an
  http:// staging IP, which is where this is most likely to actually get
  tested first). Always fall back to a hidden-textarea + execCommand copy
  rather than only calling clipboard.writeText and hoping.
 */
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;
  }
}

// Rough client-side re-check while typing, between template fetches — the
// backend's smsTemplate.helper.js measureSms() is the source of truth (it
// runs on load and would run again on save); this just keeps the counter
// live as the admin edits without a round trip on every keystroke.
// eslint-disable-next-line no-control-regex
const GSM_7_REGEX = /^[\u0000-~¡£¤¥§¿ÄÅÆÉÑÖØÜßàäåæèéìñòöøùüΓΔΘΛΞΠΣΦΨΩ€]*$/;

function measure(text: string): { charCount: number; encoding: 'GSM-7' | 'UCS-2'; segments: number } {
  const charCount = text.length;
  const isGsm7 = GSM_7_REGEX.test(text);
  const singleLimit = isGsm7 ? 160 : 70;
  const multipartLimit = isGsm7 ? 153 : 67;
  const segments = charCount === 0 ? 0 : charCount <= singleLimit ? 1 : Math.ceil(charCount / multipartLimit);
  return { charCount, encoding: isGsm7 ? 'GSM-7' : 'UCS-2', segments };
}

const SmsTemplateBox: React.FC<SmsTemplateBoxProps> = ({ projectId, disabled, value, onChange }) => {
  const [loading, setLoading] = useState(false);
  const [isSaved, setIsSaved] = useState(false);

  useEffect(() => {
    if (!projectId) {
      onChange('');
      return;
    }
    setLoading(true);
    getSmsTemplate(projectId)
      .then((res) => {
        onChange(res.template);
        setIsSaved(res.is_saved);
      })
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [projectId]);

  if (!projectId) return null;

  const { charCount, encoding, segments } = measure(value);
  const overSingleSegment = segments > 1;

  const handleCopy = async (): Promise<void> => {
    const ok = await copyToClipboard(value);
    if (ok) {
      notification.success({ message: 'Template copied.' });
    } else {
      notification.error({ message: 'Could not copy — select the text and copy manually.' });
    }
  };

  return (
    <div>
      <div className="flex items-center justify-between mb-1">
        <Text type="secondary" style={{ fontSize: 11 }}>
          SMS TEMPLATE {!isSaved && <Tag style={{ marginLeft: 6, fontSize: 10 }}>DEFAULT — NOT YET SAVED</Tag>}
        </Text>
      </div>

      {loading ? (
        <div className="flex items-center justify-center py-6">
          <Spin />
        </div>
      ) : (
        <>
          <Input.TextArea
            rows={4}
            disabled={disabled}
            value={value}
            onChange={(e) => onChange(e.target.value)}
            placeholder="SMS template..."
          />
          <div className="flex items-center justify-between mt-2">
            <Text type="secondary" style={{ fontSize: 12 }}>
              {charCount} characters · {encoding} · {segments} segment{segments === 1 ? '' : 's'}
              {overSingleSegment && (
                <span style={{ color: '#d97706', marginLeft: 6 }}>
                  — over one segment, the gateway will bill this as {segments}.
                </span>
              )}
            </Text>
            <Button size="small" icon={<CopyOutlined />} onClick={handleCopy}>
              Copy
            </Button>
          </div>
        </>
      )}
    </div>
  );
};

export default SmsTemplateBox;
