/**
 * Registration Form Emails Tab
 *
 * Email template management for the Registration Form feature.
 * Follows the same pattern as the Email Verification customization tab.
 */

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 } 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 { RegistrationFormSettings } from "../../config"

// ---------------------------------------------------------------------------
// Placeholders for Welcome Email
// ---------------------------------------------------------------------------

const welcomePlaceholders: 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: '{{user_login}}',  description: "User's login/username", example: 'johndoe',               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' },
]

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

// ---------------------------------------------------------------------------
// Default welcome email content
// ---------------------------------------------------------------------------

const defaultWelcomeContent = {
  subject: 'Welcome to {{site_name}}!',
  heading: 'Welcome to {{site_name}}!',
  body: 'Hi {{user_name}},\n\nWelcome to {{site_name}}! Your account has been successfully created.\n\nUsername: {{user_login}}\n\n{{login_link}}\n\nThank you for registering!\n\nBest regards,\n{{site_name}}',
  additionalContent: '',
  preheaderText: '',
}

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

interface EmailsTabProps {
  settings: RegistrationFormSettings
  onUpdateSettings: (updates: Partial<RegistrationFormSettings>) => void
}

export function EmailsTab({ settings, onUpdateSettings }: EmailsTabProps) {
  const { isPro } = usePro()
  const [customizerOpen, setCustmizerOpen] = useState(false)

  const emailConfig = {
    emailTypeId: 'registration_welcome',
    emailTypeLabel: 'Welcome Email',
    content: {
      subject: settings.welcomeEmailSubject,
      heading: settings.welcomeEmailHeading,
      body: settings.welcomeEmailBody,
      additionalContent: settings.welcomeEmailAdditionalContent || '',
      preheaderText: settings.welcomeEmailPreheaderText || '',
    },
    defaultContent: defaultWelcomeContent,
    onSave: (content: EmailContentSettings) => {
      onUpdateSettings({
        welcomeEmailSubject: content.subject,
        welcomeEmailHeading: content.heading,
        welcomeEmailBody: content.body,
        welcomeEmailAdditionalContent: content.additionalContent,
        welcomeEmailPreheaderText: content.preheaderText,
      })
    },
  }

  return (
    <>
      {/* Email Customizer Full-Screen Overlay */}
      {customizerOpen && (
        <EmailCustomizer
          onClose={() => setCustmizerOpen(false)}
          emailType={{
            id: emailConfig.emailTypeId,
            label: emailConfig.emailTypeLabel,
            defaultContent: emailConfig.defaultContent,
          }}
          initialContent={emailConfig.content}
          onSaveContent={emailConfig.onSave}
          placeholders={welcomePlaceholders}
          placeholderCategories={welcomeCategoryLabels}
          subjectPlaceholderHint="Available: {{site_name}}, {{user_name}}, {{user_email}}"
        />
      )}

      {/* Welcome Email Card */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            Email Templates
          </CardTitle>
          <CardDescription>
            Customize the emails sent by the Registration Form feature
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg border divide-y">
            {/* Welcome Email Row */}
            <div 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">
                  <Mail className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <div className="flex items-center gap-2">
                    <h4 className="font-medium text-sm">Welcome Email</h4>
                  </div>
                  <p className="text-sm text-muted-foreground">
                    Sent to new users after successful registration
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <Switch
                  checked={settings.sendWelcomeEmail}
                  onCheckedChange={(checked) => onUpdateSettings({ sendWelcomeEmail: checked })}
                />
                {isPro && (
                  <Button
                    size="sm"
                    className="gap-2 text-white"
                    style={{ backgroundColor: '#002269' }}
                    onClick={() => setCustmizerOpen(true)}
                    disabled={!settings.sendWelcomeEmail}
                  >
                    <Paintbrush className="h-4 w-4" />
                    Customize Email
                  </Button>
                )}
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </>
  )
}
