'use client'

import { useState, useEffect, useCallback } from 'react'
import {
  Plus,
  ArrowLeft,
  Edit,
  Trash2,
  Copy,
  Layers,
  Loader2,
  AlertTriangle,
  Calendar,
  Hash,
} from 'lucide-react'
import { toast } from 'sonner'
import { cmsApi } from '../../lib/api.js'
import { createSection, createContainer, createRow, createColumn } from '@actuate-media/cms-core'

export interface SavedSectionsProps {
  onNavigate: (path: string) => void
  config: any
}

interface SavedSection {
  id: string
  name: string
  description: string
  category: string
  tree: Record<string, unknown> | null
  usageCount: number
  createdAt: string
  updatedAt: string
}

type ViewState = { mode: 'list' } | { mode: 'create' } | { mode: 'edit'; section: SavedSection }

const CATEGORIES = ['header', 'footer', 'content', 'sidebar'] as const
type Category = (typeof CATEGORIES)[number]

const CATEGORY_COLORS: Record<string, string> = {
  header: 'bg-primary/10 text-primary',
  footer: 'bg-accent text-foreground',
  content: 'bg-muted text-muted-foreground',
  sidebar: 'bg-primary/10 text-primary',
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

function createEmptySectionTree(): Record<string, unknown> {
  const col = createColumn(100)
  const row = createRow([col])
  const container = createContainer()
  ;(container as unknown as { children: unknown[] }).children = [row]
  const section = createSection()
  ;(section as unknown as { children: unknown[] }).children = [container]
  return section as unknown as Record<string, unknown>
}

export function SavedSections({ onNavigate, config }: SavedSectionsProps) {
  const [sections, setSections] = useState<SavedSection[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [viewState, setViewState] = useState<ViewState>({ mode: 'list' })
  const [activeCategory, setActiveCategory] = useState<Category | 'all'>('all')
  const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null)
  const [saving, setSaving] = useState(false)

  const fetchSections = useCallback(async () => {
    setLoading(true)
    setError(null)
    const res = await cmsApi<SavedSection[]>('/saved-sections')
    if (res.error) {
      setError(res.error)
    } else {
      setSections(res.data ?? [])
    }
    setLoading(false)
  }, [])

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

  const filteredSections =
    activeCategory === 'all' ? sections : sections.filter((s) => s.category === activeCategory)

  async function handleDelete(id: string) {
    const res = await cmsApi(`/saved-sections/${id}`, { method: 'DELETE' })
    if (res.error) {
      toast.error(res.error)
    } else {
      toast.success('Section deleted')
      setSections((prev) => prev.filter((s) => s.id !== id))
    }
    setDeleteConfirmId(null)
  }

  async function handleDuplicate(section: SavedSection) {
    const res = await cmsApi<SavedSection>('/saved-sections', {
      method: 'POST',
      body: JSON.stringify({
        name: `${section.name} (Copy)`,
        description: section.description,
        category: section.category,
        tree: section.tree,
      }),
    })
    if (res.error) {
      toast.error(res.error)
    } else {
      toast.success('Section duplicated')
      fetchSections()
    }
  }

  if (viewState.mode === 'create' || viewState.mode === 'edit') {
    return (
      <SectionForm
        initial={viewState.mode === 'edit' ? viewState.section : undefined}
        saving={saving}
        onSave={async (data) => {
          setSaving(true)
          if (viewState.mode === 'create') {
            const res = await cmsApi<SavedSection>('/saved-sections', {
              method: 'POST',
              body: JSON.stringify({ ...data, tree: createEmptySectionTree() }),
            })
            setSaving(false)
            if (res.error) {
              toast.error(res.error)
            } else {
              toast.success('Section created')
              setViewState({ mode: 'list' })
              fetchSections()
            }
          } else {
            const res = await cmsApi<SavedSection>(`/saved-sections/${viewState.section.id}`, {
              method: 'PUT',
              body: JSON.stringify(data),
            })
            setSaving(false)
            if (res.error) {
              toast.error(res.error)
            } else {
              toast.success('Section updated')
              setViewState({ mode: 'list' })
              fetchSections()
            }
          }
        }}
        onCancel={() => setViewState({ mode: 'list' })}
      />
    )
  }

  return (
    <div className="p-4 pr-8">
      <div className="mb-6 flex items-center justify-between">
        <div>
          <h1 className="text-foreground text-2xl font-medium">Saved Sections</h1>
          <p className="text-muted-foreground mt-1 text-sm">
            Reusable sections for the page builder
          </p>
        </div>
        <button
          type="button"
          onClick={() => setViewState({ mode: 'create' })}
          className="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors"
        >
          <Plus size={16} />
          Create Section
        </button>
      </div>

      <div className="border-border mb-4 flex items-center gap-1 border-b">
        <CategoryTab
          label="All"
          active={activeCategory === 'all'}
          onClick={() => setActiveCategory('all')}
        />
        {CATEGORIES.map((cat) => (
          <CategoryTab
            key={cat}
            label={cat.charAt(0).toUpperCase() + cat.slice(1)}
            active={activeCategory === cat}
            onClick={() => setActiveCategory(cat)}
          />
        ))}
      </div>

      {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={fetchSections}
            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 && filteredSections.length === 0 && (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <Layers size={32} className="text-muted-foreground mb-3" />
          <p className="text-foreground mb-1 text-sm font-medium">No saved sections</p>
          <p className="text-muted-foreground mb-4 text-xs">
            {activeCategory === 'all'
              ? 'Create your first reusable section to get started.'
              : `No sections in the "${activeCategory}" category.`}
          </p>
          {activeCategory === 'all' && (
            <button
              type="button"
              onClick={() => setViewState({ mode: 'create' })}
              className="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-colors"
            >
              <Plus size={14} />
              Create Section
            </button>
          )}
        </div>
      )}

      {!loading && !error && filteredSections.length > 0 && (
        <div className="grid grid-cols-1 gap-3 lg:grid-cols-2">
          {filteredSections.map((section) => (
            <div
              key={section.id}
              className="border-border bg-card hover:border-primary/50 rounded-lg border p-4 transition-colors"
            >
              <div className="flex items-start justify-between gap-3">
                <div className="min-w-0 flex-1">
                  <p className="text-foreground truncate text-sm font-medium">{section.name}</p>
                  {section.description && (
                    <p className="text-muted-foreground mt-0.5 line-clamp-2 text-xs">
                      {section.description}
                    </p>
                  )}
                </div>
                <span
                  className={`shrink-0 rounded-full px-2 py-0.5 text-xs ${CATEGORY_COLORS[section.category] ?? 'bg-muted text-muted-foreground'}`}
                >
                  {section.category}
                </span>
              </div>

              <div className="text-muted-foreground mt-3 flex items-center gap-4 text-xs">
                <span className="flex items-center gap-1">
                  <Hash size={12} />
                  {section.usageCount} use{section.usageCount !== 1 ? 's' : ''}
                </span>
                <span className="flex items-center gap-1">
                  <Calendar size={12} />
                  {formatDate(section.createdAt)}
                </span>
                {section.tree && (
                  <span className="flex items-center gap-1">
                    <Layers size={12} />
                    {JSON.stringify(section.tree).length > 1000 ? 'Complex' : 'Simple'}
                  </span>
                )}
              </div>

              <div className="border-border mt-3 flex items-center gap-1 border-t pt-3">
                <button
                  type="button"
                  onClick={() => setViewState({ mode: 'edit', section })}
                  className="text-foreground hover:bg-accent flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors"
                  aria-label={`Edit ${section.name}`}
                >
                  <Edit size={13} />
                  Edit
                </button>
                <button
                  type="button"
                  onClick={() => handleDuplicate(section)}
                  className="text-foreground hover:bg-accent flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors"
                  aria-label={`Duplicate ${section.name}`}
                >
                  <Copy size={13} />
                  Duplicate
                </button>
                {deleteConfirmId === section.id ? (
                  <div className="ml-auto flex items-center gap-1">
                    <span className="text-destructive mr-1 text-xs">Delete?</span>
                    <button
                      type="button"
                      onClick={() => handleDelete(section.id)}
                      className="text-destructive-foreground bg-destructive hover:bg-destructive/90 rounded-md px-2 py-1 text-xs font-medium transition-colors"
                    >
                      Yes
                    </button>
                    <button
                      type="button"
                      onClick={() => setDeleteConfirmId(null)}
                      className="text-foreground border-border hover:bg-accent rounded-md border px-2 py-1 text-xs font-medium transition-colors"
                    >
                      No
                    </button>
                  </div>
                ) : (
                  <button
                    type="button"
                    onClick={() => setDeleteConfirmId(section.id)}
                    className="text-destructive hover:bg-destructive/10 ml-auto flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs font-medium transition-colors"
                    aria-label={`Delete ${section.name}`}
                  >
                    <Trash2 size={13} />
                    Delete
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

interface CategoryTabProps {
  label: string
  active: boolean
  onClick: () => void
}

function CategoryTab({ label, active, onClick }: CategoryTabProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`-mb-px border-b-2 px-3 py-2 text-sm transition-colors ${
        active
          ? 'border-primary text-foreground font-medium'
          : 'text-muted-foreground hover:text-foreground border-transparent'
      }`}
    >
      {label}
    </button>
  )
}

interface SectionFormProps {
  initial?: SavedSection
  saving: boolean
  onSave: (data: { name: string; description: string; category: string }) => void
  onCancel: () => void
}

function SectionForm({ initial, saving, onSave, onCancel }: SectionFormProps) {
  const [name, setName] = useState(initial?.name ?? '')
  const [description, setDescription] = useState(initial?.description ?? '')
  const [category, setCategory] = useState(initial?.category ?? 'content')

  function handleSubmit(e: React.FormEvent) {
    e.preventDefault()
    if (!name.trim()) return
    onSave({ name: name.trim(), description: description.trim(), category })
  }

  const treeSize = initial?.tree ? JSON.stringify(initial.tree).length : null

  return (
    <div className="p-4 pr-8">
      <div className="mb-6">
        <button
          type="button"
          onClick={onCancel}
          className="text-muted-foreground hover:text-foreground mb-3 flex items-center gap-1.5 text-sm transition-colors"
          aria-label="Back to saved sections"
        >
          <ArrowLeft size={16} />
          Back
        </button>
        <h1 className="text-foreground text-2xl font-medium">
          {initial ? `Edit: ${initial.name}` : 'Create Saved Section'}
        </h1>
      </div>

      <form onSubmit={handleSubmit} className="max-w-lg space-y-4">
        <div>
          <label htmlFor="section-name" className="text-foreground mb-1 block text-sm font-medium">
            Name <span className="text-destructive">*</span>
          </label>
          <input
            id="section-name"
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            required
            placeholder="e.g. Hero Banner"
            className="bg-background border-input focus:ring-ring w-full rounded-md border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
          />
        </div>

        <div>
          <label
            htmlFor="section-description"
            className="text-foreground mb-1 block text-sm font-medium"
          >
            Description
          </label>
          <textarea
            id="section-description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Optional description of this section..."
            rows={3}
            className="bg-background border-input focus:ring-ring w-full resize-none rounded-md border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
          />
        </div>

        <div>
          <label
            htmlFor="section-category"
            className="text-foreground mb-1 block text-sm font-medium"
          >
            Category
          </label>
          <select
            id="section-category"
            value={category}
            onChange={(e) => setCategory(e.target.value)}
            className="bg-background border-input focus:ring-ring w-full rounded-md border px-3 py-2 text-sm focus:ring-2 focus:outline-none"
          >
            {CATEGORIES.map((cat) => (
              <option key={cat} value={cat}>
                {cat.charAt(0).toUpperCase() + cat.slice(1)}
              </option>
            ))}
          </select>
        </div>

        {treeSize !== null && (
          <div className="border-border bg-muted rounded-md border p-3">
            <p className="text-muted-foreground text-xs">
              Section tree editing is available in the page builder. Current tree size:{' '}
              {(treeSize / 1024).toFixed(1)} KB
            </p>
          </div>
        )}

        <div className="flex items-center gap-3 pt-2">
          <button
            type="submit"
            disabled={saving || !name.trim()}
            className="bg-primary text-primary-foreground hover:bg-primary/90 flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50"
          >
            {saving && <Loader2 size={14} className="animate-spin" />}
            {initial ? 'Save Changes' : 'Create Section'}
          </button>
          <button
            type="button"
            onClick={onCancel}
            disabled={saving}
            className="text-foreground border-border hover:bg-accent rounded-lg border px-4 py-2 text-sm font-medium transition-colors disabled:opacity-50"
          >
            Cancel
          </button>
        </div>
      </form>
    </div>
  )
}
