/**
 * BoostMedia AI Content Generator Admin - Post Editor Component
 *
 * @package BoostMedia_AI
 * @license GPL-2.0-or-later
 */

import { useState, useEffect } from 'react'
import { X, Save } from 'lucide-react'
import type { GeneratedPost } from '../../types'
import { Button, Card } from '../common'
import { t } from '../../lib/i18n'

interface PostEditorProps {
  post: GeneratedPost
  onSave: (updatedPost: GeneratedPost) => void
  onClose: () => void
}

interface EditableContent {
  title: string
  content: string
  excerpt: string
  meta_fields: Record<string, string>
  seo: {
    meta_title: string
    meta_description: string
    focus_keyword: string
  }
}

export function PostEditor({ post, onSave, onClose }: PostEditorProps) {
  const [content, setContent] = useState<EditableContent>({
    title: '',
    content: '',
    excerpt: '',
    meta_fields: {},
    seo: {
      meta_title: '',
      meta_description: '',
      focus_keyword: '',
    },
  })
  const [isSaving, setIsSaving] = useState(false)

  useEffect(() => {
    let parsed: Record<string, unknown> = {}
    const raw = post.generated_content ?? post.content
    if (typeof raw === 'object' && raw !== null) {
      parsed = raw as Record<string, unknown>
    } else if (typeof raw === 'string') {
      try {
        parsed = JSON.parse(raw || '{}')
      } catch {
        parsed = { content: raw }
      }
    }

    const seo = parsed.seo as Record<string, string> | undefined
    setContent({
      title: (parsed.title as string) || (post.title as string) || '',
      content: (parsed.content as string) || '',
      excerpt: (parsed.excerpt as string) || (post.excerpt as string) || '',
      meta_fields: (parsed.meta_fields as Record<string, string>) || {},
      seo: {
        meta_title: seo?.meta_title || '',
        meta_description: seo?.meta_description || '',
        focus_keyword: seo?.focus_keyword || '',
      },
    })
  }, [post])

  const handleSave = async () => {
    setIsSaving(true)
    try {
      const updatedPost: GeneratedPost = {
        ...post,
        generated_content: JSON.stringify(content),
      }
      onSave(updatedPost)
    } finally {
      setIsSaving(false)
    }
  }

  const updateMetaField = (key: string, value: string) => {
    setContent((prev) => ({
      ...prev,
      meta_fields: {
        ...prev.meta_fields,
        [key]: value,
      },
    }))
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50">
      <Card className="w-full max-w-4xl max-h-[90vh] overflow-hidden flex flex-col">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-bc-gray-200">
          <h2 className="text-xl font-bold text-bc-gray-800">{t('Edit Post')}</h2>
          <button
            onClick={onClose}
            className="p-2 text-bc-gray-400 hover:text-bc-gray-600 transition-colors bc-focus-visible rounded-bc"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4 space-y-6">
          {/* Title */}
          <div>
            <label className="block font-semibold text-bc-gray-700 mb-2">
              {t('Title')}
            </label>
            <input
              type="text"
              value={content.title}
              onChange={(e) =>
                setContent((prev) => ({ ...prev, title: e.target.value }))
              }
              className="
                w-full p-3 rounded-bc
                border border-bc-gray-300
                bg-white text-bc-gray-800
                focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                transition-all duration-200
              "
            />
          </div>

          {/* Excerpt */}
          <div>
            <label className="block font-semibold text-bc-gray-700 mb-2">
              {t('Excerpt')}
            </label>
            <textarea
              value={content.excerpt}
              onChange={(e) =>
                setContent((prev) => ({ ...prev, excerpt: e.target.value }))
              }
              rows={2}
              className="
                w-full p-3 rounded-bc resize-none
                border border-bc-gray-300
                bg-white text-bc-gray-800
                focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                transition-all duration-200
              "
            />
          </div>

          {/* Content */}
          <div>
            <label className="block font-semibold text-bc-gray-700 mb-2">
              {t('Content')}
            </label>
            <textarea
              value={content.content}
              onChange={(e) =>
                setContent((prev) => ({ ...prev, content: e.target.value }))
              }
              rows={12}
              className="
                w-full p-3 rounded-bc resize-y
                border border-bc-gray-300
                bg-white text-bc-gray-800 font-mono text-sm
                focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                transition-all duration-200
              "
            />
            <p className="text-xs text-bc-gray-400 mt-1">
              {t('HTML input supported')}
            </p>
          </div>

          {/* Meta Fields */}
          {Object.keys(content.meta_fields).length > 0 && (
            <div>
              <h3 className="font-semibold text-bc-gray-700 mb-4">
                {t('Custom fields')}
              </h3>
              <div className="grid grid-cols-2 gap-4">
                {Object.entries(content.meta_fields).map(([key, value]) => (
                  <div key={key}>
                    <label className="block text-sm text-bc-gray-600 mb-1">
                      {key}
                    </label>
                    <input
                      type="text"
                      value={value}
                      onChange={(e) => updateMetaField(key, e.target.value)}
                      className="
                        w-full p-2 rounded-bc text-sm
                        border border-bc-gray-300
                        bg-white text-bc-gray-800
                        focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                        transition-all duration-200
                      "
                    />
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* SEO */}
          <div className="bg-bc-gray-50 rounded-bc-md p-4">
            <h3 className="font-semibold text-bc-gray-700 mb-4">SEO</h3>
            <div className="space-y-4">
              <div>
                <label className="block text-sm text-bc-gray-600 mb-1">
                  {t('Focus Keyword')}
                </label>
                <input
                  type="text"
                  value={content.seo.focus_keyword}
                  onChange={(e) =>
                    setContent((prev) => ({
                      ...prev,
                      seo: { ...prev.seo, focus_keyword: e.target.value },
                    }))
                  }
                  className="
                    w-full p-2 rounded-bc text-sm
                    border border-bc-gray-300
                    bg-white text-bc-gray-800
                    focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                    transition-all duration-200
                  "
                />
              </div>
              <div>
                <label className="block text-sm text-bc-gray-600 mb-1">
                  {t('SEO Title')}
                </label>
                <input
                  type="text"
                  value={content.seo.meta_title}
                  onChange={(e) =>
                    setContent((prev) => ({
                      ...prev,
                      seo: { ...prev.seo, meta_title: e.target.value },
                    }))
                  }
                  className="
                    w-full p-2 rounded-bc text-sm
                    border border-bc-gray-300
                    bg-white text-bc-gray-800
                    focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                    transition-all duration-200
                  "
                />
              </div>
              <div>
                <label className="block text-sm text-bc-gray-600 mb-1">
                  {t('SEO Description')}
                </label>
                <textarea
                  value={content.seo.meta_description}
                  onChange={(e) =>
                    setContent((prev) => ({
                      ...prev,
                      seo: { ...prev.seo, meta_description: e.target.value },
                    }))
                  }
                  rows={2}
                  className="
                    w-full p-2 rounded-bc text-sm resize-none
                    border border-bc-gray-300
                    bg-white text-bc-gray-800
                    focus:ring-2 focus:ring-bc-primary focus:border-bc-primary
                    transition-all duration-200
                  "
                />
              </div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <div className="flex justify-end gap-3 p-4 border-t border-bc-gray-200">
          <Button variant="ghost" onClick={onClose}>
            {t('Cancel')}
          </Button>
          <Button
            onClick={handleSave}
            loading={isSaving}
            icon={<Save className="w-4 h-4" />}
          >
            {t('Save changes')}
          </Button>
        </div>
      </Card>
    </div>
  )
}
