import { useState } from "react"
import { Mail, Paintbrush } from "lucide-react"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import { Button } from "@/components/ui/button"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { EmailCustomizer } from "@/components/email-customizer"
import type { EmailContentSettings, PlaceholderCategoryLabel, PlaceholderConfig, ProductCardConfig } from "@/components/email-customizer/sections"
import { AbandonedCartSettings, EmailSequenceItem } from "../../types"

interface BasicEmailTabProps {
  settings: AbandonedCartSettings
  updateSettings: (updates: Partial<AbandonedCartSettings>) => void
  updateEmail: (index: number, updates: Partial<EmailSequenceItem>) => void
}

const placeholders: PlaceholderConfig[] = [
  { tag: "{customer_name}", description: "Customer first name or “there” for guests", example: "John", category: "customer" },
  { tag: "{customer_email}", description: "Customer email address", example: "john@example.com", category: "customer" },
  { tag: "{cart_total}", description: "Cart total with currency", example: "$149.99", category: "cart" },
  { tag: "{recovery_link}", description: "Unique cart recovery URL", example: "https://store.com/?recover=abc123", category: "cart" },
  { tag: "{unsubscribe_link}", description: "Recovery-email opt-out URL", example: "https://store.com/?unsubscribe=abc123", category: "site" },
  { tag: "{site_name}", description: "Website name", example: "My Store", category: "site" },
  { tag: "{site_url}", description: "Website URL", example: "https://store.com", category: "site" },
]

const categoryLabels: Record<string, PlaceholderCategoryLabel> = {
  customer: { label: "Customer", color: "bg-green-100 text-green-700" },
  cart: { label: "Cart", color: "bg-blue-100 text-blue-700" },
  site: { label: "Site", color: "bg-orange-100 text-orange-700" },
}

const sampleProduct = {
  name: "Premium Wireless Headphones",
  price: "$79.99",
  imageUrl: "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200' viewBox='0 0 200 200'%3E%3Crect fill='%23f3f4f6' width='200' height='200'/%3E%3Cpath d='M70 130l30-50 30 50' fill='none' stroke='%23d1d5db' stroke-width='4'/%3E%3C/svg%3E",
  productUrl: "#",
}

export function BasicEmailTab({ settings, updateSettings, updateEmail }: BasicEmailTabProps) {
  const [showCustomizer, setShowCustomizer] = useState(false)
  const email = settings.emails[0]

  const content: EmailContentSettings = {
    subject: email?.subject || "You left something in your cart!",
    heading: settings.emailHeading || "Your cart is waiting!",
    body: settings.emailBodyText || "Hi {customer_name},\n\nIt looks like you left some items in your cart at {site_name}. Your cart is saved and ready for you.",
    additionalContent: "",
    preheaderText: "",
  }

  const productCard: ProductCardConfig = {
    showImage: settings.emailShowImage ?? true,
    showTitle: settings.emailShowTitle ?? true,
    showPrice: settings.emailShowPrice ?? true,
    buttonText: settings.emailButtonText || "Complete Your Order",
    sample: sampleProduct,
  }

  if (!email) return null

  return (
    <>
      {showCustomizer && (
        <EmailCustomizer
          onClose={() => setShowCustomizer(false)}
          emailType={{
            id: "abandoned_cart_reminder",
            label: "Cart Recovery Email",
            defaultContent: content,
          }}
          initialContent={content}
          onSaveContent={(nextContent) => {
            updateSettings({ emailHeading: nextContent.heading, emailBodyText: nextContent.body })
            updateEmail(0, { subject: nextContent.subject })
          }}
          productCard={productCard}
          onSaveProductCard={(card) => updateSettings({
            emailShowImage: card.showImage,
            emailShowTitle: card.showTitle,
            emailShowPrice: card.showPrice,
            emailButtonText: card.buttonText,
          })}
          placeholders={placeholders}
          placeholderCategories={categoryLabels}
          subjectPlaceholderHint="Available: {customer_name}, {site_name}, {cart_total}"
        />
      )}

      <div className="space-y-6">
        <Card>
          <CardHeader>
            <CardTitle>Recovery Email</CardTitle>
            <CardDescription>Configure the reminder sent after a cart becomes abandoned.</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="flex items-center justify-between gap-6">
              <Label htmlFor="recoveryEmailEnabled">Send Recovery Email</Label>
              <Switch
                id="recoveryEmailEnabled"
                checked={email.enabled}
                onCheckedChange={(checked) => updateEmail(0, { enabled: checked })}
              />
            </div>

            {email.enabled && (
              <div className="grid gap-4 md:grid-cols-[1fr_100px_130px]">
                <div className="grid gap-2">
                  <Label htmlFor="recoveryEmailSubject">Subject Line</Label>
                  <Input
                    id="recoveryEmailSubject"
                    value={email.subject}
                    onChange={(event) => updateEmail(0, { subject: event.target.value })}
                  />
                </div>
                <div className="grid gap-2">
                  <Label htmlFor="recoveryEmailDelay">Delay</Label>
                  <Input
                    id="recoveryEmailDelay"
                    type="number"
                    min={1}
                    value={email.delay}
                    onChange={(event) => updateEmail(0, { delay: parseInt(event.target.value) || 1 })}
                  />
                </div>
                <div className="grid gap-2">
                  <Label>Unit</Label>
                  <Select
                    value={email.delayUnit}
                    onValueChange={(value) => updateEmail(0, { delayUnit: value as EmailSequenceItem["delayUnit"] })}
                  >
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>
                      <SelectItem value="minutes">Minutes</SelectItem>
                      <SelectItem value="hours">Hours</SelectItem>
                      <SelectItem value="days">Days</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>Email Template</CardTitle>
            <CardDescription>Customize the message and product-card presentation.</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex items-center justify-between rounded-lg border 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>
                  <p className="text-sm font-medium">Cart Recovery Email</p>
                  <p className="text-sm text-muted-foreground">Content, product details, and call-to-action</p>
                </div>
              </div>
              <Button onClick={() => setShowCustomizer(true)} size="sm" className="gap-2">
                <Paintbrush className="h-4 w-4" />
                Customize Email
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    </>
  )
}
