﻿import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { Button } from "@/components/ui/button";
import { 
  Mail, 
  Bell, 
  AlertCircle, 
  CheckCircle, 
  XCircle, 
  RefreshCw, 
  Clock, 
  CreditCard,
  Paintbrush,
  Hourglass
} from "lucide-react";
import { EmailCustomizer } from "@/components/email-customizer";
import type { EmailContentSettings } from "@/components/email-customizer/sections";
import { usePro } from "@/contexts/pro-context";
import { ProIndicator } from "@/components/pro/pro-indicator";

interface EmailSettings {
  enabled: boolean;
  subject: string;
  heading: string;
  additionalContent: string;
  preheaderText?: string;
  reminderDays?: number;
  reminderCount?: number;
}

interface EmailsTabProps {
  settings: {
    emails?: {
      [key: string]: EmailSettings;
    };
  };
  onSettingChange: (key: string, value: unknown) => void;
  saving: boolean;
}

interface EmailType {
  id: string;
  title: string;
  description: string;
  recipient: "Admin" | "Customer";
  icon: typeof Bell;
  isPro: boolean;
  defaultSettings: EmailSettings;
}

const emailTypes: EmailType[] = [
  {
    id: "new_subscription",
    title: "New Subscription",
    description: "Sent to admin when a new subscription is created",
    recipient: "Admin",
    icon: Bell,
    isPro: false,
    defaultSettings: {
      enabled: true,
      subject: "New subscription #{subscription_id}",
      heading: "Thank you for your subscription",
      additionalContent: "Thanks for using Swift Commerce Subscriptions.",
      preheaderText: "",
    },
  },
  {
    id: "subscription_activated",
    title: "Subscription Activated",
    description: "Sent to customer when subscription becomes active",
    recipient: "Customer",
    icon: CheckCircle,
    isPro: false,
    defaultSettings: {
      enabled: true,
      subject: "Your subscription #{subscription_id} is active",
      heading: "Your subscription is now active",
      additionalContent: "Thank you for subscribing!",
      preheaderText: "",
    },
  },
  {
    id: "subscription_cancelled",
    title: "Subscription Cancelled",
    description: "Sent when a subscription is cancelled",
    recipient: "Customer",
    icon: XCircle,
    isPro: true,
    defaultSettings: {
      enabled: true,
      subject: "Your subscription #{subscription_id} has been cancelled",
      heading: "Your subscription has been cancelled",
      additionalContent: "We're sorry to see you go. Feel free to resubscribe anytime.",
      preheaderText: "",
    },
  },
  {
    id: "subscription_expired",
    title: "Subscription Expired",
    description: "Sent when a subscription reaches its end date",
    recipient: "Customer",
    icon: Clock,
    isPro: true,
    defaultSettings: {
      enabled: true,
      subject: "Your subscription #{subscription_id} has expired",
      heading: "Your subscription has expired",
      additionalContent: "Your subscription period has ended. Renew to continue enjoying our services.",
      preheaderText: "",
    },
  },
  {
    id: "subscription_on_hold",
    title: "Subscription On-Hold",
    description: "Sent when a subscription is put on hold",
    recipient: "Customer",
    icon: AlertCircle,
    isPro: true,
    defaultSettings: {
      enabled: true,
      subject: "Your subscription #{subscription_id} is on hold",
      heading: "Your subscription is on hold",
      additionalContent: "Your subscription has been paused. Contact us if you have any questions.",
      preheaderText: "",
    },
  },
  {
    id: "renewal_reminder",
    title: "Renewal Reminder",
    description: "Sent before automatic renewal occurs",
    recipient: "Customer",
    icon: RefreshCw,
    isPro: true,
    defaultSettings: {
      enabled: true,
      subject: "Reminder: Your subscription #{subscription_id} will renew soon",
      heading: "Your subscription renewal is coming up",
      additionalContent: "Your subscription will renew automatically.",
      preheaderText: "",
      reminderDays: 3,
      reminderCount: 1,
    },
  },
  {
    id: "trial_ending",
    title: "Trial Ending",
    description: "Sent when a free trial is about to end",
    recipient: "Customer",
    icon: Hourglass,
    isPro: true,
    defaultSettings: {
      enabled: true,
      subject: "Your free trial for subscription #{subscription_id} is ending soon",
      heading: "Your free trial is ending soon",
      additionalContent: "If you wish to continue, no action is required.",
      preheaderText: "",
    },
  },
  {
    id: "payment_failed",
    title: "Payment Failed",
    description: "Sent when a renewal payment fails",
    recipient: "Customer",
    icon: CreditCard,
    isPro: true,
    defaultSettings: {
      enabled: true,
      subject: "Action required: Your subscription payment failed",
      heading: "Your subscription renewal failed",
      additionalContent: "Please update your payment method to continue your subscription.",
      preheaderText: "",
    },
  },
  {
    id: "payment_retry",
    title: "Payment Retry",
    description: "Sent when payment is being retried",
    recipient: "Customer",
    icon: RefreshCw,
    isPro: true,
    defaultSettings: {
      enabled: false,
      subject: "Payment retry for subscription #{subscription_id}",
      heading: "We're retrying your payment",
      additionalContent: "We'll try to process your payment again shortly.",
      preheaderText: "",
    },
  },
];

