import { useEffect, useState } from 'react'
import { Plus } from 'lucide-react'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { ConfirmDeleteModal } from '../components/ConfirmDeleteModal'
import { PickWebsiteCategoriesModal } from '../components/PickWebsiteCategoriesModal'
import { StoreSpecialModal } from '../components/StoreSpecialModal'
import { WebsiteGroupCarousel } from '../components/WebsiteGroupCarousel'
import { WebsiteGroupItemCard } from '../components/WebsiteGroupItemCard'
import { useToast } from '../context/ToastContext'
import { useT } from '../i18n/useT'
import { ApiError } from '../lib/api'
import {
  createWebsiteCategoryGroup,
  deleteWebsiteCategoryGroup,
  listWebsiteCategoryGroups,
  updateWebsiteCategoryGroup,
} from '../services/websiteCategoryGroupService'
import type { WebsiteCategoryGroup } from '../types/websiteCategoryGroup'
import pageStyles from '../components/PageContent.module.css'
import fabStyles from './StoreItemsPage.module.css'
import styles from './StoreSpecialsPage.module.css'

export function WebsiteSpecialCategoriesPage() {
  const t = useT()
  const { showToast } = useToast()
  const [groups, setGroups] = useState<WebsiteCategoryGroup[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState('')

  const [createOpen, setCreateOpen] = useState(false)
  const [editGroupTarget, setEditGroupTarget] = useState<WebsiteCategoryGroup | null>(null)
  const [deleteGroupTarget, setDeleteGroupTarget] = useState<WebsiteCategoryGroup | null>(null)
  const [pickItemsTarget, setPickItemsTarget] = useState<WebsiteCategoryGroup | null>(null)
  const [removeTarget, setRemoveTarget] = useState<{
    group: WebsiteCategoryGroup
    categoryId: string
    categoryName: string
  } | null>(null)

  useEffect(() => {
    const controller = new AbortController()
    void loadGroups(controller.signal)
    return () => controller.abort()
  }, [])

  async function loadGroups(signal?: AbortSignal) {
    setIsLoading(true)
    setError('')

    try {
      const data = await listWebsiteCategoryGroups(1, 50, signal)
      setGroups(data.items)
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') return
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.specialCategories.errorLoad'))
      }
    } finally {
      setIsLoading(false)
    }
  }

  function replaceGroup(updated: WebsiteCategoryGroup) {
    setGroups((prev) => prev.map((entry) => (entry.id === updated.id ? updated : entry)))
  }

  async function handleCreateGroup(values: { key: string; title: string }) {
    setIsSaving(true)
    setError('')

    try {
      const result = await createWebsiteCategoryGroup({
        key: values.key,
        title: values.title,
        sortOrder: groups.length,
      })
      setGroups((prev) => [...prev, result.group])
      setCreateOpen(false)
      showToast(t('website.specialCategories.toastCreated'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.specialCategories.errorCreate'))
      }
    } finally {
      setIsSaving(false)
    }
  }

  async function handleEditGroup(values: { key: string; title: string }) {
    if (!editGroupTarget) return

    setIsSaving(true)
    setError('')

    try {
      const result = await updateWebsiteCategoryGroup(editGroupTarget.id, {
        key: values.key,
        title: values.title,
      })
      replaceGroup(result.group)
      setEditGroupTarget(null)
      showToast(t('website.specialCategories.toastUpdated'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.specialCategories.errorUpdate'))
      }
    } finally {
      setIsSaving(false)
    }
  }

  async function confirmDeleteGroup() {
    if (!deleteGroupTarget) return

    setIsSaving(true)
    setError('')

    try {
      await deleteWebsiteCategoryGroup(deleteGroupTarget.id)
      setGroups((prev) => prev.filter((entry) => entry.id !== deleteGroupTarget.id))
      setDeleteGroupTarget(null)
      showToast(t('website.specialCategories.toastDeleted'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.specialCategories.errorDelete'))
      }
    } finally {
      setIsSaving(false)
    }
  }

  async function handleAddCategories(categoryIds: string[]) {
    if (!pickItemsTarget) return

    const existingIds = pickItemsTarget.items.map((item) => item.id)
    const nextIds = [...existingIds, ...categoryIds]

    setIsSaving(true)
    setError('')

    try {
      const result = await updateWebsiteCategoryGroup(pickItemsTarget.id, {
        categoryIds: nextIds,
      })
      replaceGroup(result.group)
      setPickItemsTarget(null)
      showToast(t('website.specialCategories.toastAdded'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.specialCategories.errorAdd'))
      }
    } finally {
      setIsSaving(false)
    }
  }

  async function confirmRemoveFromGroup() {
    if (!removeTarget) return

    const { group, categoryId } = removeTarget
    const nextIds = group.items.map((item) => item.id).filter((id) => id !== categoryId)

    setIsSaving(true)
    setError('')

    try {
      const result = await updateWebsiteCategoryGroup(group.id, {
        categoryIds: nextIds,
      })
      replaceGroup(result.group)
      setRemoveTarget(null)
      showToast(t('website.specialCategories.toastRemoved'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.specialCategories.errorRemove'))
      }
    } finally {
      setIsSaving(false)
    }
  }

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs
        items={[
          { label: 'Dashboard', href: '/' },
          { label: 'Website', href: '/website' },
          { label: 'Special Categories' },
        ]}
      />

      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>{t('title.specialCategories')}</h2>
          <p className={pageStyles.pageSubtitle}>{t('website.specialCategories.subtitle')}</p>
        </div>
      </div>

      {error && <p className={styles.error}>{error}</p>}

      {isLoading ? (
        <p className={styles.empty}>{t('website.specialCategories.loading')}</p>
      ) : groups.length === 0 ? (
        <p className={styles.empty}>{t('website.specialCategories.empty')}</p>
      ) : (
        <div className={styles.carousels}>
          {groups.map((group) => (
            <WebsiteGroupCarousel
              key={group.id}
              title={group.title}
              items={group.items}
              itemKey={(item) => item.id}
              onAddItems={() => setPickItemsTarget(group)}
              onEditGroup={() => setEditGroupTarget(group)}
              onDeleteGroup={() => setDeleteGroupTarget(group)}
              addTooltip={t('website.specialCategories.addTooltip', { title: group.title })}
              renderItem={(item) => (
                <WebsiteGroupItemCard
                  title={item.name}
                  nameFa={item.nameFa}
                  subtitle={item.description}
                  onRemove={() =>
                    setRemoveTarget({
                      group,
                      categoryId: item.id,
                      categoryName: item.name,
                    })
                  }
                />
              )}
            />
          ))}
        </div>
      )}

      <div className={fabStyles.fabDock}>
        <button
          type="button"
          className={fabStyles.addFab}
          onClick={() => setCreateOpen(true)}
          aria-label={t('website.specialCategories.addFab')}
        >
          <Plus size={24} />
        </button>
      </div>

      <StoreSpecialModal
        open={createOpen}
        onClose={() => !isSaving && setCreateOpen(false)}
        onSubmit={handleCreateGroup}
        title={t('website.specialCategories.createTitle')}
        submitLabel={t('website.create')}
        isSubmitting={isSaving}
      />

      <StoreSpecialModal
        open={!!editGroupTarget}
        onClose={() => !isSaving && setEditGroupTarget(null)}
        onSubmit={handleEditGroup}
        initialKey={editGroupTarget?.key ?? ''}
        initialTitle={editGroupTarget?.title ?? ''}
        title={t('website.specialCategories.editTitle')}
        submitLabel={t('website.save')}
        isSubmitting={isSaving}
      />

      <PickWebsiteCategoriesModal
        open={!!pickItemsTarget}
        groupTitle={pickItemsTarget?.title ?? ''}
        existingCategoryIds={pickItemsTarget?.items.map((item) => item.id) ?? []}
        onClose={() => !isSaving && setPickItemsTarget(null)}
        onConfirm={handleAddCategories}
        isSubmitting={isSaving}
      />

      <ConfirmDeleteModal
        open={!!deleteGroupTarget}
        title={t('website.specialCategories.deleteTitle')}
        message={
          deleteGroupTarget
            ? t('website.specialCategories.deleteMessage', { title: deleteGroupTarget.title })
            : ''
        }
        onConfirm={() => void confirmDeleteGroup()}
        onCancel={() => !isSaving && setDeleteGroupTarget(null)}
      />

      <ConfirmDeleteModal
        open={!!removeTarget}
        title={t('website.removeFromGroupTitle')}
        message={
          removeTarget
            ? t('website.removeFromGroupMessage', {
                name: removeTarget.categoryName,
                group: removeTarget.group.title,
              })
            : ''
        }
        onConfirm={() => void confirmRemoveFromGroup()}
        onCancel={() => !isSaving && setRemoveTarget(null)}
      />
    </main>
  )
}
