'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  X,
  Loader2,
  AlertTriangle,
  Layout,
  FileText,
  MapPin,
  Phone,
  BookOpen,
  File,
} from 'lucide-react'
import type { LucideIcon } from 'lucide-react'
import { cmsApi } from '../../lib/api.js'
import { createEmptyPage } from '@actuate-media/cms-core/page-builder'
import type { PageNode } from '@actuate-media/cms-core'

export interface TemplatePickerProps {
  onSelect: (templateTree: PageNode) => void
  onClose: () => void
}

interface PageTemplate {
  id: string
  name: string
  description: string
  category: string
  tree: PageNode
}

const categoryIcons: Record<string, LucideIcon> = {
  landing: Layout,
  blog: FileText,
  contact: MapPin,
  portfolio: BookOpen,
  mobile: Phone,
}

const categoryColors: Record<string, string> = {
  landing: 'bg-primary/10 text-primary',
  blog: 'bg-accent text-foreground',
  contact: 'bg-primary/10 text-primary',
  portfolio: 'bg-accent text-foreground',
  mobile: 'bg-primary/10 text-primary',
}

function resolveIcon(category: string): LucideIcon {
  return categoryIcons[category] ?? File
}

function resolveBadgeColor(category: string): string {
  return categoryColors[category] ?? 'bg-muted text-muted-foreground'
}

export function TemplatePicker({ onSelect, onClose }: TemplatePickerProps) {
  const [templates, setTemplates] = useState<PageTemplate[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const fetchTemplates = useCallback(async () => {
    setLoading(true)
    setError(null)
    const res = await cmsApi<PageTemplate[]>('/page-templates')
    if (res.error) {
      setError(res.error)
    } else {
      setTemplates(res.data ?? [])
    }
    setLoading(false)
  }, [])

  useEffect(() => {
    fetchTemplates()
  }, [fetchTemplates])

  useEffect(() => {
    function handleKeyDown(e: KeyboardEvent) {
      if (e.key === 'Escape') onClose()
    }
    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [onClose])

  function handleBlankPage() {
    onSelect(createEmptyPage())
    onClose()
  }

  function handleTemplateSelect(template: PageTemplate) {
    onSelect(template.tree)
    onClose()
  }

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center"
      role="dialog"
      aria-modal="true"
      aria-label="Choose a template"
    >
      <div
        className="motion-safe:animate-in motion-safe:fade-in-0 absolute inset-0 bg-black/50"
        onClick={onClose}
        aria-hidden="true"
      />

      <div className="bg-card border-border relative z-10 flex max-h-[80vh] w-full max-w-2xl flex-col overflow-hidden rounded-xl border shadow-2xl">
        <div className="flex items-center justify-between px-5 pt-5 pb-3">
          <h2 className="text-foreground text-lg font-medium">Choose a Template</h2>
          <button
            type="button"
            onClick={onClose}
            className="text-muted-foreground hover:text-foreground hover:bg-accent rounded-md p-1.5 transition-colors"
            aria-label="Close"
          >
            <X size={18} />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto px-5 pb-5">
          {loading && (
            <div className="flex items-center justify-center py-16">
              <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" />
            </div>
          )}

          {error && !loading && (
            <div className="flex flex-col items-center justify-center py-12 text-center">
              <AlertTriangle size={24} className="text-destructive mb-2" />
              <p className="text-muted-foreground mb-3 text-sm">{error}</p>
              <button
                type="button"
                onClick={fetchTemplates}
                className="text-foreground border-border hover:bg-accent rounded-md border px-3 py-1.5 text-sm font-medium transition-colors"
              >
                Retry
              </button>
            </div>
          )}

          {!loading && !error && (
            <div
              className="grid grid-cols-2 gap-3 md:grid-cols-3"
              role="list"
              aria-label="Available templates"
            >
              <button
                type="button"
                role="listitem"
                onClick={handleBlankPage}
                className="border-border hover:border-primary bg-card group focus:ring-ring flex cursor-pointer flex-col items-center gap-2 rounded-lg border p-4 text-left transition-colors focus:ring-2 focus:outline-none"
              >
                <div className="bg-muted text-muted-foreground group-hover:bg-primary/10 group-hover:text-primary flex h-10 w-10 items-center justify-center rounded-md transition-colors">
                  <File size={20} />
                </div>
                <p className="text-foreground text-center text-sm font-medium">Blank Page</p>
                <p className="text-muted-foreground text-center text-xs">Start from scratch</p>
              </button>

              {templates.map((template) => {
                const Icon = resolveIcon(template.category)
                const badgeColor = resolveBadgeColor(template.category)

                return (
                  <button
                    key={template.id}
                    type="button"
                    role="listitem"
                    onClick={() => handleTemplateSelect(template)}
                    className="border-border hover:border-primary bg-card group focus:ring-ring flex cursor-pointer flex-col items-center gap-2 rounded-lg border p-4 text-left transition-colors focus:ring-2 focus:outline-none"
                  >
                    <div className="bg-accent text-foreground group-hover:bg-primary/10 group-hover:text-primary flex h-10 w-10 items-center justify-center rounded-md transition-colors">
                      <Icon size={20} />
                    </div>
                    <p className="text-foreground w-full truncate text-center text-sm font-medium">
                      {template.name}
                    </p>
                    {template.description && (
                      <p className="text-muted-foreground line-clamp-2 text-center text-xs">
                        {template.description}
                      </p>
                    )}
                    <span className={`inline-block rounded-full px-2 py-0.5 text-xs ${badgeColor}`}>
                      {template.category}
                    </span>
                  </button>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
