import { useState } from 'react'
import { useAdminAuth, useAdminLogout, useCreateOrganizationWallets } from '@features/admin'
import type { Organization } from '@features/admin'
import { Notification } from '@shared/ui'
import { AdminLoginForm } from '@widgets/admin-login-form'
import { LegalEntitiesTable } from '@widgets/legal-entities-table'
import { AddLegalEntityModal } from '@widgets/add-legal-entity-modal'
import styles from './AdminPage.module.css'

type NotificationState = { message: string; status: 'success' | 'error' | 'warning' }

export function AdminPage() {
  const { isAuthenticated, isLoading } = useAdminAuth()
  const logout = useAdminLogout()
  const createWallets = useCreateOrganizationWallets()
  const [modalOpen, setModalOpen] = useState(false)
  const [notification, setNotification] = useState<NotificationState | null>(null)

  // After a legal entity is created we immediately provision its wallets.
  // The page stays mounted (unlike the modal), so these mutate callbacks fire reliably.
  function handleCreated(organization: Organization) {
    setNotification({ status: 'success', message: 'Юридическое лицо добавлено' })
    createWallets.mutate(organization.id, {
      onSuccess: (result) => {
        setNotification({
          status: 'success',
          message: `Кошельки созданы (${result.wallets.length})`,
        })
      },
      onError: () => {
        setNotification({
          status: 'warning',
          message: 'Юридическое лицо создано, но кошельки создать не удалось',
        })
      },
    })
  }

  if (isLoading) return null
  if (!isAuthenticated) return <AdminLoginForm />

  return (
    <div className={styles.page}>
      <header className={styles.header}>
        <h1 className={styles.greeting}>Привет, Марк!</h1>
        <button className={styles.logout} type="button" onClick={() => logout.mutate()}>
          Выйти
        </button>
      </header>

      <section className={styles.content}>
        <div className={styles.toolbar}>
          <h2 className={styles.sectionTitle}>Юридические лица</h2>
          <button className={styles.addBtn} type="button" onClick={() => setModalOpen(true)}>
            + Добавить юридическое лицо
          </button>
        </div>

        <LegalEntitiesTable />
      </section>

      <AddLegalEntityModal
        open={modalOpen}
        onClose={() => setModalOpen(false)}
        onCreated={handleCreated}
      />

      {notification && (
        <Notification
          status={notification.status}
          message={notification.message}
          onClose={() => setNotification(null)}
        />
      )}
    </div>
  )
}
