import React, { useState, useEffect } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { RichTextEditor } from '@/components/ui/rich-text-editor';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { X, Plus, Eye, Edit } from 'lucide-react';
import { toast } from 'sonner';
import { __ } from '@/lib/i18n';

interface TemplateEditorProps {
  open: boolean;
  onClose: () => void;
  eventId: string;
  channelId: string;
  eventLabel: string;
  channelLabel: string;
  template?: any;
}

export default function TemplateEditor({
  open,
  onClose,
  eventId,
  channelId,
  eventLabel,
  channelLabel,
  template: initialTemplate,
}: TemplateEditorProps) {
  const queryClient = useQueryClient();
  const [subject, setSubject] = useState('');
  const [body, setBody] = useState('');
  const [variables, setVariables] = useState<{ [key: string]: string }>({});
  const [activeTab, setActiveTab] = useState('editor');

  useEffect(() => {
    if (initialTemplate) {
      setSubject(initialTemplate.subject || '');
      // Set body with default value - ensure it's set properly
      const defaultBody = initialTemplate.body || '';
      setBody(defaultBody);
      setVariables(initialTemplate.variables || {});
    }
  }, [initialTemplate, open]);

  const saveMutation = useMutation({
    mutationFn: async () => {
      return api.post('/notifications/templates', {
        eventId,
        channelId,
        subject,
        body,
      });
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
      toast.success(__('Template saved successfully'));
      onClose();
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to save template'));
    },
  });

  const resetMutation = useMutation({
    mutationFn: async () => {
      return api.del(`/notifications/templates/${eventId}/${channelId}`);
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['notification-templates'] });
      toast.success(__('Template reset to default'));
      onClose();
    },
    onError: (error: any) => {
      toast.error(error?.message || __('Failed to reset template'));
    },
  });

  // Get variable keys for the rich text editor
  const variableKeys = Object.keys(variables);

  // Parse [card] tags for preview
  const parseCardsForPreview = (content: string) => {
    // Match [card ...] ... [/card] patterns
    const cardRegex = /\[card([^\]]*)\](.*?)\[\/card\]/gs;

    return content.replace(cardRegex, (match, attributes, cardContent) => {
      // Parse attributes
      let cardClass = 'card';
      const typeMatch = attributes.match(/type=["']([^"']+)["']/);
      if (typeMatch) {
        cardClass += ` card-${typeMatch[1]}`;
      }

      const bgMatch = attributes.match(/bg=["']([^"']+)["']/);
      const bgStyle = bgMatch ? `background-image: url(${bgMatch[1]}); background-size: cover; background-position: center;` : '';

      return `<div class="${cardClass}" style="${bgStyle}">${cardContent}</div>`;
    });
  };

  // Generate preview HTML
  const generatePreviewHTML = () => {
    let previewBody = body;

    // Replace store-identity variables with actual data
    const storeVariables: { [key: string]: string } = {
      store_name: 'My WordPress Store',
      site_url: window.location.origin,
      store_email: 'store@example.com',
    };

    Object.entries(storeVariables).forEach(([key, value]) => {
      previewBody = previewBody.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
    });

    // Highlight dynamic variables (non-store variables)
    Object.keys(variables).forEach(key => {
      if (!storeVariables[key]) {
        const sampleValue = `<span style="background: #fef3c7; padding: 2px 4px; border-radius: 2px;">[${key}]</span>`;
        previewBody = previewBody.replace(new RegExp(`\\{${key}\\}`, 'g'), sampleValue);
      }
    });

    // Parse [card] tags
    previewBody = parseCardsForPreview(previewBody);

    return `
      <!DOCTYPE html>
      <html>
      <head>
        <style>
          body { font-family: 'Inter', Arial, sans-serif; background: #f8f8f8; margin: 0; padding: 20px; }
          .container { max-width: 600px; margin: 0 auto; }
          .header { padding: 32px; text-align: center; background: #f8f8f8; }
          .card-gutter { padding: 0 16px; }
          .card { background: #ffffff; border-radius: 8px; margin-bottom: 24px; padding: 32px 40px; }
          .card-success { background-color: #f0fdf4; }
          .card-highlight { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: #fff; }
          .card-highlight * { color: #fff !important; }
          .card-info { background-color: #f0f7ff; }
          .card-warning { background-color: #fff8e1; }
          h1 { font-size: 26px; margin-top: 0; margin-bottom: 16px; color: #333; }
          h2 { font-size: 18px; margin-top: 0; margin-bottom: 16px; color: #333; }
          h3 { font-size: 16px; margin-top: 0; margin-bottom: 8px; color: #333; }
          p { font-size: 16px; line-height: 1.6; color: #555; margin-bottom: 16px; }
          .button { display: inline-block; background: #7f54b3; color: #fff !important; padding: 14px 28px; border-radius: 6px; text-decoration: none; font-weight: 600; }
          .info-box { background: #f6f6f6; border-radius: 6px; padding: 20px; margin: 16px 0; }
          .footer { padding: 32px; text-align: center; color: #888; font-size: 13px; }
        </style>
      </head>
      <body>
        <div class="container">
          <div class="header">
            <strong style="font-size: 24px; color: #333;">My WordPress Store</strong>
          </div>
          <div class="card-gutter">
            ${previewBody}
          </div>
          <div class="footer">
            <p>© ${new Date().getFullYear()} My WordPress Store. All rights reserved.</p>
          </div>
        </div>
      </body>
      </html>
    `;
  };

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-4xl h-[85vh] flex flex-col p-0">
        {/* Header - Fixed */}
        <DialogHeader className="px-6 pt-6 pb-4 border-b">
          <DialogTitle>
            {__('Edit Template')}: {eventLabel} - {channelLabel}
          </DialogTitle>
          <div className="space-y-2 pt-2">
            <Label htmlFor="subject" className="text-sm">{__('Subject / Title')}</Label>
            <Input
              id="subject"
              value={subject}
              onChange={(e) => setSubject(e.target.value)}
              placeholder={__('Enter notification subject')}
            />
          </div>
        </DialogHeader>

        {/* Body - Scrollable */}
        <div className="flex-1 overflow-y-auto px-6 py-4">
          <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
            <TabsList className="grid w-full max-w-md grid-cols-2">
              <TabsTrigger value="editor" className="flex items-center gap-2">
                <Edit className="h-4 w-4" />
                {__('Editor')}
              </TabsTrigger>
              <TabsTrigger value="preview" className="flex items-center gap-2">
                <Eye className="h-4 w-4" />
                {__('Preview')}
              </TabsTrigger>
            </TabsList>

            {/* Editor Tab */}
            <TabsContent value="editor" className="space-y-4 mt-4">
              <div className="space-y-2">
                <Label htmlFor="body">{__('Message Body')}</Label>
                <RichTextEditor
                  content={body}
                  onChange={setBody}
                  placeholder={__('Enter notification message')}
                  variables={variableKeys}
                />
              </div>
            </TabsContent>

            {/* Preview Tab */}
            <TabsContent value="preview" className="mt-4">
              <div className="space-y-2">
                <Label>{__('Email Preview')}</Label>
                <div className="rounded-lg border bg-white overflow-hidden">
                  <iframe
                    srcDoc={generatePreviewHTML()}
                    className="w-full border-0"
                    style={{ minHeight: '400px', height: 'auto' }}
                    title="Email Preview"
                    onLoad={(e) => {
                      const iframe = e.target as HTMLIFrameElement;
                      if (iframe.contentWindow) {
                        const height = iframe.contentWindow.document.body.scrollHeight;
                        iframe.style.height = height + 40 + 'px';
                      }
                    }}
                  />
                </div>
                <p className="text-xs text-muted-foreground">
                  {__('This is how your email will look. Variables are highlighted in yellow.')}
                </p>
              </div>
            </TabsContent>
          </Tabs>
        </div>

        {/* Footer - Fixed */}
        <DialogFooter className="px-6 py-4 border-t gap-2">
          <Button variant="outline" onClick={() => resetMutation.mutate()} disabled={saveMutation.isPending || resetMutation.isPending}>
            {__('Reset to Default')}
          </Button>
          <Button variant="outline" onClick={onClose}>
            {__('Cancel')}
          </Button>
          <Button onClick={() => saveMutation.mutate()} disabled={saveMutation.isPending || resetMutation.isPending}>
            {saveMutation.isPending ? __('Saving...') : __('Save Template')}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
