'use client'

import {
  Search,
  Plus,
  Trash2,
  ChevronLeft,
  ChevronRight,
  Loader2,
  FileText,
  MoreHorizontal,
} from 'lucide-react'
import { useState, useMemo, useCallback, useEffect, useRef } from 'react'
import { toast } from 'sonner'
import { cmsApi } from '../lib/api.js'
import { useApiData } from '../lib/useApiData.js'

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

type SortField = 'title' | 'status' | 'updatedAt'
type SortOrder = 'asc' | 'desc'

function resolveLabel(config: any, slug: string): { singular: string; plural: string } {
  const fallback = { singular: slug, plural: slug }
  if (!config?.collections) return fallback
  const list = Array.isArray(config.collections)
    ? config.collections
    : Object.values(config.collections)
  const match = (list as any[]).find((c: any) => c.slug === slug)
  return match?.labels ?? fallback
}

function statusColor(status: string): string {
  switch (status?.toUpperCase()) {
    case 'PUBLISHED':
      return 'var(--actuate-success-bg, #dcfce7)'
    case 'DRAFT':
      return 'var(--actuate-muted-bg, #f3f4f6)'
    case 'ARCHIVED':
      return 'var(--actuate-warning-bg, #fef9c3)'
    case 'SCHEDULED':
      return 'var(--actuate-info-bg, #dbeafe)'
    default:
      return 'var(--actuate-muted-bg, #f3f4f6)'
  }
}

function statusText(status: string): string {
  switch (status?.toUpperCase()) {
    case 'PUBLISHED':
      return 'var(--actuate-success-text, #166534)'
    case 'DRAFT':
      return 'var(--actuate-muted-text, #374151)'
    case 'ARCHIVED':
      return 'var(--actuate-warning-text, #854d0e)'
    case 'SCHEDULED':
      return 'var(--actuate-info-text, #1e40af)'
    default:
      return 'var(--actuate-muted-text, #374151)'
  }
}

