import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { toast } from '@/hooks/use-toast';
import { Eye, Send, Mail } from 'lucide-react';
import { EmailTemplateRenderer, ShortcodeProcessor } from '@/lib/email-templates/master-template';

interface NotificationTemplate {
  id: string;
  key: string;
  name: string;
  is_active: boolean;
  email_subject: string;
  email_body_html: string;
  webhook_url: string;
  last_payload_example?: Record<string, unknown> | null;
}

interface EmailTemplatePreviewProps {
  template: NotificationTemplate;
  onTest?: (template: NotificationTemplate) => void;
  isTestSending?: boolean;
}

export function EmailTemplatePreview({ template, onTest, isTestSending = false }: EmailTemplatePreviewProps) {
  const [previewMode, setPreviewMode] = useState<'master' | 'content'>('master');
  const [testEmail, setTestEmail] = useState('');
  const [showTestForm, setShowTestForm] = useState(false);

  // Generate preview with dummy shortcode data
  const generatePreview = () => {
    const processedSubject = ShortcodeProcessor.process(template.email_subject);
    const processedContent = ShortcodeProcessor.process(template.email_body_html);

    if (previewMode === 'master') {
      const fullHtml = EmailTemplateRenderer.render({
        subject: processedSubject,
        content: processedContent,
        brandName: 'ACCESS HUB'
      });
      return fullHtml;
    } else {
      return processedContent;
    }
  };

  const handleTestEmail = async () => {
    if (!testEmail) {
      toast({ title: 'Error', description: 'Masukkan email tujuan', variant: 'destructive' });
      return;
    }

    if (onTest) {
      await onTest({ ...template, test_email: testEmail });
    }
  };

  const previewHtml = generatePreview();

  return (
    <div className="space-y-4">
      {/* Preview Controls */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Label>Preview Mode:</Label>
          <select
            value={previewMode}
            onChange={(e) => setPreviewMode(e.target.value as 'master' | 'content')}
            className="border-2 px-3 py-1 rounded"
          >
            <option value="master">Master Template</option>
            <option value="content">Content Only</option>
          </select>
        </div>

        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowTestForm(!showTestForm)}
          >
            <Send className="w-4 h-4 mr-2" />
            {showTestForm ? 'Cancel' : 'Test Email'}
          </Button>
        </div>
      </div>

      {/* Test Email Form */}
      {showTestForm && (
        <div className="p-4 border-2 border-gray-300 rounded-lg bg-gray-50">
          <div className="space-y-3">
            <Label htmlFor="test-email">Test Email Address:</Label>
            <div className="flex gap-2">
              <Input
                id="test-email"
                type="email"
                value={testEmail}
                onChange={(e) => setTestEmail(e.target.value)}
                placeholder="test@example.com"
                className="flex-1"
              />
              <Button
                onClick={handleTestEmail}
                disabled={!testEmail || isTestSending}
              >
                <Mail className="w-4 h-4 mr-2" />
                {isTestSending ? 'Sending...' : 'Send Test'}
              </Button>
            </div>
            <p className="text-sm text-muted-foreground">
              This will send a test email with dummy data for all available shortcodes.
            </p>
          </div>
        </div>
      )}

      {/* Preview Info */}
      <Alert>
        <Eye className="w-4 h-4" />
        <AlertDescription>
          {previewMode === 'master'
            ? 'Showing complete email template with header, footer, and styling applied.'
            : 'Showing only the content section without master template styling.'
          }
        </AlertDescription>
      </Alert>

      {/* Email Preview */}
      <div className="border-2 border-gray-300 rounded-lg overflow-hidden">
        <div className="bg-gray-100 px-4 py-2 border-b border-gray-300">
          <span className="text-sm font-mono text-gray-600">
            {previewMode === 'master' ? 'Full Email Preview' : 'Content Preview'}
          </span>
        </div>
        <div className="bg-white" style={{ height: '600px', overflow: 'hidden' }}>
          <iframe
            srcDoc={previewHtml}
            className="w-full h-full border-0"
            style={{
              height: '100%',
              overflow: 'hidden'
            }}
            sandbox="allow-same-origin"
            scrolling="no"
          />
        </div>
      </div>

      {/* Shortcodes Used */}
      <div className="p-3 bg-blue-50 border border-blue-200 rounded">
        <h4 className="font-semibold text-sm mb-2">Shortcodes Used in This Template:</h4>
        <div className="grid grid-cols-2 gap-2 text-sm">
          {['{nama}', '{email}', '{order_id}', '{tanggal_pesanan}', '{total}', '{metode_pembayaran}',
           '{produk}', '{link_akses}', '{tanggal_konsultasi}', '{jam_konsultasi}', '{link_meet}',
           '{judul_event}', '{tanggal_event}', '{jam_event}', '{link_event}'].filter(shortcode =>
             template.email_subject.includes(shortcode) || template.email_body_html.includes(shortcode)
          ).map(shortcode => (
            <code key={shortcode} className="bg-blue-100 px-2 py-1 rounded text-xs">
              {shortcode}
            </code>
          ))}
        </div>
      </div>
    </div>
  );
}