'use client';

import { useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';

type TemplateButton = {
  type: string;
  label: string;
};

type TemplateRecord = {
  id: string;
  name: string;
  category: string;
  status: string;
  language: string;
  headerText: string | null;
  bodyText: string;
  footerText: string | null;
  buttons: TemplateButton[];
};

type Props = {
  labels: Record<string, string>;
  initialTemplate: TemplateRecord | null;
};

const sampleVariableValues = ['Alex', 'SUMMER50', 'Order-481', 'May 15', 'BizOne'];

function substituteVariables(input: string) {
  return input.replace(/\{\{(\d+)\}\}/g, (_, token) => {
    const index = Number(token) - 1;
    return `[${sampleVariableValues[index] || `Value ${token}`}]`;
  });
}

function countTemplateVariables(input: string) {
  return new Set(input.match(/\{\{\d+\}\}/g) || []).size;
}

export function TemplateBuilderForm({ labels, initialTemplate }: Props) {
  const router = useRouter();
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [form, setForm] = useState({
    name: initialTemplate?.name || '',
    category: initialTemplate?.category || 'Marketing',
    status: initialTemplate?.status || 'Draft',
    language: initialTemplate?.language || 'en_US',
    headerText: initialTemplate?.headerText || '',
    bodyText:
      initialTemplate?.bodyText ||
      labels.defaultBody,
    footerText: initialTemplate?.footerText || '',
    buttons:
      initialTemplate?.buttons?.length
        ? initialTemplate.buttons
        : [{ type: 'quick_reply', label: labels.defaultButton }],
  });

  const variableCount = useMemo(() => countTemplateVariables(form.bodyText), [form.bodyText]);
  const previewBody = useMemo(() => substituteVariables(form.bodyText), [form.bodyText]);
  const previewHeader = useMemo(() => substituteVariables(form.headerText), [form.headerText]);
  const previewFooter = useMemo(() => substituteVariables(form.footerText), [form.footerText]);

  async function submit(intent: 'draft' | 'submit') {
    setIsSaving(true);
    setError('');
    setSuccess('');

    try {
      const payload = {
        ...form,
        status: intent === 'submit' ? 'Pending' : 'Draft',
        headerText: form.headerText.trim() || undefined,
        footerText: form.footerText.trim() || undefined,
        buttons: form.buttons
          .map((button) => ({
            type: button.type || 'quick_reply',
            label: button.label.trim(),
          }))
          .filter((button) => button.label.length > 0),
      };

      const response = await fetch(initialTemplate ? `/api/templates/${initialTemplate.id}` : '/api/templates', {
        method: initialTemplate ? 'PATCH' : 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });

      const result = await response.json();
      if (!response.ok) {
        const message = typeof result?.message === 'string' ? result.message : labels.failedSave;
        throw new Error(message);
      }

      setSuccess(intent === 'submit' ? labels.submitted : labels.draftSaved);

      if (!initialTemplate?.id && result?.id) {
        router.push(`/dashboard/templates/builder?id=${result.id}`);
      } else {
        router.refresh();
      }
    } catch (submitError) {
      setError(submitError instanceof Error ? submitError.message : labels.failedSave);
    } finally {
      setIsSaving(false);
    }
  }

  return (
    <section className="template-builder-page">
      <header className="template-builder-hero">
        <div>
          <h1 className="template-builder-heading">
            {initialTemplate ? labels.editTitle : labels.createTitle}
          </h1>
          <p className="template-builder-copy">
            {labels.copy}
          </p>
        </div>
        <div className="template-builder-actions">
          <button
            type="button"
            className="template-builder-draft-button"
            disabled={isSaving}
            onClick={() => submit('draft')}
          >
            {isSaving ? labels.saving : labels.saveDraft}
          </button>
          <button
            type="button"
            className="template-builder-submit-button"
            disabled={isSaving}
            onClick={() => submit('submit')}
          >
            {isSaving ? labels.saving : labels.submitApproval}
            <span className="material-symbols-outlined">send</span>
          </button>
        </div>
      </header>

      {error ? <p className="form-error">{error}</p> : null}
      {success ? <p className="form-success">{success}</p> : null}

      <section className="template-builder-grid">
        <div className="template-builder-form-column">
          <article className="surface-card template-builder-card">
            <div className="template-builder-card-head">
              <span className="material-symbols-outlined">edit_note</span>
              <h2>{labels.basicDetails}</h2>
            </div>
            <div className="template-builder-basic-grid">
              <label className="template-builder-field template-builder-field-full">
                <span>{labels.templateName}</span>
                <input
                  type="text"
                  value={form.name}
                  onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
                  placeholder={labels.namePlaceholder}
                />
              </label>
              <label className="template-builder-field">
                <span>{labels.category}</span>
                <select
                  value={form.category}
                  onChange={(event) => setForm((current) => ({ ...current, category: event.target.value }))}
                >
                  <option value="Marketing">{labels.marketing}</option>
                  <option value="Utility">{labels.utility}</option>
                  <option value="Authentication">{labels.authentication}</option>
                </select>
              </label>
              <label className="template-builder-field">
                <span>{labels.language}</span>
                <select
                  value={form.language}
                  onChange={(event) => setForm((current) => ({ ...current, language: event.target.value }))}
                >
                  <option value="en_US">English (US)</option>
                  <option value="id_ID">Bahasa Indonesia</option>
                  <option value="pt_BR">Portuguese (BR)</option>
                </select>
              </label>
            </div>
          </article>

          <article className="surface-card template-builder-card">
            <div className="template-builder-card-topline">
              <div className="template-builder-card-head">
                <span className="material-symbols-outlined">subject</span>
                <h2>{labels.messageContent}</h2>
              </div>
            </div>
            <div className="template-builder-content-stack">
              <label className="template-builder-field">
                <span>{labels.headerOptional}</span>
                <input
                  type="text"
                  placeholder={labels.headerPlaceholder}
                  value={form.headerText}
                  onChange={(event) => setForm((current) => ({ ...current, headerText: event.target.value }))}
                />
              </label>
              <label className="template-builder-field">
                <span>{labels.bodyText}</span>
                <textarea
                  rows={8}
                  value={form.bodyText}
                  onChange={(event) => setForm((current) => ({ ...current, bodyText: event.target.value }))}
                />
              </label>
              <div className="template-builder-inline-meta">
                <span>{labels.variablesDetected} {variableCount}</span>
                <button
                  type="button"
                  onClick={() =>
                    setForm((current) => ({
                      ...current,
                      bodyText: `${current.bodyText}${current.bodyText.endsWith(' ') || current.bodyText.endsWith('\n') ? '' : ' '}{{${variableCount + 1}}}`,
                    }))
                  }
                >
                  {labels.addVariable}
                </button>
              </div>
              <label className="template-builder-field">
                <span>{labels.footerOptional}</span>
                <input
                  type="text"
                  placeholder={labels.footerPlaceholder}
                  value={form.footerText}
                  onChange={(event) => setForm((current) => ({ ...current, footerText: event.target.value }))}
                />
              </label>
            </div>
          </article>

          <article className="surface-card template-builder-card">
            <div className="template-builder-card-head">
              <span className="material-symbols-outlined">smart_button</span>
              <h2>{labels.buttons}</h2>
            </div>
            <div className="template-builder-button-stack">
              {form.buttons.map((button, index) => (
                <div key={`${index}-${button.label}`} className="template-builder-button-row">
                  <span className="material-symbols-outlined">ads_click</span>
                  <div>
                    <strong>{labels.quickReply}</strong>
                    <input
                      type="text"
                      value={button.label}
                      onChange={(event) =>
                        setForm((current) => ({
                          ...current,
                          buttons: current.buttons.map((item, itemIndex) =>
                            itemIndex === index ? { ...item, label: event.target.value } : item,
                          ),
                        }))
                      }
                      placeholder={labels.buttonPlaceholder}
                    />
                  </div>
                  <button
                    type="button"
                    className="template-builder-delete-button"
                    aria-label={labels.deleteQuickReply}
                    onClick={() =>
                      setForm((current) => ({
                        ...current,
                        buttons: current.buttons.filter((_, itemIndex) => itemIndex !== index),
                      }))
                    }
                  >
                    <span className="material-symbols-outlined">delete</span>
                  </button>
                </div>
              ))}
              <button
                type="button"
                className="template-builder-add-button"
                onClick={() =>
                  setForm((current) => ({
                    ...current,
                    buttons: [...current.buttons, { type: 'quick_reply', label: '' }].slice(0, 10),
                  }))
                }
              >
                <span className="material-symbols-outlined">add</span>
                {labels.addButton}
              </button>
            </div>
          </article>
        </div>

        <aside className="template-builder-preview-column">
          <div className="template-builder-preview-shell">
            <div className="template-builder-phone-frame">
              <div className="template-builder-phone-status">
                <span>9:41</span>
                <div>
                  <span className="material-symbols-outlined">signal_cellular_4_bar</span>
                  <span className="material-symbols-outlined">wifi</span>
                  <span className="material-symbols-outlined">battery_full</span>
                </div>
              </div>
              <div className="template-builder-phone-screen">
                <div className="template-builder-phone-header">
                  <span className="material-symbols-outlined">arrow_back</span>
                  <div className="template-builder-phone-avatar">Y</div>
                  <div className="template-builder-phone-contact">
                    <strong>{labels.business}</strong>
                    <span>{labels.online}</span>
                  </div>
                  <span className="material-symbols-outlined">videocam</span>
                  <span className="material-symbols-outlined">call</span>
                  <span className="material-symbols-outlined">more_vert</span>
                </div>

                <div className="template-builder-chat-area">
                  <div className="template-builder-chat-date">{labels.today}</div>
                  <div className="template-builder-chat-stack">
                    <div className="template-builder-chat-bubble">
                      {previewHeader ? <strong>{previewHeader}</strong> : null}
                      <p>{previewBody}</p>
                      {previewFooter ? <small>{previewFooter}</small> : null}
                      <div className="template-builder-chat-meta">
                        <small>09:41 AM</small>
                        <span className="material-symbols-outlined">done_all</span>
                      </div>
                    </div>
                    {form.buttons
                      .filter((button) => button.label.trim().length > 0)
                      .map((button, index) => (
                        <button key={`${button.label}-${index}`} type="button" className="template-builder-chat-reply">
                          <span className="material-symbols-outlined">reply</span>
                          {button.label}
                        </button>
                      ))}
                  </div>

                  <div className="template-builder-input-row">
                    <div className="template-builder-input-shell">
                      <span className="material-symbols-outlined">mood</span>
                      <span className="template-builder-input-placeholder">{labels.message}</span>
                      <span className="material-symbols-outlined">attach_file</span>
                      <span className="material-symbols-outlined">photo_camera</span>
                    </div>
                    <div className="template-builder-mic-button">
                      <span className="material-symbols-outlined">mic</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div className="template-builder-preview-toggle">
              <button type="button" className="is-active">
                {labels.mobile}
              </button>
              <button type="button">{labels.desktop}</button>
            </div>
          </div>
        </aside>
      </section>
    </section>
  );
}