interface EmailRowProps {
  email: EmailType;
  settings: EmailSettings;
  onToggle: (checked: boolean) => void;
  onCustomize: () => void;
  disabled: boolean;
}

function EmailRow({ email, settings, onToggle, onCustomize, disabled }: EmailRowProps) {
  const Icon = email.icon;

  return (
    <div 
      className="flex items-center justify-between p-4 border rounded-lg transition-colors hover:bg-muted/30"
    >
      <div className="flex items-center gap-4">
        <div className="p-2 rounded-lg bg-primary/10">
          <Icon className="h-5 w-5 text-primary" />
        </div>
        <div>
          <div className="flex items-center gap-2">
            <h4 className="font-medium">{email.title}</h4>
            {email.isPro && <ProIndicator size="sm" />}
          </div>
          <p className="text-sm text-muted-foreground">{email.description}</p>
        </div>
      </div>
      
      <div className="flex items-center gap-3">
        <span className="text-xs text-muted-foreground px-2 py-1 bg-muted rounded">
          {email.recipient}
        </span>
        
        <Switch
          checked={settings.enabled}
          onCheckedChange={onToggle}
          disabled={disabled}
        />
        
        <Button 
          size="sm" 
          className="gap-2"
          onClick={onCustomize}
          disabled={!settings.enabled}
        >
          <Paintbrush className="h-4 w-4" />
          Customize
        </Button>
      </div>
    </div>
  );
}

export function EmailsTab({ settings, onSettingChange, saving }: EmailsTabProps) {
  const { isPro } = usePro();
  const [customizerState, setCustomizerState] = useState<{
    isOpen: boolean;
    emailType: EmailType | null;
  }>({ isOpen: false, emailType: null });

  // Only show Free emails to Free users; Pro users see all
  const visibleEmailTypes = isPro ? emailTypes : emailTypes.filter(e => !e.isPro);

  const getEmailSettings = (emailId: string): EmailSettings => {
    const emailType = emailTypes.find(e => e.id === emailId);
    const savedSettings = settings.emails?.[emailId];
    return savedSettings || emailType?.defaultSettings || {
      enabled: true,
      subject: "",
      heading: "",
      additionalContent: "",
      preheaderText: "",
    };
  };

  const handleEmailToggle = (emailId: string, enabled: boolean) => {
    const currentEmails = settings.emails || {};
    const currentSettings = getEmailSettings(emailId);
    onSettingChange("emails", {
      ...currentEmails,
      [emailId]: { ...currentSettings, enabled },
    });
  };

  const handleOpenCustomizer = (email: EmailType) => {
    setCustomizerState({ isOpen: true, emailType: email });
  };

  const handleCloseCustomizer = () => {
    setCustomizerState({ isOpen: false, emailType: null });
  };

  const handleSaveContent = (content: EmailContentSettings) => {
    if (!customizerState.emailType) return;
    
    const emailId = customizerState.emailType.id;
    const currentEmails = settings.emails || {};
    const currentSettings = getEmailSettings(emailId);
    
    onSettingChange("emails", {
      ...currentEmails,
      [emailId]: {
        ...currentSettings,
        subject: content.subject,
        heading: content.heading,
        additionalContent: content.additionalContent,
        preheaderText: content.preheaderText,
      },
    });
  };

  // Convert email settings to content format for the customizer
  const getEmailContent = (emailId: string): EmailContentSettings => {
    const emailSettings = getEmailSettings(emailId);
    return {
      subject: emailSettings.subject,
      heading: emailSettings.heading,
      additionalContent: emailSettings.additionalContent,
      preheaderText: emailSettings.preheaderText || "",
    };
  };

  return (
    <div className="space-y-6">
      {/* Email Customizer (Full Screen Overlay) */}
      {customizerState.isOpen && customizerState.emailType && (
        <EmailCustomizer 
          onClose={handleCloseCustomizer}
          emailType={{
            id: customizerState.emailType.id,
            label: customizerState.emailType.title,
            defaultContent: {
              subject: customizerState.emailType.defaultSettings.subject,
              heading: customizerState.emailType.defaultSettings.heading,
              additionalContent: customizerState.emailType.defaultSettings.additionalContent,
              preheaderText: customizerState.emailType.defaultSettings.preheaderText || "",
            },
          }}
          initialContent={getEmailContent(customizerState.emailType.id)}
          onSaveContent={handleSaveContent}
        />
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-5 w-5" />
            Subscription Emails
          </CardTitle>
          <CardDescription>
            Configure email notifications for subscription events. Toggle emails on/off and click Customize to edit content and design.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {visibleEmailTypes.map((email) => (
              <EmailRow
                key={email.id}
                email={email}
                settings={getEmailSettings(email.id)}
                onToggle={(enabled) => handleEmailToggle(email.id, enabled)}
                onCustomize={() => handleOpenCustomizer(email)}
                disabled={saving}
              />
            ))}
          </div>
          {!isPro && (
            <p className="text-xs text-muted-foreground mt-4">
              More email notifications available in Swift Commerce Pro.
            </p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
