import { Copy, Trash, AddSquare, DocumentText } from 'iconsax-react'
import { useState } from 'react'
import { useEditorStore } from '../store/editorStore'
import type { Page } from '../store/editorStore.types'
import { clx } from '@/helpers/utils'
import CatalogPreview from '@/pages/catalogue/components/CatalogPreview'

function isPageEmptyForPreview(page: Page): boolean {
  if (page.objects.length > 0) return false
  if (page.backgroundType === 'image' && page.backgroundImageUrl.trim() !== '') {
    return false
  }
  if (page.backgroundType === 'video' && page.backgroundVideoUrl.trim() !== '') {
    return false
  }
  if (page.backgroundType === 'gradient') return false
  return true
}

type PagesPanelProps = {
  catalogSize?: string
}

const PagesPanel = ({ catalogSize }: PagesPanelProps) => {
  const {
    pages,
    currentPageId,
    setCurrentPage,
    addPage,
    duplicatePage,
    deletePage,
    reorderPages,
  } = useEditorStore()
  const [draggedPageId, setDraggedPageId] = useState<string | null>(null)
  const [dragOverPageId, setDragOverPageId] = useState<string | null>(null)

  const handleAddPage = () => {
    addPage()
  }

  const handleDuplicatePage = (pageId: string) => {
    duplicatePage(pageId)
  }

  const handleDeletePage = (pageId: string) => {
    if (pages.length > 1) {
      deletePage(pageId)
    }
  }

  return (
    <>
      <div className="flex-1 overflow-y-auto p-4">
        <div className="flex flex-col gap-3 items-center">
          {pages.length === 0 ? (
            <div className="text-sm text-gray-500 text-center py-8">
              صفحه‌ای وجود ندارد
            </div>
          ) : (
            pages.map((page) => {
              const isSelected = currentPageId === page.id
              const isEmpty = isPageEmptyForPreview(page)
              return (
                <div
                  key={page.id}
                  onClick={() => setCurrentPage(page.id)}
                  draggable
                  onDragStart={() => {
                    setDraggedPageId(page.id)
                  }}
                  onDragOver={(e) => {
                    e.preventDefault()
                    if (dragOverPageId !== page.id) {
                      setDragOverPageId(page.id)
                    }
                  }}
                  onDrop={(e) => {
                    e.preventDefault()
                    if (draggedPageId && draggedPageId !== page.id) {
                      reorderPages(draggedPageId, page.id)
                    }
                    setDraggedPageId(null)
                    setDragOverPageId(null)
                  }}
                  onDragEnd={() => {
                    setDraggedPageId(null)
                    setDragOverPageId(null)
                  }}
                  className={clx(
                    'flex flex-col gap-2 cursor-pointer transition-colors',
                    dragOverPageId === page.id &&
                      draggedPageId !== page.id &&
                      'ring-2 ring-blue-300 rounded-lg',
                    isSelected && ' rounded-lg p-0.5'
                  )}
                >
                  {isEmpty ? (
                    <div
                      className={clx(
                        'w-[72px] h-[94px] bg-[#EEF0F7] rounded-lg flex items-center justify-center',
                        isSelected && 'border border-black'
                      )}
                    >
                      <DocumentText size={20} color="#000" variant="Outline" />
                    </div>
                  ) : (
                    <CatalogPreview
                      page={page}
                      size={catalogSize}
                      selected={isSelected}
                    />
                  )}
                  <div className="text-xs font-medium text-center text-black">
                    {page.name}
                  </div>
                </div>
              )
            })
          )}
        </div>
      </div>

      <div className="p-4 border-t border-border rounded-b-[32px]">
        <div className="flex items-center justify-center gap-3">
          <button
            onClick={handleAddPage}
            className="size-7 flex items-center justify-center rounded-lg bg-white hover:bg-gray-100 transition-colors "
          >
            <AddSquare size={16} color="black" />
          </button>
          {currentPageId && (
            <>
              <button
                onClick={() => handleDuplicatePage(currentPageId)}
                className="size-7 flex items-center justify-center rounded-lg bg-white hover:bg-gray-100 transition-colors "
              >
                <Copy size={16} color="black" />
              </button>
              <button
                onClick={() => handleDeletePage(currentPageId)}
                disabled={pages.length <= 1}
                className="size-7 flex items-center hover:bg-gray-100 justify-center rounded-lg  transition-colors  disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <Trash size={16} color="#FF3B30" />
              </button>
            </>
          )}
        </div>
      </div>
    </>
  )
}

export default PagesPanel

