/**
 * Email Template Editor Page
 *
 * Dedicated page for editing email templates with Puck editor.
 * Matches the PageEditor structure to ensure proper Puck functionality.
 */

import React, { useState, useEffect, useCallback } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Puck } from '@measured/puck';
import '@measured/puck/puck.css';
import { Loader2, ArrowLeft, Save, Eye, X } from 'lucide-react';
import toast from 'react-hot-toast';
import api from '../api/client';

// Use the email-specific config
import { getEmailEditorConfig } from '../puck/emailConfig';

interface EmailTemplateDetail {
  email_type: string;
  display_name: string;
  description: string;
  subject: string;
  puck_data: {
    root: Record<string, unknown>;
    content: Array<{
      type: string;
      props: Record<string, unknown>;
    }>;
  };
  available_tags: Array<{ tag: string; description: string }>;
}

/**
 * Transform puck_data to ensure id is inside props (Puck requirement).
 * Puck expects: { type: 'X', props: { id: 'X-1', ... } }
 * API may return: { type: 'X', id: 'X-1', props: { ... } }
 */
const transformPuckDataForEditor = (puckData: any): any => {
  if (!puckData?.content) return puckData;

  return {
    ...puckData,
    content: puckData.content.map((item: any, index: number) => {
      const rootId = item.id;
      const hasPropsId = item.props?.id;

      if (rootId && !hasPropsId) {
        const { id, ...rest } = item;
        return {
          ...rest,
          props: {
            ...rest.props,
            id: rootId,
          },
        };
      } else if (!hasPropsId) {
        return {
          ...item,
          props: {
            ...item.props,
            id: `${item.type}-${index}-${crypto.randomUUID().substring(0, 8)}`,
          },
        };
      }

      return item;
    }),
  };
};

