'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-purple-100 text-purple-700',
  body_open: 'bg-blue-100 text-blue-700',
  body_close: 'bg-green-100 text-green-700',
}

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="h-6 w-6 animate-spin text-blue-600" />
      </div>
    )
  }

  return (
    <div className="p-3 pr-6 sm:p-4 sm:pr-8">
      {error && (
        <div className="mb-4 flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-3">
          <AlertTriangle className="h-5 w-5 shrink-0 text-red-600" />
          <span className="flex-1 text-sm text-red-800">{error}</span>
          <button
            onClick={refetch}
            className="rounded-lg border border-red-300 px-3 py-1 text-sm text-red-700 transition-colors hover:bg-red-100"
          >
            Retry
          </button>
        </div>
      )}

      <div className="mb-4 flex items-center justify-between">
        <div>
          <h1 className="mb-1 text-2xl font-semibold text-gray-900">Script Tags</h1>
          <p className="text-sm text-gray-600">
            Manage tracking codes, analytics, and custom scripts injected into your site
          </p>
        </div>
        <button
          type="button"
          onClick={() => onNavigate?.('/script-tags/new')}
          className="flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700"
        >
          <Plus className="h-4 w-4" />
          New Tag
        </button>
      </div>

      {tags.length === 0 && !error ? (
        <div className="rounded-lg border border-gray-200 bg-white p-12 text-center">
          <Code2 className="mx-auto mb-3 h-10 w-10 text-gray-300" />
          <h3 className="text-sm font-semibold text-gray-900">No script tags yet</h3>
          <p className="mt-1 text-sm text-gray-500">
            Add tracking codes like Google Analytics, Tag Manager, or Facebook Pixel.
          </p>
          <button
            type="button"
            onClick={() => onNavigate?.('/script-tags/new')}
            className="mt-4 inline-flex items-center gap-2 rounded-lg bg-blue-600 px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-blue-700"
          >
            <Plus className="h-4 w-4" />
            Add Your First Tag
          </button>
        </div>
      ) : (
        <div className="overflow-hidden rounded-lg border border-gray-200 bg-white">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-200 bg-gray-50">
                <th className="px-4 py-3 text-left font-medium text-gray-600">Name</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">Placement</th>
                <th className="px-4 py-3 text-left font-medium text-gray-600">Scope</th>
                <th className="px-4 py-3 text-center font-medium text-gray-600">Priority</th>
                <th className="px-4 py-3 text-center font-medium text-gray-600">Enabled</th>
              </tr>
            </thead>
            <tbody>
              {tags.map((tag) => (
                <tr
                  key={tag.id}
                  className="border-b border-gray-100 transition-colors last:border-0 hover:bg-gray-50"
                >
                  <td className="px-4 py-3">
                    <button
                      type="button"
                      onClick={() => onNavigate?.(`/script-tags/${tag.id}`)}
                      className="font-medium text-blue-600 hover:text-blue-800 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-gray-100 text-gray-700'}`}
                    >
                      {PLACEMENT_LABELS[tag.placement] ?? tag.placement}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-gray-600">{scopeLabel(tag)}</td>
                  <td className="px-4 py-3 text-center font-mono text-gray-600">{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-blue-600' : 'bg-gray-300'}`}
                      aria-pressed={tag.enabled}
                    >
                      <span
                        className={`absolute top-0.5 block h-5 w-5 rounded-full bg-white transition-transform ${
                          tag.enabled ? 'translate-x-[22px]' : 'translate-x-0.5'
                        }`}
                      />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  )
}
