/**
 * Shipment Tracking Email Tab
 */

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Switch } from "@/components/ui/switch"
import { EmailCustomizer } from "@/components/email-customizer"
import type { EmailContentSettings, PlaceholderCategoryLabel, PlaceholderConfig } from "@/components/email-customizer/sections"
import { TrackingSettings } from "../../types"
import { Mail, PackageCheck, Paintbrush } from "lucide-react"

interface EmailTabProps {
  settings: TrackingSettings
  updateSetting: <K extends keyof TrackingSettings>(key: K, value: TrackingSettings[K]) => void
}

const trackingPlaceholders: PlaceholderConfig[] = [
  { tag: '{order_number}', description: 'Order number', example: '1024', category: 'order' },
  { tag: '{order_id}', description: 'Internal order ID', example: '1024', category: 'order' },
  { tag: '{customer_name}', description: "Customer's first name", example: 'John', category: 'customer' },
  { tag: '{customer_full_name}', description: "Customer's full name", example: 'John Smith', category: 'customer' },
  { tag: '{tracking_number}', description: 'Shipment tracking number', example: '1234567890123456', category: 'tracking' },
  { tag: '{carrier}', description: 'Shipping carrier name', example: 'FedEx', category: 'tracking' },
  { tag: '{date_shipped}', description: 'Shipment date', example: 'June 18, 2026', category: 'tracking' },
  { tag: '{estimated_delivery_date}', description: 'Estimated delivery date', example: 'June 21, 2026', category: 'tracking' },
  { tag: '{tracking_url}', description: 'Carrier tracking URL', example: 'https://example.com/track/123', category: 'tracking' },
  { 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' },
]

const trackingCategoryLabels: Record<string, PlaceholderCategoryLabel> = {
  order: { label: 'Order', color: 'bg-blue-100 text-blue-700' },
  customer: { label: 'Customer', color: 'bg-purple-100 text-purple-700' },
  tracking: { label: 'Tracking', color: 'bg-green-100 text-green-700' },
  site: { label: 'Site', color: 'bg-orange-100 text-orange-700' },
}

const defaultTrackingContent: EmailContentSettings = {
  subject: 'Your order has shipped!',
  heading: 'Your order is on its way',
  body: 'Good news! Your order #{order_number} has been shipped. You can track your package using the tracking information below.',
  additionalContent: '',
  preheaderText: '',
}

export function EmailTab({ settings, updateSetting }: EmailTabProps) {
  const [isCustomizerOpen, setIsCustomizerOpen] = useState(false)

  const trackingContent: EmailContentSettings = {
    subject: settings.email_subject || defaultTrackingContent.subject,
    heading: settings.email_heading || defaultTrackingContent.heading,
    body: settings.email_content || defaultTrackingContent.body,
    additionalContent: settings.email_additional_content || '',
    preheaderText: settings.email_preheader_text || '',
  }

  const handleSaveContent = (content: EmailContentSettings) => {
    updateSetting('email_subject', content.subject)
    updateSetting('email_heading', content.heading)
    if (content.body !== undefined) {
      updateSetting('email_content', content.body)
    }
    updateSetting('email_additional_content', content.additionalContent)
    updateSetting('email_preheader_text', content.preheaderText)
  }

  return (
    <>
      {isCustomizerOpen && (
        <EmailCustomizer
          onClose={() => setIsCustomizerOpen(false)}
          emailType={{
            id: 'shipment_tracking',
            label: 'Tracking Notification Email',
            defaultContent: defaultTrackingContent,
          }}
          initialContent={trackingContent}
          onSaveContent={handleSaveContent}
          placeholders={trackingPlaceholders}
          placeholderCategories={trackingCategoryLabels}
          subjectPlaceholderHint="Available: {order_number}, {customer_name}, {tracking_number}, {carrier}, {site_name}"
        />
      )}

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Mail className="h-5 w-5" />
            Email Templates
          </CardTitle>
          <CardDescription>
            Customize the tracking notification sent when shipment tracking is added to an order.
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="rounded-lg border divide-y">
            <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">
                  <PackageCheck className="h-5 w-5 text-primary" />
                </div>
                <div>
                  <h4 className="font-medium text-sm">Tracking Notification Email</h4>
                  <p className="text-sm text-muted-foreground">
                    Sent to customers when tracking details are added or when a tracked order is completed.
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-3">
                <Switch
                  checked={settings.send_tracking_email}
                  onCheckedChange={(checked) => updateSetting('send_tracking_email', checked)}
                />
                <Button
                  size="sm"
                  className="gap-2 text-white"
                  style={{ backgroundColor: '#00226b' }}
                  onClick={() => setIsCustomizerOpen(true)}
                  disabled={!settings.send_tracking_email}
                >
                  <Paintbrush className="h-4 w-4" />
                  Customize Email
                </Button>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>
    </>
  )
}