const EmailTemplateEditor: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { emailType } = useParams<{ emailType: string }>();
  const queryClient = useQueryClient();

  const [data, setData] = useState<any>(null);
  const [subject, setSubject] = useState<string>('');
  const [hasChanges, setHasChanges] = useState(false);
  const [showPreview, setShowPreview] = useState(false);
  const [previewHtml, setPreviewHtml] = useState<string>('');

  // Use the email-specific config
  const editorConfig = getEmailEditorConfig();

  // Fetch template data
  const { data: template, isLoading } = useQuery<EmailTemplateDetail>({
    queryKey: ['email-template', emailType],
    queryFn: async () => {
      const response = await api.get(`/messages/email-templates/${emailType}/`);
      return response.data;
    },
    enabled: !!emailType,
  });

  // Load template data when available - transform to ensure correct Puck format
  useEffect(() => {
    if (template?.puck_data) {
      // Transform the data to ensure id is inside props (Puck requirement)
      const transformedData = transformPuckDataForEditor(template.puck_data);
      setData(transformedData);
      setSubject(template.subject);
    }
  }, [template]);

  // Update mutation
  const updateMutation = useMutation({
    mutationFn: async (updatedData: { subject: string; puck_data: any }) => {
      const response = await api.patch(`/messages/email-templates/${emailType}/`, updatedData);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['email-template', emailType] });
      toast.success(t('emailTemplates.saveSuccess', 'Template saved'));
      setHasChanges(false);
    },
    onError: () => {
      toast.error(t('emailTemplates.saveError', 'Failed to save template'));
    },
  });

  // Preview mutation
  const previewMutation = useMutation({
    mutationFn: async () => {
      const response = await api.post(`/messages/email-templates/${emailType}/preview/`, {
        subject,
        puck_data: data,
      });
      return response.data;
    },
    onSuccess: (result) => {
      setPreviewHtml(result.html);
      setShowPreview(true);
    },
    onError: () => {
      toast.error(t('emailTemplates.previewError', 'Failed to generate preview'));
    },
  });

  const handleDataChange = useCallback((newData: any) => {
    setData(newData);
    setHasChanges(true);
  }, []);

  const handleSave = useCallback(() => {
    if (data) {
      updateMutation.mutate({ subject, puck_data: data });
    }
  }, [data, subject, updateMutation]);

  const handleBack = useCallback(() => {
    navigate('/dashboard/settings/email-templates');
  }, [navigate]);

  const isDataReady = !!data && !!emailType;

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-full">
        <Loader2 className="w-8 h-8 animate-spin text-indigo-600" />
      </div>
    );
  }

  return (
    <div className="flex flex-col h-screen overflow-hidden">
      {/* Header */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 flex items-center justify-between shrink-0">
        <div className="flex items-center gap-4">
          <button
            onClick={handleBack}
            className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          >
            <ArrowLeft className="h-5 w-5" />
          </button>
          <div>
            <h2 className="font-semibold text-gray-900 dark:text-white">
              {template?.display_name || 'Email Template'}
            </h2>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              {template?.description}
            </p>
          </div>
        </div>

        <div className="flex items-center gap-3">
          {hasChanges && (
            <span className="flex items-center gap-1.5 px-2 py-1 bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 rounded text-xs font-medium">
              <span className="w-2 h-2 bg-amber-500 rounded-full animate-pulse"></span>
              Unsaved changes
            </span>
          )}
          <button
            onClick={() => previewMutation.mutate()}
            disabled={previewMutation.isPending}
            className="flex items-center gap-1.5 px-3 py-1.5 text-gray-700 dark:text-gray-300 bg-gray-100 dark:bg-gray-700 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-600 text-sm font-medium transition-colors"
          >
            <Eye className="h-4 w-4" />
            Preview
          </button>
          <button
            onClick={handleSave}
            disabled={updateMutation.isPending || !hasChanges}
            className="flex items-center gap-1.5 px-4 py-1.5 bg-brand-600 text-white rounded-lg hover:bg-brand-700 disabled:opacity-50 text-sm font-medium transition-colors"
          >
            {updateMutation.isPending ? (
              <Loader2 className="h-4 w-4 animate-spin" />
            ) : (
              <Save className="h-4 w-4" />
            )}
            Save
          </button>
        </div>
      </div>

      {/* Subject Line */}
      <div className="bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 px-4 py-3 shrink-0">
        <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
          Email Subject
        </label>
        <input
          type="text"
          value={subject}
          onChange={(e) => {
            setSubject(e.target.value);
            setHasChanges(true);
          }}
          placeholder="Enter email subject..."
          className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-400 dark:placeholder-gray-500 focus:ring-2 focus:ring-brand-500 focus:border-brand-500"
        />
      </div>

      {/* Puck Editor - Full height, force light mode for email preview accuracy */}
      <div className="flex-1 min-h-0 email-editor-light-mode">
        {isDataReady ? (
          <div className="h-full overflow-hidden">
            <Puck
              key={`email-puck-${emailType}`}
              config={editorConfig}
              data={data}
              onPublish={handleSave}
              onChange={handleDataChange}
            />
          </div>
        ) : (
          <div className="flex items-center justify-center h-full bg-gray-50">
            <div className="text-center">
              <Loader2 className="w-8 h-8 animate-spin text-indigo-600 mx-auto mb-2" />
              <p className="text-gray-600">Loading template...</p>
            </div>
          </div>
        )}
      </div>

      {/* Preview Modal - uses sandboxed iframe for security */}
      {showPreview && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-xl max-w-4xl w-full max-h-[90vh] overflow-hidden flex flex-col">
            <div className="flex items-center justify-between px-4 py-3 border-b border-gray-200 dark:border-gray-700">
              <h3 className="font-semibold text-gray-900 dark:text-white">Email Preview</h3>
              <button
                onClick={() => setShowPreview(false)}
                className="p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg"
              >
                <X className="h-5 w-5" />
              </button>
            </div>
            <div className="flex-1 overflow-auto p-4 bg-gray-100 dark:bg-gray-900">
              <iframe
                srcDoc={previewHtml}
                title="Email Preview"
                className="w-full h-[600px] bg-white mx-auto max-w-2xl shadow-lg border-0"
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EmailTemplateEditor;
