import { useEffect, useState } from 'react'
import {
  AddWebsiteSliderSlideModal,
  type WebsiteSliderSlideFormData,
} from '../components/AddWebsiteSliderSlideModal'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { ConfirmDeleteModal } from '../components/ConfirmDeleteModal'
import { WebsiteSliderGallery } from '../components/WebsiteSliderGallery'
import { useToast } from '../context/ToastContext'
import { useT } from '../i18n/useT'
import { ApiError } from '../lib/api'
import { resolveDataUrlToMediaId } from '../services/mediaService'
import {
  createWebsiteSlider,
  listWebsiteSliders,
  slidesToPayload,
  updateWebsiteSlider,
} from '../services/websiteSliderService'
import type { WebsiteSlider, WebsiteSliderSlide } from '../types/websiteSlider'
import pageStyles from '../components/PageContent.module.css'
import styles from './StoreSpecialsPage.module.css'

export function WebsiteSlidersPage() {
  const t = useT()
  const { showToast } = useToast()
  const [slider, setSlider] = useState<WebsiteSlider | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [isSaving, setIsSaving] = useState(false)
  const [error, setError] = useState('')
  const [addSlideOpen, setAddSlideOpen] = useState(false)
  const [removeTarget, setRemoveTarget] = useState<WebsiteSliderSlide | null>(null)

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

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

    try {
      const data = await listWebsiteSliders(1, 1, signal)
      setSlider(data.items[0] ?? null)
    } catch (err) {
      if (err instanceof DOMException && err.name === 'AbortError') return
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.sliders.errorLoad'))
      }
    } finally {
      setIsLoading(false)
    }
  }

  async function handleAddSlide(data: WebsiteSliderSlideFormData) {
    setIsSaving(true)
    setError('')

    try {
      const imageMediaId = await resolveDataUrlToMediaId(data.image, 'slider-slide.jpg')
      if (!imageMediaId) {
        throw new Error(t('website.sliders.errorUpload'))
      }

      const slideInput = {
        imageMediaId,
        ...(data.title ? { title: data.title } : {}),
        ...(data.linkUrl ? { linkUrl: data.linkUrl } : {}),
        isActive: true,
      }

      if (slider) {
        const result = await updateWebsiteSlider(slider.id, {
          slides: [...slidesToPayload(slider.slides), slideInput],
        })
        setSlider(result.slider)
      } else {
        const result = await createWebsiteSlider({
          title: t('website.sliders.defaultTitle'),
          slides: [slideInput],
        })
        setSlider(result.slider)
      }

      setAddSlideOpen(false)
      showToast(t('website.sliders.toastAdded'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else if (err instanceof Error) {
        setError(err.message)
      } else {
        setError(t('website.sliders.errorAdd'))
      }
    } finally {
      setIsSaving(false)
    }
  }

  async function confirmRemoveSlide() {
    if (!slider || !removeTarget) return

    const nextSlides = slidesToPayload(
      slider.slides.filter((entry) => entry.id !== removeTarget.id),
    )

    setIsSaving(true)
    setError('')

    try {
      const result = await updateWebsiteSlider(slider.id, { slides: nextSlides })
      setSlider(result.slider)
      setRemoveTarget(null)
      showToast(t('website.sliders.toastRemoved'), 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError(t('website.sliders.errorRemove'))
      }
    } finally {
      setIsSaving(false)
    }
  }

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

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

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

      {isLoading ? (
        <p className={styles.empty}>{t('website.sliders.loading')}</p>
      ) : (
        <WebsiteSliderGallery
          slides={slider?.slides ?? []}
          onAddSlide={() => setAddSlideOpen(true)}
          onRemoveSlide={setRemoveTarget}
        />
      )}

      <AddWebsiteSliderSlideModal
        open={addSlideOpen}
        onClose={() => !isSaving && setAddSlideOpen(false)}
        onSubmit={(data) => void handleAddSlide(data)}
        isSubmitting={isSaving}
      />

      <ConfirmDeleteModal
        open={!!removeTarget}
        title={t('website.sliders.removeTitle')}
        message={t('website.sliders.removeMessage')}
        onConfirm={() => void confirmRemoveSlide()}
        onCancel={() => !isSaving && setRemoveTarget(null)}
      />
    </main>
  )
}
