'use client'

import { useState } from 'react'
import { Code2, Plus, Loader2, AlertTriangle } from 'lucide-react'
import { toast } from 'sonner'
import { useApiData } from '../lib/useApiData.js'
import { cmsApi } from '../lib/api.js'

interface ScriptTag {
  id: string
  name: string
  code: string
  placement: string
  scope: string
  targetPaths: string[]
  priority: number
  enabled: boolean
  createdAt: string
  updatedAt: string
}

export interface ScriptTagsProps {
  onNavigate?: (path: string) => void
}

const PLACEMENT_LABELS: Record<string, string> = {
  head: 'Head',
  body_open: 'Body Open',
  body_close: 'Body Close',
}

const PLACEMENT_COLORS: Record<string, string> = {
  head: 'bg-accent text-accent-foreground',
  body_open: 'bg-primary/15 text-primary',
  body_close: 'bg-success/15 text-success',
}

function scopeLabel(tag: ScriptTag): string {
  const scope = String(tag.scope ?? '')
  const targetPaths = Array.isArray(tag.targetPaths) ? tag.targetPaths : []
  if (scope === 'site') return 'Entire Site'
  if (scope === 'parents') {
    const count = targetPaths.length
    return `${count} parent path${count !== 1 ? 's' : ''} + children`
  }
  if (scope === 'urls') {
    const count = targetPaths.length
    return `${count} URL${count !== 1 ? 's' : ''}`
  }
  return scope || 'Custom'
}

export function ScriptTags({ onNavigate }: ScriptTagsProps) {
  const { data, loading, error, refetch } = useApiData<ScriptTag[]>('/script-tags')
  const [togglingId, setTogglingId] = useState<string | null>(null)

  const tags = data ?? []

  const toggleEnabled = async (tag: ScriptTag) => {
    setTogglingId(tag.id)
    const res = await cmsApi(`/script-tags/${tag.id}`, {
      method: 'PUT',
      body: JSON.stringify({ enabled: !tag.enabled }),
    })
    setTogglingId(null)
    if (res.error) {
      toast.error(res.error)
    } else {
      refetch()
    }
  }

  if (loading) {
    return (
      <div className="flex h-64 items-center justify-center p-3 pr-6 sm:p-4 sm:pr-8">
        <Loader2 className="text-primary h-6 w-6 animate-spin" />
      </div>
    )
  }

  return (
    <div className="p-3 pr-6 sm:p-4 sm:pr-8">
      {error && (
        <div className="border-destructive/30 bg-destructive/10 mb-4 flex items-center gap-3 rounded-lg border p-3">
          <AlertTriangle className="text-destructive h-5 w-5 shrink-0" />
          <span className="text-destructive flex-1 text-sm">{error}</span>
          <button
            onClick={refetch}
            className="border-destructive/40 text-destructive hover:bg-destructive/15 rounded-lg border px-3 py-1 text-sm transition-colors"
          >
            Retry
          </button>
        </div>
      )}

      <div className="mb-4 flex items-center justify-between">
        <div>
          <h1 className="text-foreground mb-1 text-2xl font-medium">Script Tags</h1>
          <p className="text-muted-foreground text-sm">
            Manage tracking codes, analytics, and custom scripts injected into your site
          </p>
        </div>
        <button
          type="button"
          onClick={() => onNavigate?.('/script-tags/new')}
          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 className="h-4 w-4" />
          New Tag
        </button>
      </div>

      {tags.length === 0 && !error ? (
        <div className="border-border bg-card rounded-lg border p-12 text-center">
          <Code2 className="text-muted-foreground mx-auto mb-3 h-10 w-10" />
          <h3 className="text-foreground text-sm font-medium">No script tags yet</h3>
          <p className="text-muted-foreground mt-1 text-sm">
            Add tracking codes like Google Analytics, Tag Manager, or Facebook Pixel.
          </p>
          <button
            type="button"
            onClick={() => onNavigate?.('/script-tags/new')}
            className="bg-primary text-primary-foreground hover:bg-primary/90 mt-4 inline-flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium transition-colors"
          >
            <Plus className="h-4 w-4" />
            Add Your First Tag
          </button>
        </div>
      ) : (
        <div className="border-border bg-card overflow-hidden rounded-lg border">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-border bg-muted border-b">
                <th className="text-muted-foreground px-4 py-3 text-left font-medium">Name</th>
                <th className="text-muted-foreground px-4 py-3 text-left font-medium">Placement</th>
                <th className="text-muted-foreground px-4 py-3 text-left font-medium">Scope</th>
                <th className="text-muted-foreground px-4 py-3 text-center font-medium">
                  Priority
                </th>
                <th className="text-muted-foreground px-4 py-3 text-center font-medium">Enabled</th>
              </tr>
            </thead>
            <tbody>
              {tags.map((tag) => (
                <tr
                  key={tag.id}
                  className="border-border hover:bg-muted border-b transition-colors last:border-0"
                >
                  <td className="px-4 py-3">
                    <button
                      type="button"
                      onClick={() => onNavigate?.(`/script-tags/${tag.id}`)}
                      className="text-primary hover:text-primary/80 font-medium hover:underline"
                    >
                      {tag.name}
                    </button>
                  </td>
                  <td className="px-4 py-3">
                    <span
                      className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${PLACEMENT_COLORS[tag.placement] ?? 'bg-muted text-foreground'}`}
                    >
                      {PLACEMENT_LABELS[tag.placement] ?? tag.placement}
                    </span>
                  </td>
                  <td className="text-muted-foreground px-4 py-3">{scopeLabel(tag)}</td>
                  <td className="text-muted-foreground px-4 py-3 text-center font-mono">
                    {tag.priority}
                  </td>
                  <td className="px-4 py-3 text-center">
                    <button
                      type="button"
                      onClick={() => toggleEnabled(tag)}
                      disabled={togglingId === tag.id}
                      className={`relative h-6 w-11 shrink-0 rounded-full transition-colors ${tag.enabled ? 'bg-primary' : 'bg-switch-background'}`}
                      aria-pressed={tag.enabled}
                    >
                      <span
                        className={`bg-card absolute top-0.5 block h-5 w-5 rounded-full transition-transform ${
                          tag.enabled ? 'translate-x-[22px]' : 'translate-x-0.5'
                        }`}
                      />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
