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 { 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'

const DEFAULT_SLIDER_TITLE = 'Homepage slider'

export function WebsiteSlidersPage() {
  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('Unable to load slides.')
      }
    } 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('Unable to upload slide image.')
      }

      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: DEFAULT_SLIDER_TITLE,
          slides: [slideInput],
        })
        setSlider(result.slider)
      }

      setAddSlideOpen(false)
      showToast('Slide added.', 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('Unable to add slide.')
      }
    } 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('Slide removed.', 'success')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else {
        setError('Unable to remove slide.')
      }
    } 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}>Sliders</h2>
          <p className={pageStyles.pageSubtitle}>
            Manage homepage banner slides in a 9:4 gallery.
          </p>
        </div>
      </div>

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

      {isLoading ? (
        <p className={styles.empty}>Loading slides...</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="Remove Slide"
        message="Remove this slide from the homepage slider?"
        onConfirm={() => void confirmRemoveSlide()}
        onCancel={() => !isSaving && setRemoveTarget(null)}
      />
    </main>
  )
}
