/**
 * Email Customizer Preview Panel
 * Contains the preview frame with device switching and test email functionality
 */

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Label } from '@/components/ui/label';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Send, Loader2, Moon } from 'lucide-react';
import { DeviceSwitcher, EmailPreviewFrame } from './preview';
import type { EmailCustomizerSettings, DevicePreview } from './types';
import type { ProductCardConfig, CouponDisplayConfig } from './sections';

interface CustomizerPreviewProps {
  settings: EmailCustomizerSettings;
  devicePreview: DevicePreview;
  onDeviceChange: (device: DevicePreview) => void;
  darkModePreview: boolean;
  onDarkModeChange: (enabled: boolean) => void;
  onSendTestEmail: (email: string, emailType: string) => Promise<void>;
  isSendingTest: boolean;
  selectedEmailType?: string;
  emailHeading?: string;
  emailBody?: string;
  emailAdditionalContent?: string;
  emailPreheaderText?: string;
  productCard?: ProductCardConfig;
  couponDisplay?: CouponDisplayConfig;
}

export function CustomizerPreview({
  settings,
  devicePreview,
  onDeviceChange,
  darkModePreview,
  onDarkModeChange,
  onSendTestEmail,
  isSendingTest,
  selectedEmailType = 'subscription_new',
  emailHeading = 'Your Subscription is Active',
  emailBody,
  emailAdditionalContent = '',
  emailPreheaderText = '',
  productCard,
  couponDisplay,
}: CustomizerPreviewProps) {
  const [showTestDialog, setShowTestDialog] = useState(false);
  const [testEmail, setTestEmail] = useState('');
  const [testEmailError, setTestEmailError] = useState('');

  const handleSendTestEmail = async () => {
    if (!testEmail) {
      setTestEmailError('Please enter an email address');
      return;
    }

    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(testEmail)) {
      setTestEmailError('Please enter a valid email address');
      return;
    }

    setTestEmailError('');
    try {
      await onSendTestEmail(testEmail, selectedEmailType);
      setShowTestDialog(false);
      setTestEmail('');
    } catch {
      setTestEmailError('Failed to send test email. Please try again.');
    }
  };

  return (
    <div className="flex flex-col h-full bg-muted/20">
      {/* Preview Toolbar */}
      <div className="flex items-center justify-between p-4 border-b bg-background">
        <div className="flex items-center gap-4">
          <DeviceSwitcher device={devicePreview} onChange={onDeviceChange} />
          
          {/* Dark Mode Toggle */}
          <div className="flex items-center gap-2 pl-4 border-l">
            <Moon className={`h-4 w-4 ${darkModePreview ? 'text-primary' : 'text-muted-foreground'}`} />
            <Label htmlFor="dark-mode-toggle" className="text-sm cursor-pointer">
              Dark Mode
            </Label>
            <Switch
              id="dark-mode-toggle"
              checked={darkModePreview}
              onCheckedChange={onDarkModeChange}
            />
          </div>
        </div>

        <Button
          variant="outline"
          size="sm"
          onClick={() => setShowTestDialog(true)}
        >
          <Send className="h-4 w-4 mr-2" />
          Send Test Email
        </Button>
      </div>

      {/* Preview Area */}
      <div className="flex-1 p-6 overflow-hidden">
        <EmailPreviewFrame
          settings={settings}
          device={devicePreview}
          darkMode={darkModePreview}
          emailType={selectedEmailType}
          heading={emailHeading}
          body={emailBody}
          additionalContent={emailAdditionalContent}
          preheaderText={emailPreheaderText}
          productCard={productCard}
          couponDisplay={couponDisplay}
        />
      </div>

      {/* Test Email Dialog */}
      <Dialog open={showTestDialog} onOpenChange={setShowTestDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Send Test Email</DialogTitle>
            <DialogDescription>
              Send a test email with the current customization settings to preview
              how it will look in an email client.
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Input
                type="email"
                placeholder="Enter email address"
                value={testEmail}
                onChange={(e) => {
                  setTestEmail(e.target.value);
                  setTestEmailError('');
                }}
                className={testEmailError ? 'border-destructive' : ''}
              />
              {testEmailError && (
                <p className="text-sm text-destructive">{testEmailError}</p>
              )}
            </div>

            <p className="text-sm text-muted-foreground">
              The test email will be sent with sample data and your
              current customization settings.
            </p>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowTestDialog(false)}
              disabled={isSendingTest}
            >
              Cancel
            </Button>
            <Button onClick={handleSendTestEmail} disabled={isSendingTest}>
              {isSendingTest ? (
                <>
                  <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  Sending...
                </>
              ) : (
                <>
                  <Send className="h-4 w-4 mr-2" />
                  Send Test
                </>
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

export default CustomizerPreview;