function formatDate(d: string | undefined): string {
  if (!d) return '—'
  return new Date(d).toLocaleDateString(undefined, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
}

export function CollectionList({ collectionSlug, config, onNavigate }: CollectionListProps) {
  const labels = useMemo(() => resolveLabel(config, collectionSlug), [config, collectionSlug])

  const [page, setPage] = useState(1)
  const [search, setSearch] = useState('')
  const [debouncedSearch, setDebouncedSearch] = useState('')
  const [sort, setSort] = useState<SortField | null>(null)
  const [order, setOrder] = useState<SortOrder>('asc')
  const [selected, setSelected] = useState<Set<string>>(new Set())
  const searchTimer = useRef<ReturnType<typeof setTimeout>>(undefined)

  useEffect(() => {
    clearTimeout(searchTimer.current)
    searchTimer.current = setTimeout(() => {
      setDebouncedSearch(search)
      setPage(1)
    }, 300)
    return () => clearTimeout(searchTimer.current)
  }, [search])

  const endpoint = useMemo(() => {
    let url = `/collections/${collectionSlug}?page=${page}&pageSize=25`
    if (debouncedSearch) url += `&search=${encodeURIComponent(debouncedSearch)}`
    if (sort) url += `&sort=${sort}&order=${order}`
    return url
  }, [collectionSlug, page, debouncedSearch, sort, order])

  const { data, loading, error, refetch } = useApiData<{ docs: any[]; total: number }>(endpoint)
  const docs = data?.docs ?? []
  const total = data?.total ?? 0
  const totalPages = Math.max(1, Math.ceil(total / 25))

  useEffect(() => {
    setPage(1)
    setSelected(new Set())
    setSearch('')
  }, [collectionSlug])

  const toggleSort = useCallback((field: SortField) => {
    setSort((prev) => {
      if (prev === field) {
        setOrder((o) => (o === 'asc' ? 'desc' : 'asc'))
        return field
      }
      setOrder('asc')
      return field
    })
  }, [])

  const toggleSelect = (id: string) =>
    setSelected((prev) => {
      const s = new Set(prev)
      s.has(id) ? s.delete(id) : s.add(id)
      return s
    })

  const toggleAll = (checked: boolean) =>
    setSelected(checked ? new Set(docs.map((d: any) => String(d.id))) : new Set())

  const bulkAction = async (action: 'delete' | 'publish' | 'unpublish') => {
    const ids = [...selected]
    for (const id of ids) {
      if (action === 'delete') {
        await cmsApi(`/collections/${collectionSlug}/${id}`, { method: 'DELETE' })
      } else {
        await cmsApi(`/collections/${collectionSlug}/${id}`, {
          method: 'PUT',
          body: JSON.stringify({ status: action === 'publish' ? 'PUBLISHED' : 'DRAFT' }),
        })
      }
    }
    const verb =
      action === 'delete' ? 'deleted' : action === 'publish' ? 'published' : 'unpublished'
    toast.success(`${ids.length} ${ids.length === 1 ? labels.singular : labels.plural} ${verb}`)
    setSelected(new Set())
    refetch()
  }

  const SortCol = ({ field, children }: { field: SortField; children: string }) => (
    <button
      type="button"
      onClick={() => toggleSort(field)}
      className="flex items-center gap-1 text-xs font-medium transition-opacity hover:opacity-80"
      style={{ color: 'var(--actuate-text-secondary, #6b7280)' }}
    >
      {children}
      {sort === field && <span>{order === 'asc' ? '↑' : '↓'}</span>}
    </button>
  )

  if (loading && docs.length === 0) {
    return (
      <div className="flex h-64 items-center justify-center p-4">
        <Loader2
          className="h-6 w-6 animate-spin"
          style={{ color: 'var(--actuate-primary, #2563eb)' }}
        />
      </div>
    )
  }

  return (
    <div className="flex h-full flex-col p-3 pr-6 sm:p-4 sm:pr-8">
      {/* Header */}
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <h1
            className="text-xl font-semibold sm:text-2xl"
            style={{ color: 'var(--actuate-text, #111827)' }}
          >
            {labels.plural}
          </h1>
          <p className="text-sm" style={{ color: 'var(--actuate-text-secondary, #6b7280)' }}>
            {total} total
          </p>
        </div>
        <button
          onClick={() => onNavigate(`/${collectionSlug}/new`)}
          className="flex items-center gap-2 rounded-lg px-4 py-2 text-sm font-medium text-white transition-colors"
          style={{ background: 'var(--actuate-primary, #2563eb)' }}
        >
          <Plus className="h-4 w-4" /> New {labels.singular}
        </button>
      </div>

      {/* Search */}
      <div className="relative mb-4">
        <Search
          className="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2"
          style={{ color: 'var(--actuate-text-muted, #9ca3af)' }}
        />
        <input
          type="text"
          placeholder={`Search ${labels.plural.toLowerCase()}...`}
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="w-full rounded-lg border py-2 pr-3 pl-9 text-sm focus:ring-2 focus:outline-none"
          style={{
            borderColor: 'var(--actuate-border, #d1d5db)',
            color: 'var(--actuate-text, #111827)',
          }}
        />
      </div>

      {/* Bulk actions */}
      {selected.size > 0 && (
        <div
          className="mb-4 flex flex-wrap items-center justify-between gap-2 rounded-lg p-3"
          style={{
            background: 'var(--actuate-info-bg, #eff6ff)',
            borderColor: 'var(--actuate-info-border, #bfdbfe)',
            borderWidth: 1,
            borderStyle: 'solid',
          }}
        >
          <span className="text-sm" style={{ color: 'var(--actuate-info-text, #1e40af)' }}>
            {selected.size} selected
          </span>
          <div className="flex gap-2">
            <button
              onClick={() => bulkAction('publish')}
              className="rounded-lg px-3 py-1.5 text-sm text-white"
              style={{ background: 'var(--actuate-success, #16a34a)' }}
            >
              Publish
            </button>
            <button
              onClick={() => bulkAction('unpublish')}
              className="rounded-lg px-3 py-1.5 text-sm text-white"
              style={{ background: 'var(--actuate-warning, #ca8a04)' }}
            >
              Unpublish
            </button>
            <button
              onClick={() => bulkAction('delete')}
              className="rounded-lg px-3 py-1.5 text-sm text-white"
              style={{ background: 'var(--actuate-danger, #dc2626)' }}
            >
              <Trash2 className="-mt-0.5 mr-1 inline h-3.5 w-3.5" />
              Delete
            </button>
          </div>
        </div>
      )}

      {error && (
        <div
          className="mb-4 rounded-lg p-3 text-sm"
          style={{
            background: 'var(--actuate-danger-bg, #fef2f2)',
            color: 'var(--actuate-danger-text, #991b1b)',
          }}
        >
          {error} —{' '}
          <button onClick={refetch} className="underline">
            retry
          </button>
        </div>
      )}

      {/* Table */}
      {docs.length === 0 && !loading ? (
        <div
          className="flex flex-1 flex-col items-center justify-center rounded-lg border p-8"
          style={{
            borderColor: 'var(--actuate-border, #d1d5db)',
            color: 'var(--actuate-text-secondary, #6b7280)',
          }}
        >
          <FileText className="mb-3 h-10 w-10 opacity-40" />
          <p className="mb-3 text-sm">No {labels.plural.toLowerCase()} found</p>
          <button
            onClick={() => onNavigate(`/${collectionSlug}/new`)}
            className="rounded-lg px-4 py-2 text-sm text-white"
            style={{ background: 'var(--actuate-primary, #2563eb)' }}
          >
            Create {labels.singular}
          </button>
        </div>
      ) : (
        <div
          className="flex-1 overflow-auto rounded-lg border"
          style={{ borderColor: 'var(--actuate-border, #d1d5db)' }}
        >
          <table className="w-full text-sm">
            <thead
              className="sticky top-0"
              style={{
                background: 'var(--actuate-surface-alt, #f9fafb)',
                borderBottom: '1px solid var(--actuate-border, #d1d5db)',
              }}
            >
              <tr>
                <th className="w-10 px-3 py-2 text-left">
                  <input
                    type="checkbox"
                    checked={selected.size === docs.length && docs.length > 0}
                    onChange={(e) => toggleAll(e.target.checked)}
                    className="rounded"
                  />
                </th>
                <th className="px-3 py-2 text-left">
                  <SortCol field="title">Title</SortCol>
                </th>
                <th className="px-3 py-2 text-left">
                  <SortCol field="status">Status</SortCol>
                </th>
                <th className="px-3 py-2 text-left">
                  <SortCol field="updatedAt">Updated</SortCol>
                </th>
                <th
                  className="px-3 py-2 text-left text-xs font-medium"
                  style={{ color: 'var(--actuate-text-secondary, #6b7280)' }}
                >
                  Actions
                </th>
              </tr>
            </thead>
            <tbody>
              {docs.map((doc: any) => (
                <tr
                  key={doc.id}
                  className="transition-colors hover:opacity-95"
                  style={{ borderBottom: '1px solid var(--actuate-border, #e5e7eb)' }}
                >
                  <td className="px-3 py-2">
                    <input
                      type="checkbox"
                      checked={selected.has(String(doc.id))}
                      onChange={() => toggleSelect(String(doc.id))}
                      className="rounded"
                    />
                  </td>
                  <td className="px-3 py-2">
                    <button
                      type="button"
                      onClick={() => onNavigate(`/${collectionSlug}/${doc.id}`)}
                      className="text-left font-medium hover:underline"
                      style={{ color: 'var(--actuate-text, #111827)' }}
                    >
                      {doc.title || doc.name || `#${doc.id}`}
                    </button>
                  </td>
                  <td className="px-3 py-2">
                    <span
                      className="inline-block rounded-full px-2 py-0.5 text-xs font-medium"
                      style={{ background: statusColor(doc.status), color: statusText(doc.status) }}
                    >
                      {doc.status ?? 'DRAFT'}
                    </span>
                  </td>
                  <td
                    className="px-3 py-2"
                    style={{ color: 'var(--actuate-text-secondary, #6b7280)' }}
                  >
                    {formatDate(doc.updatedAt)}
                  </td>
                  <td className="px-3 py-2">
                    <button
                      type="button"
                      onClick={() => onNavigate(`/${collectionSlug}/${doc.id}`)}
                      className="rounded p-1.5 transition-opacity hover:opacity-75"
                      title="Edit"
                    >
                      <MoreHorizontal
                        className="h-4 w-4"
                        style={{ color: 'var(--actuate-text-secondary, #6b7280)' }}
                      />
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* Pagination */}
      {totalPages > 1 && (
        <div
          className="mt-4 flex items-center justify-between text-sm"
          style={{ color: 'var(--actuate-text-secondary, #6b7280)' }}
        >
          <span>
            Page {page} of {totalPages}
          </span>
          <div className="flex gap-2">
            <button
              disabled={page <= 1}
              onClick={() => setPage((p) => p - 1)}
              className="flex items-center gap-1 rounded-lg border px-3 py-1.5 transition-opacity disabled:opacity-40"
              style={{ borderColor: 'var(--actuate-border, #d1d5db)' }}
            >
              <ChevronLeft className="h-4 w-4" /> Previous
            </button>
            <button
              disabled={page >= totalPages}
              onClick={() => setPage((p) => p + 1)}
              className="flex items-center gap-1 rounded-lg border px-3 py-1.5 transition-opacity disabled:opacity-40"
              style={{ borderColor: 'var(--actuate-border, #d1d5db)' }}
            >
              Next <ChevronRight className="h-4 w-4" />
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
