import React, { useEffect, useState, useEffect as useLayoutEffect } from 'react'
import { observer } from 'mobx-react-lite'
import { t } from '$themelocalization'
import DraftSection from './DraftSection'
import Search from '../addresses/Search'
import DraftsModel from './model/DraftsModel'
import DraftsSkeleton from './DraftsSkeleton'
import './DraftsNG.scss'

const DraftsNG = ({ model }) => {
  const [searchInput, setSearchInput] = useState(model?.searchQuery || '')
  const maxDrafts = model?.maxDrafts ?? 3

  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' })
  }, [])

  useLayoutEffect(() => {
    setSearchInput(model?.searchQuery || '')
  }, [model?.searchQuery])

  const handleSearch = (value) => {
    const next = (value ?? '').trim()
    setSearchInput(value ?? '')
    model.setSearchQuery(next)
  }

  if (!model || !model.initiated) {
    return <DraftsSkeleton />
  }

  return (
    <div className="drafts-container">
      <div className="drafts-header">
        <h1 className="drafts-title">{t('Drafts.Title')}</h1>
        <Search
          value={searchInput}
          placeholder={t('Drafts.Search.Placeholder')}
          onChange={(value) => setSearchInput(value)}
          onSearch={handleSearch}
        />
      </div>

      <DraftSection
        model={model}
        section={DraftsModel.DRAFT_SECTIONS.SAVED}
        items={model.filteredSavedDrafts}
        filteredCount={model.filteredSavedCount}
        isExpanded={model.savedSectionExpanded}
        onToggle={() => model.toggleSection(DraftsModel.DRAFT_SECTIONS.SAVED)}
      />

      <DraftSection
        model={model}
        section={DraftsModel.DRAFT_SECTIONS.LATEST}
        items={model.filteredLatestDrafts}
        filteredCount={model.filteredLatestCount}
        isExpanded={model.latestSectionExpanded}
        onToggle={() => model.toggleSection(DraftsModel.DRAFT_SECTIONS.LATEST)}
        maxDrafts={maxDrafts}
      />
    </div>
  )
}

export default observer(DraftsNG)
