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

import { useState, useRef, useEffect } from 'react'
import { RefreshCw, ExternalLink, HelpCircle, Globe, X, MessageSquare } from 'lucide-react'
import { Button, FeedbackModal } from '../common'
import { useDataLanguage } from '../../lib/DataLanguageContext'
import { useOnboarding } from '../../hooks/useOnboarding'
import { PingDot } from '../onboarding/PingDot'
import { t } from '../../lib/i18n'

interface HeaderProps {
  title: string
  subtitle?: string
  onRefresh?: () => void
  isRefreshing?: boolean
  helpContent?: string[]
}

export function Header({ title, subtitle, onRefresh, isRefreshing = false, helpContent }: HeaderProps) {
  const [showHelp, setShowHelp] = useState(false)
  const [showFeedback, setShowFeedback] = useState(false)
  const helpRef = useRef<HTMLDivElement>(null)
  const { dataLanguage, setDataLanguage, isSavingLanguage } = useDataLanguage()
  const { state: onboardingState, markSeen } = useOnboarding()

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (helpRef.current && !helpRef.current.contains(e.target as Node)) setShowHelp(false)
    }
    if (showHelp) document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [showHelp])

  return (
    <header className="bg-white border-b border-bc-gray-200 px-6 py-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-bc-gray-800">{title}</h1>
          {subtitle && (
            <p className="text-bc-gray-500 mt-1">{subtitle}</p>
          )}
        </div>

        <div className="flex items-center gap-3">
          <label className="flex items-center gap-2 rounded-bc border border-bc-gray-200 bg-bc-gray-50 px-3 py-2 text-sm text-bc-gray-700">
            <Globe className="w-4 h-4 text-bc-primary" />
            <span className="font-medium">{t('Working Language')}</span>
            <select
              value={dataLanguage}
              onChange={(e) => {
                void setDataLanguage(e.target.value === 'en' ? 'en' : 'he')
              }}
              disabled={isSavingLanguage}
              className="border-none bg-transparent text-sm font-semibold text-bc-gray-800 outline-none"
            >
              <option value="he">{t('Hebrew Data')}</option>
              <option value="en">{t('English Data')}</option>
            </select>
          </label>

          {onRefresh && (
            <Button
              variant="ghost"
              size="sm"
              onClick={onRefresh}
              loading={isRefreshing}
              icon={<RefreshCw className="w-4 h-4" />}
            >
              {t('Refresh')}
            </Button>
          )}

          <div className="relative" ref={helpRef}>
            <Button
              variant="ghost"
              size="sm"
              onClick={() => {
                setShowHelp(!showHelp)
                if (!onboardingState.helpSeen) {
                  void markSeen('helpSeen')
                }
              }}
              icon={<HelpCircle className="w-4 h-4" />}
            >
              {t('Help')}
              <PingDot visible={!onboardingState.helpSeen} size="md" className="ms-1" />
            </Button>
            {showHelp && helpContent && helpContent.length > 0 && (
              <div className="absolute end-0 top-full mt-2 w-80 bg-white border border-bc-gray-200 rounded-bc-md shadow-bc-lg z-50 p-4">
                <div className="flex items-center justify-between mb-3">
                  <h4 className="font-semibold text-bc-gray-800 text-sm flex items-center gap-1.5">
                    <HelpCircle className="w-4 h-4 text-bc-primary" />
                    {t('Page Guide')}
                  </h4>
                  <button
                    type="button"
                    onClick={() => setShowHelp(false)}
                    className="p-0.5 text-bc-gray-400 hover:text-bc-gray-600 bg-transparent border-none cursor-pointer"
                  >
                    <X className="w-3.5 h-3.5" />
                  </button>
                </div>
                <ul className="space-y-2">
                  <li className="text-xs text-bc-gray-600 leading-relaxed ps-3 border-s-2 border-bc-primary/30">
                    {t("This controls which language's content you see and create. It's separate from the admin interface language.")}
                  </li>
                  {helpContent.map((item, i) => (
                    <li key={i} className="text-xs text-bc-gray-600 leading-relaxed ps-3 border-s-2 border-bc-primary/30">
                      {item}
                    </li>
                  ))}
                </ul>
              </div>
            )}
          </div>

          <Button
            variant="ghost"
            size="sm"
            onClick={() => setShowFeedback(true)}
            icon={<MessageSquare className="w-4 h-4" />}
          >
            {t('Feedback')}
          </Button>

          <Button
            variant="ghost"
            size="sm"
            onClick={() => window.open(window.bmaiSettings?.adminUrl || '/wp-admin/', '_blank')}
            icon={<ExternalLink className="w-4 h-4" />}
          >
            {t('Back to WordPress')}
          </Button>
        </div>
      </div>

      <FeedbackModal isOpen={showFeedback} onClose={() => setShowFeedback(false)} />
    </header>
  )
}
