'use client'

import { useState, useEffect, useMemo, useCallback } from 'react'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from '../ui/dialog'
import { Button } from '../ui/button'
import { Badge } from '../ui/badge'
import { ScrollArea } from '../ui/scroll-area'
import { Input } from '../ui/input'
import { FileText, Loader2, Search } from 'lucide-react'

export interface EmailTemplate {
  id: string
  name: string
  description: string | null
  subject: string
  blocks: string | null
  category: string | null
  isDefault: boolean
  useCount: number
  /** Alternative field name for subject */
  subjectTemplate?: string
  /** Alternative field name for body */
  bodyTemplate?: string
}

interface TemplatePickerProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  onSelectTemplate: (template: EmailTemplate) => void
  /** Fetch templates from the API. Should return an array of templates. */
  onLoadTemplates: () => Promise<EmailTemplate[]>
  /** Optional callback to seed/create default templates when none exist */
  onSeedTemplates?: () => Promise<void>
  /** Optional category filter -- when set, only templates matching this category are shown */
  categoryFilter?: string
}

// Normalize API response to ensure subject/blocks fields are populated
function normalizeTemplates(raw: EmailTemplate[]): EmailTemplate[] {
  return raw.map((t) => ({
    ...t,
    subject: t.subject || t.subjectTemplate || '',
    blocks: t.blocks || t.bodyTemplate || null,
  }))
}

export function TemplatePicker({
  open,
  onOpenChange,
  onSelectTemplate,
  onLoadTemplates,
  onSeedTemplates,
  categoryFilter,
}: TemplatePickerProps) {
  const [templates, setTemplates] = useState<EmailTemplate[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [search, setSearch] = useState('')

  const fetchTemplates = useCallback(async () => {
    try {
      setLoading(true)
      setError(null)

      const data = await onLoadTemplates()

      // If no templates and a seed function is provided, try seeding
      if ((!data || data.length === 0) && onSeedTemplates) {
        await onSeedTemplates()
        const retryData = await onLoadTemplates()
        setTemplates(normalizeTemplates(retryData || []))
        return
      }

      setTemplates(normalizeTemplates(data || []))
    } catch (err) {
      console.error('Error fetching templates:', err)
      setError('Failed to load templates')
    } finally {
      setLoading(false)
    }
  }, [onLoadTemplates, onSeedTemplates])

  useEffect(() => {
    if (open) {
      fetchTemplates()
      setSearch('')
    }
  }, [open, fetchTemplates])

  const filteredTemplates = useMemo(() => {
    let result = templates
    if (categoryFilter) {
      result = result.filter((t) => t.category === categoryFilter)
    }
    if (search.trim()) {
      const q = search.toLowerCase()
      result = result.filter(
        (t) =>
          t.name.toLowerCase().includes(q) ||
          (t.description && t.description.toLowerCase().includes(q)) ||
          t.subject.toLowerCase().includes(q)
      )
    }
    return result
  }, [templates, categoryFilter, search])

  const handleSelect = useCallback((template: EmailTemplate) => {
    onSelectTemplate(template)
    onOpenChange(false)
  }, [onSelectTemplate, onOpenChange])

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[600px]">
        <DialogHeader>
          <DialogTitle>Choose a Template</DialogTitle>
          <DialogDescription>
            Start with a pre-built template to save time
          </DialogDescription>
        </DialogHeader>

        {loading ? (
          <div className="flex items-center justify-center py-8" role="status" aria-label="Loading templates">
            <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" aria-hidden="true" />
            <span className="ml-2 text-muted-foreground">Loading templates...</span>
          </div>
        ) : error ? (
          <div className="text-center py-8">
            <p className="text-red-600">{error}</p>
            <Button onClick={fetchTemplates} variant="outline" className="mt-2">
              Retry
            </Button>
          </div>
        ) : templates.length === 0 ? (
          <div className="text-center py-8">
            <FileText className="h-12 w-12 mx-auto text-muted-foreground mb-2" />
            <p className="text-muted-foreground">No templates available</p>
            {onSeedTemplates && (
              <Button
                onClick={async () => {
                  await onSeedTemplates()
                  fetchTemplates()
                }}
                variant="outline"
                className="mt-2"
              >
                Create Default Templates
              </Button>
            )}
          </div>
        ) : (
          <>
            {/* Search */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
              <Input
                placeholder="Search templates..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
                className="pl-9"
              />
            </div>

            <ScrollArea className="h-[350px] pr-4" role="region" aria-label="Template list">
              <div className="space-y-3" role="listbox" aria-label="Available templates">
                {filteredTemplates.map((template) => (
                  <button
                    key={template.id}
                    onClick={() => handleSelect(template)}
                    className="w-full text-left p-4 rounded-lg border hover:border-primary hover:bg-accent/50 transition-colors"
                    role="option"
                    aria-label={`Select ${template.name} template`}
                  >
                    <div className="flex items-start justify-between">
                      <div className="flex items-center gap-2">
                        <FileText className="h-4 w-4 text-muted-foreground" />
                        <span className="font-medium">{template.name}</span>
                      </div>
                      <div className="flex items-center gap-2">
                        {template.isDefault && (
                          <Badge variant="secondary" className="text-xs">
                            Default
                          </Badge>
                        )}
                      </div>
                    </div>
                    {template.description && (
                      <p className="text-sm text-muted-foreground mt-1">
                        {template.description}
                      </p>
                    )}
                    <p className="text-sm text-muted-foreground mt-2 font-mono">
                      Subject: {template.subject}
                    </p>
                  </button>
                ))}
                {filteredTemplates.length === 0 && (
                  <p className="text-center py-6 text-muted-foreground">
                    No templates match your search
                  </p>
                )}
              </div>
            </ScrollArea>

            <div className="flex justify-between items-center pt-4 border-t">
              <p className="text-xs text-muted-foreground">
                {filteredTemplates.length} template{filteredTemplates.length !== 1 ? 's' : ''} available
              </p>
              <Button variant="ghost" onClick={() => onOpenChange(false)}>
                Cancel
              </Button>
            </div>
          </>
        )}
      </DialogContent>
    </Dialog>
  )
}
