'use client';

import { useState, useEffect } from 'react';
import { MessageSquare, Mail, Phone, Bell, Save, RotateCcw, Eye, Tag, CheckCircle2, Copy, Info, Loader2 } from 'lucide-react';
import { listTemplates, saveTemplates } from '@client/api/templates';
import { usePageHeader } from '@client/contexts/PageHeaderContext';
import { useLanguage } from '@client/contexts/LanguageContext';

type Channel = 'sms' | 'email' | 'whatsapp' | 'in-app';
type TemplateKey = 'order-confirmation' | 'booking-confirmation' | 'customer-alert';

interface Variable {
  tag: string;
  label: string;
  example: string;
}

interface Template {
  id: TemplateKey;
  label: string;
  description: string;
  icon: React.ReactNode;
  color: string;
  variables: Variable[];
  defaults: Record<Channel, string>;
}

const variables: Record<TemplateKey, Variable[]> = {
  'order-confirmation': [
    { tag: '{{customer_name}}', label: 'Customer Name', example: 'John Smith' },
    { tag: '{{order_id}}', label: 'Order ID', example: '#ORD-4821' },
    { tag: '{{order_items}}', label: 'Order Items', example: 'Margherita Pizza, Garlic Bread' },
    { tag: '{{order_total}}', label: 'Order Total', example: '$34.50' },
    { tag: '{{estimated_time}}', label: 'Estimated Time', example: '25–30 mins' },
    { tag: '{{restaurant_name}}', label: 'Restaurant Name', example: 'The Rustic Fork' },
    { tag: '{{tracking_link}}', label: 'Tracking Link', example: 'https://track.restroagent.com/4821' },
  ],
  'booking-confirmation': [
    { tag: '{{customer_name}}', label: 'Customer Name', example: 'Jane Doe' },
    { tag: '{{booking_id}}', label: 'Booking ID', example: '#BKG-2034' },
    { tag: '{{booking_date}}', label: 'Booking Date', example: 'Saturday, March 20, 2026' },
    { tag: '{{booking_time}}', label: 'Booking Time', example: '7:30 PM' },
    { tag: '{{party_size}}', label: 'Party Size', example: '4 guests' },
    { tag: '{{table_number}}', label: 'Table Number', example: 'Table 12' },
    { tag: '{{restaurant_name}}', label: 'Restaurant Name', example: 'The Rustic Fork' },
    { tag: '{{restaurant_address}}', label: 'Restaurant Address', example: '123 Main St, New York' },
    { tag: '{{cancel_link}}', label: 'Cancel Link', example: 'https://book.restroagent.com/cancel/2034' },
  ],
  'customer-alert': [
    { tag: '{{customer_name}}', label: 'Customer Name', example: 'Alex Johnson' },
    { tag: '{{alert_type}}', label: 'Alert Type', example: 'Order Delay' },
    { tag: '{{alert_message}}', label: 'Alert Message', example: 'Your order is running 10 minutes late.' },
    { tag: '{{order_id}}', label: 'Order ID', example: '#ORD-5512' },
    { tag: '{{restaurant_name}}', label: 'Restaurant Name', example: 'The Rustic Fork' },
    { tag: '{{support_link}}', label: 'Support Link', example: 'https://help.restroagent.com' },
  ],
};

