import { useEffect, useState } from 'react'
import { Link, useParams, useNavigate } from 'react-router-dom'
import { SearchableSelect } from '../components/SearchableSelect'
import { ImageCropper } from '../components/ImageCropper'
import { TagInput } from '../components/TagInput'
import { RichTextEditor } from '../components/RichTextEditor'
import { Breadcrumbs } from '../components/Breadcrumbs'
import { useToast } from '../context/ToastContext'
import { ApiError } from '../lib/api'
import {
  listBlogCategories,
  mapBlogCategoryToUi,
} from '../services/blogCategoryService'
import {
  resolveDataUrlToMediaId,
  resolveHtmlEmbeddedDataUrls,
} from '../services/mediaService'
import {
  createBlog,
  getBlog,
  mapBlogApiToFormState,
  updateBlog,
} from '../services/blogService'
import type { Category } from '../types/category'
import type { BlogPostType } from '../types/blog'
import { BLOG_TYPE_OPTIONS } from '../types/blog'
import { flattenCategories } from '../utils/categories'
import pageStyles from '../components/PageContent.module.css'
import styles from './AddNewProductPage.module.css'

export function AddNewBlogPage() {
  const { id } = useParams()
  const navigate = useNavigate()
  const { showToast } = useToast()
  const isEdit = Boolean(id)

  const [categories, setCategories] = useState<Category[]>([])
  const [type, setType] = useState<BlogPostType>('blog')
  const [categoryId, setCategoryId] = useState('')
  const [title, setTitle] = useState('')
  const [abstract, setAbstract] = useState('')
  const [mainTextHtml, setMainTextHtml] = useState('')
  const [titleImage, setTitleImage] = useState<string | null>(null)
  const [tags, setTags] = useState<string[]>([])
  const [featuredMediaId, setFeaturedMediaId] = useState<string | null>(null)
  const [loaded, setLoaded] = useState(!isEdit)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState('')

  const categoryOptions = flattenCategories(categories)

  useEffect(() => {
    const controller = new AbortController()

    async function loadCategories() {
      try {
        const items = await listBlogCategories(controller.signal)
        setCategories(items.map(mapBlogCategoryToUi))
      } catch (err) {
        if (err instanceof DOMException && err.name === 'AbortError') return
        if (err instanceof ApiError) {
          setError(err.message)
        } else {
          setError('Unable to load categories.')
        }
      }
    }

    void loadCategories()
    return () => controller.abort()
  }, [])

  useEffect(() => {
    if (!isEdit || !id) return

    const controller = new AbortController()

    async function loadBlog() {
      setError('')
      try {
        const blog = await getBlog(id!, controller.signal)
        const form = mapBlogApiToFormState(blog)
        setType(form.type)
        setCategoryId(form.categoryId)
        setTitle(form.title)
        setAbstract(form.abstract)
        setMainTextHtml(form.mainTextHtml)
        setTitleImage(form.titleImage)
        setTags(form.tags)
        setFeaturedMediaId(form.featuredMediaId)
        setLoaded(true)
      } catch (err) {
        if (err instanceof DOMException && err.name === 'AbortError') return
        navigate('/blog/list', { replace: true })
      }
    }

    void loadBlog()
    return () => controller.abort()
  }, [isEdit, id, navigate])

  if (!loaded) return null

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setIsSubmitting(true)
    setError('')

    try {
      const nextFeaturedMediaId = await resolveDataUrlToMediaId(
        titleImage,
        'blog-title-image.jpg',
        featuredMediaId,
      )
      const resolvedMainTextHtml = await resolveHtmlEmbeddedDataUrls(mainTextHtml)

      const payload = {
        title: title.trim(),
        type,
        abstract: abstract.trim(),
        mainTextHtml: resolvedMainTextHtml,
        categoryId: categoryId || undefined,
        featuredMediaId: nextFeaturedMediaId ?? undefined,
        tags,
        status: 'published' as const,
      }

      if (isEdit && id) {
        await updateBlog(id, {
          ...payload,
          categoryId: categoryId || null,
          featuredMediaId: nextFeaturedMediaId,
        })
        showToast('Blog post updated.', 'success')
      } else {
        await createBlog(payload)
        showToast('Blog post created.', 'success')
      }

      navigate('/blog/list')
    } catch (err) {
      if (err instanceof ApiError) {
        setError(err.message)
      } else if (err instanceof Error) {
        setError(err.message)
      } else {
        setError('Unable to save blog post.')
      }
    } finally {
      setIsSubmitting(false)
    }
  }

  return (
    <main className={pageStyles.content}>
      <Breadcrumbs
        items={
          isEdit
            ? [
                { label: 'Dashboard', href: '/' },
                { label: 'Blog', href: '/blog' },
                { label: 'My Blogs', href: '/blog/list' },
                { label: 'Edit Blog' },
              ]
            : [
                { label: 'Dashboard', href: '/' },
                { label: 'Blog', href: '/blog' },
                { label: 'Add New Blog' },
              ]
        }
      />
      <div className={pageStyles.pageHeader}>
        <div>
          <h2 className={pageStyles.pageTitle}>
            {isEdit ? 'Edit Blog' : 'Add New Blog'}
          </h2>
          <p className={pageStyles.pageSubtitle}>
            {isEdit
              ? 'Update blog post details and save changes.'
              : 'Create and publish a new blog post.'}
          </p>
        </div>
      </div>

      {error && (
        <div className={styles.error} role="alert">
          {error}
        </div>
      )}

      <form className={styles.form} onSubmit={handleSubmit}>
        <div className={styles.formGrid}>
          <div className={`${styles.field} ${styles.col3} ${styles.rowSpan3}`}>
            <label>Title Image</label>
            <ImageCropper
              value={titleImage}
              onChange={setTitleImage}
              aspect={3 / 2}
              uploadLabel="Upload title image"
              hint="Click to select, then crop"
              changeLabel="Change title image"
            />
          </div>

          <div className={`${styles.field} ${styles.col3}`}>
            <label htmlFor="blog-type">Type</label>
            <select
              id="blog-type"
              value={type}
              onChange={(e) => setType(e.target.value as BlogPostType)}
              disabled={isSubmitting}
            >
              {BLOG_TYPE_OPTIONS.map((option) => (
                <option key={option.value} value={option.value}>
                  {option.label}
                </option>
              ))}
            </select>
          </div>

          <div className={`${styles.field} ${styles.col6Span}`}>
            <label>Category</label>
            <SearchableSelect
              options={categoryOptions}
              value={categoryId}
              onChange={setCategoryId}
              placeholder="Search and select category..."
            />
          </div>

          <div className={`${styles.field} ${styles.col9}`}>
            <label htmlFor="blog-title">Title</label>
            <input
              id="blog-title"
              name="title"
              type="text"
              placeholder="Blog post title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              required
              disabled={isSubmitting}
            />
          </div>

          <div className={`${styles.field} ${styles.col9}`}>
            <label htmlFor="blog-abstract">Abstract</label>
            <textarea
              id="blog-abstract"
              name="abstract"
              rows={4}
              placeholder="Short summary shown in blog listings"
              value={abstract}
              onChange={(e) => setAbstract(e.target.value)}
              required
              disabled={isSubmitting}
            />
          </div>

          <div className={`${styles.field} ${styles.col12}`}>
            <label>Main Text</label>
            <RichTextEditor
              value={mainTextHtml}
              onChange={setMainTextHtml}
              placeholder="Full blog content with formatting and images..."
              allowImages
              editorMinHeight={320}
            />
          </div>

          <div className={`${styles.field} ${styles.col12}`}>
            <label>Tags</label>
            <TagInput tags={tags} onChange={setTags} />
          </div>
        </div>

        <div className={styles.actions}>
          <Link to="/blog/list" className={styles.cancelBtn}>
            Cancel
          </Link>
          <button type="submit" className={styles.submitBtn} disabled={isSubmitting}>
            {isSubmitting ? 'Saving...' : isEdit ? 'Update Blog' : 'Save Blog'}
          </button>
        </div>
      </form>
    </main>
  )
}
