'use client'

import { useState } from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog'
import { Button } from '../ui/button'
import { Input } from '../ui/input'
import { Label } from '../ui/label'
import { Checkbox } from '../ui/checkbox'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '../ui/select'
import { Loader2, Send, AlertCircle } from 'lucide-react'
import { useToast } from '../toast'

interface TestSendRecipient {
  id: string
  name: string
  email?: string | null
}

interface TestSendPayload {
  testEmail: string
  selectedRecipientId: string | undefined
  includeTracking: boolean
}

interface TestSendDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  subject: string
  /** Sample recipients whose data can be used for merge field substitution */
  recipients?: TestSendRecipient[]
  /** Default sample option label shown when no specific recipient is chosen */
  defaultSampleLabel?: string
  /** Callback to send the test email. Receives the test send configuration. */
  onSendTest: (payload: TestSendPayload) => Promise<void>
  /** Merge field help text */
  mergeFieldHint?: string
}

export function TestSendDialog({
  open,
  onOpenChange,
  subject,
  recipients = [],
  defaultSampleLabel = 'Sample Data (John Smith)',
  onSendTest,
  mergeFieldHint = 'Merge fields like {{recipient.firstName}} will use this recipient\'s data',
}: TestSendDialogProps) {
  const { toast } = useToast()
  const [sending, setSending] = useState(false)
  const [testEmail, setTestEmail] = useState('')
  const [selectedRecipientId, setSelectedRecipientId] = useState<string>('sample')
  const [includeTracking, setIncludeTracking] = useState(false)

  const handleSendTest = async () => {
    if (!testEmail) {
      toast({ description: 'Please enter a test email address', variant: 'destructive' })
      return
    }

    setSending(true)
    try {
      await onSendTest({
        testEmail,
        selectedRecipientId: selectedRecipientId !== 'sample' ? selectedRecipientId : undefined,
        includeTracking,
      })

      toast({
        description: `Test email sent to ${testEmail}`,
      })
      onOpenChange(false)
    } catch (error) {
      console.error('Error sending test:', error)
      toast({
        description: error instanceof Error ? error.message : 'Failed to send test email',
        variant: 'destructive'
      })
    } finally {
      setSending(false)
    }
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Send Test Email</DialogTitle>
          <DialogDescription>
            Send a test version to yourself to preview how it will look in your inbox.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          {/* Subject preview */}
          <div className="p-3 bg-muted rounded-lg">
            <Label className="text-xs text-muted-foreground">Subject</Label>
            <p className="text-sm font-medium mt-1">[TEST] {subject || '(no subject)'}</p>
          </div>

          {/* Test email input */}
          <div className="space-y-2">
            <Label htmlFor="test-email">Send to</Label>
            <Input
              id="test-email"
              type="email"
              value={testEmail}
              onChange={(e) => setTestEmail(e.target.value)}
              placeholder="your-email@example.com"
            />
          </div>

          {/* Sample recipient data for merge fields */}
          <div className="space-y-2">
            <Label>Use data from</Label>
            <Select value={selectedRecipientId} onValueChange={setSelectedRecipientId}>
              <SelectTrigger>
                <SelectValue placeholder="Select recipient for merge fields" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="sample">{defaultSampleLabel}</SelectItem>
                {recipients.map(r => (
                  <SelectItem key={r.id} value={r.id}>
                    {r.name} {r.email ? `(${r.email})` : ''}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            <p className="text-xs text-muted-foreground">
              {mergeFieldHint}
            </p>
          </div>

          {/* Tracking option */}
          <div className="flex items-center space-x-2">
            <Checkbox
              id="include-tracking"
              checked={includeTracking}
              onCheckedChange={(checked) => setIncludeTracking(checked as boolean)}
            />
            <Label htmlFor="include-tracking" className="text-sm font-normal">
              Include tracking pixel and link tracking
            </Label>
          </div>

          {/* Warning */}
          <div className="flex items-start gap-2 p-3 bg-amber-50 border border-amber-200 rounded-lg text-amber-800">
            <AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
            <p className="text-sm">
              Test emails are marked with [TEST] in the subject and include a banner indicating it&apos;s a test.
            </p>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={sending}>
            Cancel
          </Button>
          <Button onClick={handleSendTest} disabled={sending || !testEmail}>
            {sending ? (
              <>
                <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                Sending...
              </>
            ) : (
              <>
                <Send className="mr-2 h-4 w-4" />
                Send Test
              </>
            )}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  )
}
