'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 = {
  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({ 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 ||
      `Hi {{1}}, our Summer Sale is finally here! 🌴

Get up to 50% OFF on all collections using code {{2}} at checkout.

Shop now: https://example.com/shop`,
    footerText: initialTemplate?.footerText || '',
    buttons:
      initialTemplate?.buttons?.length
        ? initialTemplate.buttons
        : [{ type: 'quick_reply', label: 'Stop promotions' }],
  });

  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 : 'Failed to save template';
        throw new Error(message);
      }

      setSuccess(intent === 'submit' ? 'Template submitted for approval.' : 'Draft saved.');

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

  return (
    <section className="template-builder-page">
      <header className="template-builder-hero">
        <div>
          <h1 className="template-builder-heading">
            {initialTemplate ? 'Edit Message Template' : 'Create Message Template'}
          </h1>
          <p className="template-builder-copy">
            Design and manage your business messages before they are approved for outbound delivery.
          </p>
        </div>
        <div className="template-builder-actions">
          <button
            type="button"
            className="template-builder-draft-button"
            disabled={isSaving}
            onClick={() => submit('draft')}
          >
            {isSaving ? 'Saving...' : 'Save Draft'}
          </button>
          <button
            type="button"
            className="template-builder-submit-button"
            disabled={isSaving}
            onClick={() => submit('submit')}
          >
            {isSaving ? 'Saving...' : 'Submit for Approval'}
            <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>Basic Details</h2>
            </div>
            <div className="template-builder-basic-grid">
              <label className="template-builder-field template-builder-field-full">
                <span>Template Name</span>
                <input
                  type="text"
                  value={form.name}
                  onChange={(event) => setForm((current) => ({ ...current, name: event.target.value }))}
                  placeholder="e.g. welcome_message"
                />
              </label>
              <label className="template-builder-field">
                <span>Category</span>
                <select
                  value={form.category}
                  onChange={(event) => setForm((current) => ({ ...current, category: event.target.value }))}
                >
                  <option value="Marketing">Marketing</option>
                  <option value="Utility">Utility</option>
                  <option value="Authentication">Authentication</option>
                </select>
              </label>
              <label className="template-builder-field">
                <span>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>Message Content</h2>
              </div>
            </div>
            <div className="template-builder-content-stack">
              <label className="template-builder-field">
                <span>Header (Optional)</span>
                <input
                  type="text"
                  placeholder="Add a title or choose media"
                  value={form.headerText}
                  onChange={(event) => setForm((current) => ({ ...current, headerText: event.target.value }))}
                />
              </label>
              <label className="template-builder-field">
                <span>Body Text</span>
                <textarea
                  rows={8}
                  value={form.bodyText}
                  onChange={(event) => setForm((current) => ({ ...current, bodyText: event.target.value }))}
                />
              </label>
              <div className="template-builder-inline-meta">
                <span>Variables detected: {variableCount}</span>
                <button
                  type="button"
                  onClick={() =>
                    setForm((current) => ({
                      ...current,
                      bodyText: `${current.bodyText}${current.bodyText.endsWith(' ') || current.bodyText.endsWith('\n') ? '' : ' '}{{${variableCount + 1}}}`,
                    }))
                  }
                >
                  Add Variable
                </button>
              </div>
              <label className="template-builder-field">
                <span>Footer (Optional)</span>
                <input
                  type="text"
                  placeholder="Add a short line of text"
                  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>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>Quick Reply</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="Button label"
                    />
                  </div>
                  <button
                    type="button"
                    className="template-builder-delete-button"
                    aria-label="Delete quick reply"
                    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>
                Add Button (Max 10)
              </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>Your Business</strong>
                    <span>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">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">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">
                Mobile
              </button>
              <button type="button">Desktop</button>
            </div>
          </div>
        </aside>
      </section>
    </section>
  );
}