const defaultTemplates: Record<TemplateKey, Record<Channel, string>> = {
  'order-confirmation': {
    sms: `Hi {{customer_name}}! Your order {{order_id}} from {{restaurant_name}} has been confirmed. Items: {{order_items}}. Total: {{order_total}}. Estimated delivery: {{estimated_time}}. Track here: {{tracking_link}}`,
    email: `Dear {{customer_name}},\n\nThank you for your order at {{restaurant_name}}!\n\nOrder ID: {{order_id}}\nItems: {{order_items}}\nTotal: {{order_total}}\nEstimated Time: {{estimated_time}}\n\nTrack your order: {{tracking_link}}\n\nWe hope you enjoy your meal!\n\nThe {{restaurant_name}} Team`,
    whatsapp: `Hi {{customer_name}}!\n\nYour order *{{order_id}}* is confirmed!\n\n*Items:* {{order_items}}\n*Total:* {{order_total}}\n*ETA:* {{estimated_time}}\n\nTrack: {{tracking_link}}`,
    'in-app': `Your order {{order_id}} is confirmed! Estimated time: {{estimated_time}}.`,
  },
  'booking-confirmation': {
    sms: `Hi {{customer_name}}! Your table at {{restaurant_name}} is confirmed. Booking {{booking_id}} for {{party_size}} on {{booking_date}} at {{booking_time}}. Cancel: {{cancel_link}}`,
    email: `Dear {{customer_name}},\n\nYour reservation at {{restaurant_name}} is confirmed!\n\nBooking ID: {{booking_id}}\nDate: {{booking_date}}\nTime: {{booking_time}}\nParty Size: {{party_size}}\nTable: {{table_number}}\nAddress: {{restaurant_address}}\n\nNeed to cancel? {{cancel_link}}\n\nWe look forward to seeing you!\n\nThe {{restaurant_name}} Team`,
    whatsapp: `Hi {{customer_name}}!\n\nYour reservation is confirmed!\n\n*Date:* {{booking_date}}\n*Time:* {{booking_time}}\n*Guests:* {{party_size}}\n*Table:* {{table_number}}\n*Address:* {{restaurant_address}}\n\nNeed to cancel? {{cancel_link}}`,
    'in-app': `Reservation confirmed for {{booking_date}} at {{booking_time}} — {{party_size}}.`,
  },
  'customer-alert': {
    sms: `Hi {{customer_name}}, alert from {{restaurant_name}}: {{alert_message}} (Ref: {{order_id}}). Need help? {{support_link}}`,
    email: `Dear {{customer_name}},\n\nWe wanted to let you know:\n\n{{alert_message}}\n\nReference: {{order_id}}\n\nIf you need assistance, please visit: {{support_link}}\n\nApologies for any inconvenience.\n\nThe {{restaurant_name}} Team`,
    whatsapp: `Hi {{customer_name}},\n\n*{{alert_type}}* — {{alert_message}}\n\nRef: {{order_id}}\n\nNeed help? {{support_link}}`,
    'in-app': `{{alert_type}}: {{alert_message}}`,
  },
};

const templates: Template[] = [
  {
    id: 'order-confirmation',
    label: 'Order Confirmation',
    description: 'Sent when a customer order is successfully placed and confirmed.',
    icon: <CheckCircle2 size={16} />,
    color: 'hsl(142, 72%, 29%)',
    variables: variables['order-confirmation'],
    defaults: defaultTemplates['order-confirmation'],
  },
  {
    id: 'booking-confirmation',
    label: 'Booking Confirmation',
    description: 'Sent when a table reservation is confirmed for a customer.',
    icon: <Bell size={16} />,
    color: 'hsl(210, 100%, 40%)',
    variables: variables['booking-confirmation'],
    defaults: defaultTemplates['booking-confirmation'],
  },
  {
    id: 'customer-alert',
    label: 'Customer Alert',
    description: 'Sent to notify customers about delays, changes, or important updates.',
    icon: <Info size={16} />,
    color: 'hsl(22, 89%, 48%)',
    variables: variables['customer-alert'],
    defaults: defaultTemplates['customer-alert'],
  },
];

const channels: { id: Channel; label: string; icon: React.ReactNode }[] = [
  { id: 'sms', label: 'SMS', icon: <Phone size={14} /> },
  { id: 'email', label: 'Email', icon: <Mail size={14} /> },
  { id: 'whatsapp', label: 'WhatsApp', icon: <MessageSquare size={14} /> },
  { id: 'in-app', label: 'In-App', icon: <Bell size={14} /> },
];

