import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Mail, Paintbrush, Clock, CheckCircle, Bell, XCircle } from "lucide-react"
import { EmailCustomizer } from "@/components/email-customizer"
import type { EmailContentSettings, PlaceholderConfig, PlaceholderCategoryLabel } from "@/components/email-customizer/sections"
import { usePro } from "@/contexts/pro-context"
import { ProIndicator } from "@/components/pro/pro-indicator"
import { 
  EmailVerificationSettings, 
  defaultEmailTemplate,
  defaultPendingApprovalEmailTemplate,
  defaultAccountApprovedEmailTemplate,
  defaultAdminNotificationEmailTemplate,
  defaultAccountRejectedEmailTemplate,
} from "../../config"

// ---------------------------------------------------------------------------
// Placeholders for Email Verification emails
// ---------------------------------------------------------------------------

const evPlaceholders: PlaceholderConfig[] = [
  { tag: '{{user_name}}',          description: "User's display name",        example: 'John',                              category: 'user' },
  { tag: '{{user_email}}',         description: "User's email address",       example: 'john@example.com',                  category: 'user' },
  { tag: '{{verification_link}}',  description: 'The verification link/button', example: 'https://example.com/verify?key=abc', category: 'verification' },
  { tag: '{{site_name}}',          description: 'Your website name',          example: 'My Store',                          category: 'site' },
  { tag: '{{site_url}}',           description: 'Your website URL',           example: 'https://mystore.com',               category: 'site' },
  { tag: '{{expiry_time}}',        description: 'Time until link expires',    example: '24 hours',                          category: 'verification' },
]

const approvalPlaceholders: PlaceholderConfig[] = [
  { tag: '{{user_name}}',    description: "User's display name",  example: 'John',              category: 'user' },
  { tag: '{{user_email}}',   description: "User's email address", example: 'john@example.com',  category: 'user' },
  { tag: '{{site_name}}',    description: 'Your website name',    example: 'My Store',          category: 'site' },
  { tag: '{{site_url}}',     description: 'Your website URL',     example: 'https://mystore.com', category: 'site' },
  { tag: '{{login_link}}',   description: 'Login page URL',       example: 'https://mystore.com/my-account/', category: 'site' },
  { tag: '{{admin_link}}',   description: 'Admin dashboard link', example: 'https://mystore.com/wp-admin/', category: 'site' },
]

const evCategoryLabels: Record<string, PlaceholderCategoryLabel> = {
  user:         { label: 'User',         color: 'bg-blue-100 text-blue-700' },
  verification: { label: 'Verification', color: 'bg-green-100 text-green-700' },
  site:         { label: 'Site',         color: 'bg-orange-100 text-orange-700' },
}

const approvalCategoryLabels: Record<string, PlaceholderCategoryLabel> = {
  user: { label: 'User', color: 'bg-blue-100 text-blue-700' },
  site: { label: 'Site', color: 'bg-orange-100 text-orange-700' },
}

// ---------------------------------------------------------------------------
// Email template definitions
// ---------------------------------------------------------------------------

type EmailTemplateId = 'verification' | 'pending_approval' | 'account_approved' | 'admin_notification' | 'account_rejected'

interface EmailTemplateRow {
  id: EmailTemplateId
  icon: React.ElementType
  label: string
  description: string
  isPro?: boolean
  /** Only show when this verification mode is active */
  visibleInMode?: 'email_verification' | 'admin_approval'
  /** Settings key for the enable/disable toggle */
  settingsKey: keyof EmailVerificationSettings
}

const emailTemplateRows: EmailTemplateRow[] = [
  {
    id: 'verification',
    icon: Mail,
    label: 'Verification Email',
    description: 'Sent to new users to verify their email address',
    visibleInMode: 'email_verification',
    settingsKey: 'sendVerificationEmail',
  },
  {
    id: 'pending_approval',
    icon: Clock,
    label: 'Pending Approval Email',
    description: 'Sent to new users when their account is awaiting admin approval',
    isPro: true,
    visibleInMode: 'admin_approval',
    settingsKey: 'sendPendingApprovalEmail',
  },
  {
    id: 'account_approved',
    icon: CheckCircle,
    label: 'Account Approved Email',
    description: 'Sent to users when their account is approved by an admin',
    isPro: true,
    visibleInMode: 'admin_approval',
    settingsKey: 'sendAccountApprovedEmail',
  },
  {
    id: 'admin_notification',
    icon: Bell,
    label: 'Admin Notification Email',
    description: 'Sent to the site admin when a new user registers and needs approval',
    isPro: true,
    visibleInMode: 'admin_approval',
    settingsKey: 'sendAdminNotificationEmail',
  },
  {
    id: 'account_rejected',
    icon: XCircle,
    label: 'Account Rejected Email',
    description: 'Sent to users when their account registration is rejected by an admin',
    isPro: true,
    visibleInMode: 'admin_approval',
    settingsKey: 'sendAccountRejectedEmail',
  },
]

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