function escapeHtml(str: string): string {
  return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
function renderPreview(text: string, vars: Variable[]): string {
  let result = escapeHtml(text);
  vars.forEach((v) => {
    const escapedTag = escapeHtml(v.tag);
    result = result.split(escapedTag).join(`<span style="background:hsl(22,89%,95%);color:hsl(22,89%,35%);padding:0 3px;border-radius:3px;font-weight:600">${escapeHtml(v.example)}</span>`);
  });
  return result.replace(/\n/g, '<br/>');
}

export default function TemplatesPage() {
  const { t } = useLanguage();
  usePageHeader(t('settings.templates.title', "Message Templates"), t('settings.templates.subtitle', "Manage response templates"));
  const [activeTemplate, setActiveTemplate] = useState<TemplateKey>('order-confirmation');
  const [activeChannel, setActiveChannel] = useState<Channel>('sms');
  const [contents, setContents] = useState<Record<TemplateKey, Record<Channel, string>>>(
    JSON.parse(JSON.stringify(defaultTemplates))
  );
  const [savedState, setSavedState] = useState<Record<string, boolean>>({});
  const [copiedTag, setCopiedTag] = useState<string | null>(null);
  const [showPreview, setShowPreview] = useState(true);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    listTemplates()
      .then(serverTemplates => {
        if (serverTemplates.length > 0) {
          const merged = JSON.parse(JSON.stringify(defaultTemplates));
          serverTemplates.forEach(st => {
            if (merged[st.templateKey] && merged[st.templateKey][st.channel] !== undefined) {
              merged[st.templateKey][st.channel] = st.content;
            }
          });
          setContents(merged);
        }
      })
      .catch(() => {})
      .finally(() => setLoading(false));
  }, []);

  const currentTemplate = templates.find((t) => t.id === activeTemplate)!;
  const currentContent = contents[activeTemplate][activeChannel];

  const handleContentChange = (val: string) => {
    setContents((prev) => ({
      ...prev,
      [activeTemplate]: { ...prev[activeTemplate], [activeChannel]: val },
    }));
    setSavedState((prev) => ({ ...prev, [`${activeTemplate}-${activeChannel}`]: false }));
  };

  const handleInsertTag = (tag: string) => {
    setContents((prev) => ({
      ...prev,
      [activeTemplate]: {
        ...prev[activeTemplate],
        [activeChannel]: prev[activeTemplate][activeChannel] + tag,
      },
    }));
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      await saveTemplates([{
        templateKey: activeTemplate,
        channel: activeChannel,
        content: currentContent,
      }]);
      setSavedState((prev) => ({ ...prev, [`${activeTemplate}-${activeChannel}`]: true }));
    } catch {
      // save failed
    } finally {
      setSaving(false);
    }
  };

  const handleReset = () => {
    setContents((prev) => ({
      ...prev,
      [activeTemplate]: {
        ...prev[activeTemplate],
        [activeChannel]: defaultTemplates[activeTemplate][activeChannel],
      },
    }));
    setSavedState((prev) => ({ ...prev, [`${activeTemplate}-${activeChannel}`]: false }));
  };

  const handleCopyTag = (tag: string) => {
    navigator.clipboard.writeText(tag).catch(() => {});
    setCopiedTag(tag);
    setTimeout(() => setCopiedTag(null), 1500);
  };

  const isSaved = savedState[`${activeTemplate}-${activeChannel}`];

  if (loading) {
    return (
      <>
        <div className="flex items-center justify-center py-20 gap-2" style={{ color: 'hsl(var(--muted-foreground))' }}>
          <Loader2 size={20} className="animate-spin" /> {t('common.loading_templates', 'Loading templates…')}
        </div>
      </>
    );
  }

  return (
    <>
      <div className="flex flex-col h-full" style={{ backgroundColor: 'hsl(var(--background))' }}>
        <div className="px-6 pt-6 pb-4 shrink-0" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
          <h1 className="text-2xl font-bold" style={{ color: 'hsl(var(--foreground))' }}>{t('settings.templates.title', 'Message Templates')}</h1>
          <p className="text-sm mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
            {t('settings.templates.description', 'Customise automated messages sent to customers across all channels')}
          </p>
        </div>

        <div className="flex flex-1 min-h-0">
          <div className="w-56 shrink-0 flex flex-col py-4 px-3 gap-1" style={{ borderRight: '1px solid hsl(var(--border))' }}>
            <p className="text-xs font-semibold uppercase tracking-wider px-2 mb-2" style={{ color: 'hsl(var(--muted-foreground))' }}>{t('settings.templates.templates_list', 'Templates')}</p>
            {templates.map((t_item) => (
              <button
                key={t_item.id}
                onClick={() => setActiveTemplate(t_item.id)}
                className="flex items-start gap-3 px-3 py-3 rounded-xl text-left transition-all"
                style={
                  activeTemplate === t_item.id
                    ? { backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }
                    : { color: 'hsl(var(--foreground-secondary))' }
                }
              >
                <span className="mt-0.5 shrink-0" style={{ color: activeTemplate === t_item.id ? 'hsl(var(--primary))' : t_item.color }}>
                  {t_item.icon}
                </span>
                <div>
                  <p className="text-sm font-medium leading-tight">{t(`settings.templates.label_${t_item.id}`, t_item.label)}</p>
                  <p className="text-xs mt-0.5 leading-snug opacity-70">{t(`settings.templates.desc_${t_item.id}`, t_item.description)}</p>
                </div>
              </button>
            ))}
          </div>

          <div className="flex-1 flex flex-col min-w-0">
            <div className="flex items-center gap-1 px-5 pt-4 pb-0 shrink-0">
              {channels.map((ch) => (
                <button
                  key={ch.id}
                  onClick={() => setActiveChannel(ch.id)}
                  className="flex items-center gap-1.5 px-4 py-2 text-sm font-medium rounded-t-lg border-b-2 transition-all"
                  style={
                    activeChannel === ch.id
                      ? { borderBottomColor: 'hsl(var(--primary))', color: 'hsl(var(--primary))', backgroundColor: 'hsl(var(--primary-light))' }
                      : { borderBottomColor: 'transparent', color: 'hsl(var(--muted-foreground))' }
                  }
                >
                  {ch.icon}
                  {t(`settings.templates.channel_${ch.id}`, ch.label)}
                </button>
              ))}
              <div className="flex-1" />
              <button
                onClick={() => setShowPreview((v) => !v)}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium border transition-all"
                style={{
                  borderColor: showPreview ? 'hsl(var(--primary))' : 'hsl(var(--border))',
                  color: showPreview ? 'hsl(var(--primary))' : 'hsl(var(--muted-foreground))',
                  backgroundColor: showPreview ? 'hsl(var(--primary-light))' : 'transparent',
                }}
              >
                <Eye size={13} />
                {t('common.preview', 'Preview')}
              </button>
            </div>

            <div className="flex flex-1 min-h-0 gap-0" style={{ borderTop: '1px solid hsl(var(--border))' }}>
              <div className="flex-1 flex flex-col min-w-0 p-5 gap-4">
                <div>
                  <p className="text-xs font-semibold mb-2 flex items-center gap-1.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    <Tag size={12} />
                    {t('settings.templates.placeholders', 'Variable Placeholders — click to insert, or copy')}
                  </p>
                  <div className="flex flex-wrap gap-1.5">
                    {currentTemplate.variables.map((v) => (
                      <div key={v.tag} className="flex items-center rounded-lg overflow-hidden" style={{ border: '1px solid hsl(var(--border))' }}>
                        <button
                          onClick={() => handleInsertTag(v.tag)}
                          className="px-2.5 py-1 text-xs font-mono font-semibold transition-colors hover:opacity-80"
                          style={{ backgroundColor: 'hsl(var(--primary-light))', color: 'hsl(var(--primary))' }}
                          title={`${t('common.insert', 'Insert')} ${v.tag}`}
                        >
                          {v.tag}
                        </button>
                        <button
                          onClick={() => handleCopyTag(v.tag)}
                          className="px-2 py-1 transition-colors hover:opacity-70"
                          style={{ backgroundColor: 'hsl(var(--surface))', color: 'hsl(var(--muted-foreground))' }}
                          title={t('common.copy_tag', "Copy tag")}
                        >
                          {copiedTag === v.tag ? <CheckCircle2 size={11} style={{ color: 'hsl(142, 72%, 29%)' }} /> : <Copy size={11} />}
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

                <div className="flex-1 flex flex-col">
                  <textarea
                    value={currentContent}
                    onChange={(e) => handleContentChange(e.target.value)}
                    className="flex-1 w-full p-4 text-sm rounded-xl border outline-none resize-none font-mono leading-relaxed"
                    style={{
                      backgroundColor: 'hsl(var(--surface))',
                      borderColor: 'hsl(var(--border))',
                      color: 'hsl(var(--foreground))',
                      minHeight: '200px',
                    }}
                    placeholder={t('settings.templates.textarea_placeholder', "Enter your message template here...")}
                    spellCheck={false}
                  />
                  <p className="text-xs mt-1.5 text-right" style={{ color: 'hsl(var(--muted-foreground))' }}>
                    {currentContent.length} {t('common.characters', 'characters')}
                    {activeChannel === 'sms' && currentContent.length > 160 && (
                      <span className="ml-2" style={{ color: 'hsl(22, 89%, 48%)' }}>
                        ({Math.ceil(currentContent.length / 160)} {t('settings.templates.sms_segments', 'SMS segments')})
                      </span>
                    )}
                  </p>
                </div>

                <div className="flex items-center gap-3">
                  <button
                    onClick={handleSave}
                    disabled={saving}
                    className="flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold text-white transition-all hover:opacity-90"
                    style={{ backgroundColor: isSaved ? 'hsl(142, 72%, 29%)' : 'hsl(var(--primary))' }}
                  >
                    {saving ? <Loader2 size={15} className="animate-spin" /> : isSaved ? <CheckCircle2 size={15} /> : <Save size={15} />}
                    {saving ? t('common.saving', 'Saving…') : isSaved ? t('common.saved', 'Saved!') : t('settings.templates.save_template', 'Save Template')}
                  </button>
                  <button
                    onClick={handleReset}
                    className="flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium border transition-all hover:opacity-80"
                    style={{ borderColor: 'hsl(var(--border))', color: 'hsl(var(--foreground-secondary))' }}
                  >
                    <RotateCcw size={14} />
                    {t('settings.templates.reset_default', 'Reset to Default')}
                  </button>
                </div>
              </div>

              {showPreview && (
                <div className="w-72 shrink-0 flex flex-col" style={{ borderLeft: '1px solid hsl(var(--border))' }}>
                  <div className="px-4 py-3 shrink-0" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                    <p className="text-xs font-semibold flex items-center gap-1.5" style={{ color: 'hsl(var(--foreground))' }}>
                      <Eye size={13} />
                      {t('settings.templates.live_preview', 'Live Preview')}
                    </p>
                    <p className="text-xs mt-0.5" style={{ color: 'hsl(var(--muted-foreground))' }}>
                      {t('settings.templates.preview_disclaimer', 'Variables replaced with example values')}
                    </p>
                  </div>

                  <div className="flex-1 overflow-y-auto p-4">
                    {activeChannel === 'sms' && (
                      <div className="flex flex-col gap-2">
                        <div
                          className="rounded-2xl rounded-tl-sm px-4 py-3 text-xs leading-relaxed max-w-[90%]"
                          style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
                          dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTemplate.variables) }}
                        />
                        <p className="text-xs" style={{ color: 'hsl(var(--muted-foreground))' }}>SMS · {currentContent.length} {t('common.chars', 'chars')}</p>
                      </div>
                    )}

                    {activeChannel === 'whatsapp' && (
                      <div
                        className="rounded-2xl rounded-tl-sm px-4 py-3 text-xs leading-relaxed"
                        style={{ backgroundColor: 'hsl(142, 72%, 95%)', color: 'hsl(var(--foreground))' }}
                        dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTemplate.variables) }}
                      />
                    )}

                    {activeChannel === 'email' && (
                      <div
                        className="rounded-xl p-4 text-xs leading-relaxed"
                        style={{ backgroundColor: 'hsl(var(--surface))', border: '1px solid hsl(var(--border))', color: 'hsl(var(--foreground))' }}
                      >
                        <div className="pb-3 mb-3" style={{ borderBottom: '1px solid hsl(var(--border))' }}>
                          <p className="font-semibold text-xs" style={{ color: 'hsl(var(--foreground))' }}>
                            {t(`settings.templates.label_${currentTemplate.id}`, currentTemplate.label)}
                          </p>
                        </div>
                        <div dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTemplate.variables) }} />
                      </div>
                    )}

                    {activeChannel === 'in-app' && (
                      <div
                        className="rounded-xl p-4 flex gap-3"
                        style={{ backgroundColor: 'hsl(var(--primary-light))', border: '1px solid hsla(var(--primary), 0.3)' }}
                      >
                        <div className="w-8 h-8 rounded-full flex items-center justify-center shrink-0" style={{ backgroundColor: 'hsl(var(--primary))', color: 'white' }}>
                          <Bell size={14} />
                        </div>
                        <div>
                          <p className="text-xs font-semibold mb-1" style={{ color: 'hsl(var(--foreground))' }}>{t('common.notification', 'Notification')}</p>
                          <p
                            className="text-xs leading-relaxed"
                            style={{ color: 'hsl(var(--foreground-secondary))' }}
                            dangerouslySetInnerHTML={{ __html: renderPreview(currentContent, currentTemplate.variables) }}
                          />
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}