interface CustomizationTabProps {
  settings: EmailVerificationSettings
  updateSettings: <K extends keyof EmailVerificationSettings>(key: K, value: EmailVerificationSettings[K]) => void
}

export function CustomizationTab({ settings, updateSettings }: CustomizationTabProps) {
  const { isPro } = usePro()
  const [activeCustomizer, setActiveCustomizer] = useState<EmailTemplateId | null>(null)

  // Build email content and handlers per template ID
  const getEmailConfig = (templateId: EmailTemplateId) => {
    switch (templateId) {
      case 'verification':
        return {
          emailTypeId: 'email_verification',
          emailTypeLabel: 'Verification Email',
          content: {
            subject: settings.emailSubject,
            heading: settings.emailHeading || 'Verify Your Email Address',
            body: settings.emailBody,
            additionalContent: settings.emailAdditionalContent || '',
            preheaderText: settings.emailPreheaderText || '',
          },
          defaultContent: {
            subject: defaultEmailTemplate.subject,
            heading: 'Verify Your Email Address',
            body: defaultEmailTemplate.body,
            additionalContent: '',
            preheaderText: '',
          },
          placeholders: evPlaceholders,
          categoryLabels: evCategoryLabels,
          subjectHint: 'Available: {{site_name}}, {{user_name}}, {{user_email}}',
          onSave: (content: EmailContentSettings) => {
            updateSettings('emailSubject', content.subject)
            updateSettings('emailHeading', content.heading)
            if (content.body !== undefined) updateSettings('emailBody', content.body)
            updateSettings('emailAdditionalContent', content.additionalContent)
            updateSettings('emailPreheaderText', content.preheaderText)
          },
        }
      case 'pending_approval':
        return {
          emailTypeId: 'email_pending_approval',
          emailTypeLabel: 'Pending Approval Email',
          content: {
            subject: settings.pendingApprovalEmailSubject,
            heading: settings.pendingApprovalEmailHeading || 'Account Pending Approval',
            body: settings.pendingApprovalEmailBody,
            additionalContent: '',
            preheaderText: '',
          },
          defaultContent: {
            subject: defaultPendingApprovalEmailTemplate.subject,
            heading: 'Account Pending Approval',
            body: defaultPendingApprovalEmailTemplate.body,
            additionalContent: '',
            preheaderText: '',
          },
          placeholders: approvalPlaceholders,
          categoryLabels: approvalCategoryLabels,
          subjectHint: 'Available: {{site_name}}, {{user_name}}',
          onSave: (content: EmailContentSettings) => {
            updateSettings('pendingApprovalEmailSubject', content.subject)
            updateSettings('pendingApprovalEmailHeading', content.heading)
            if (content.body !== undefined) updateSettings('pendingApprovalEmailBody', content.body)
          },
        }
      case 'account_approved':
        return {
          emailTypeId: 'email_account_approved',
          emailTypeLabel: 'Account Approved Email',
          content: {
            subject: settings.accountApprovedEmailSubject,
            heading: settings.accountApprovedEmailHeading || 'Account Approved',
            body: settings.accountApprovedEmailBody,
            additionalContent: '',
            preheaderText: '',
          },
          defaultContent: {
            subject: defaultAccountApprovedEmailTemplate.subject,
            heading: 'Account Approved',
            body: defaultAccountApprovedEmailTemplate.body,
            additionalContent: '',
            preheaderText: '',
          },
          placeholders: approvalPlaceholders,
          categoryLabels: approvalCategoryLabels,
          subjectHint: 'Available: {{site_name}}, {{user_name}}',
          onSave: (content: EmailContentSettings) => {
            updateSettings('accountApprovedEmailSubject', content.subject)
            updateSettings('accountApprovedEmailHeading', content.heading)
            if (content.body !== undefined) updateSettings('accountApprovedEmailBody', content.body)
          },
        }
      case 'admin_notification':
        return {
          emailTypeId: 'email_admin_notification',
          emailTypeLabel: 'Admin Notification Email',
          content: {
            subject: settings.adminNotificationEmailSubject,
            heading: settings.adminNotificationEmailHeading || 'New Registration Pending Approval',
            body: settings.adminNotificationEmailBody,
            additionalContent: '',
            preheaderText: '',
          },
          defaultContent: {
            subject: defaultAdminNotificationEmailTemplate.subject,
            heading: 'New Registration Pending Approval',
            body: defaultAdminNotificationEmailTemplate.body,
            additionalContent: '',
            preheaderText: '',
          },
          placeholders: approvalPlaceholders,
          categoryLabels: approvalCategoryLabels,
          subjectHint: 'Available: {{site_name}}, {{user_name}}, {{user_email}}',
          onSave: (content: EmailContentSettings) => {
            updateSettings('adminNotificationEmailSubject', content.subject)
            updateSettings('adminNotificationEmailHeading', content.heading)
            if (content.body !== undefined) updateSettings('adminNotificationEmailBody', content.body)
          },
        }
      case 'account_rejected':
        return {
          emailTypeId: 'email_account_rejected',
          emailTypeLabel: 'Account Rejected Email',
          content: {
            subject: settings.accountRejectedEmailSubject,
            heading: settings.accountRejectedEmailHeading || 'Registration Update',
            body: settings.accountRejectedEmailBody,
            additionalContent: '',
            preheaderText: '',
          },
          defaultContent: {
            subject: defaultAccountRejectedEmailTemplate.subject,
            heading: 'Registration Update',
            body: defaultAccountRejectedEmailTemplate.body,
            additionalContent: '',
            preheaderText: '',
          },
          placeholders: approvalPlaceholders,
          categoryLabels: approvalCategoryLabels,
          subjectHint: 'Available: {{site_name}}, {{user_name}}',
          onSave: (content: EmailContentSettings) => {
            updateSettings('accountRejectedEmailSubject', content.subject)
            updateSettings('accountRejectedEmailHeading', content.heading)
            if (content.body !== undefined) updateSettings('accountRejectedEmailBody', content.body)
          },
        }
    }
  }

  // Filter visible templates based on verification mode and Pro status
  const visibleTemplates = emailTemplateRows.filter((row) => {
    // Show based on the current verification mode
    if (row.visibleInMode && row.visibleInMode !== settings.verificationMode) return false
    // Hide Pro templates from Free users
    if (row.isPro && !isPro) return false
    return true
  })

  const activeConfig = activeCustomizer ? getEmailConfig(activeCustomizer) : null

  return (
    <>
      {/* Email Customizer Full-Screen Overlay */}
      {activeCustomizer && activeConfig && (
        <EmailCustomizer
          onClose={() => setActiveCustomizer(null)}
          emailType={{
            id: activeConfig.emailTypeId,
            label: activeConfig.emailTypeLabel,
            defaultContent: activeConfig.defaultContent,
          }}
          initialContent={activeConfig.content}
          onSaveContent={activeConfig.onSave}
          placeholders={activeConfig.placeholders}
          placeholderCategories={activeConfig.categoryLabels}
          subjectPlaceholderHint={activeConfig.subjectHint}
        />
      )}

      {/* Email Templates List */}
      <Card>
        <CardHeader>
          <CardTitle>Email Templates</CardTitle>
          <CardDescription>
            Customize the emails sent by the Email Verification feature
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg border divide-y">
            {visibleTemplates.map((row) => {
              const Icon = row.icon
              const isEnabled = settings[row.settingsKey] !== false
              return (
                <div key={row.id} className="flex items-center justify-between p-4">
                  <div className="flex items-center gap-3">
                    <div className="flex h-10 w-10 items-center justify-center 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 text-sm">{row.label}</h4>
                        {row.isPro && <ProIndicator size="sm" />}
                      </div>
                      <p className="text-sm text-muted-foreground">{row.description}</p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3">
                    <Switch
                      checked={isEnabled}
                      onCheckedChange={(checked) => updateSettings(row.settingsKey, checked as any)}
                    />
                    <Button
                      size="sm"
                      className="gap-2 text-white"
                      style={{ backgroundColor: '#002269' }}
                      onClick={() => setActiveCustomizer(row.id)}
                      disabled={!isEnabled}
                    >
                      <Paintbrush className="h-4 w-4" />
                      Customize Email
                    </Button>
                  </div>
                </div>
              )
            })}
          </div>
        </CardContent>
      </Card>
    </>
  )
}
