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

import { useState, useEffect, useCallback } from 'react'
import {
  Download,
  RefreshCw,
  CheckCircle,
  AlertTriangle,
  Loader2,
  Package,
  ExternalLink,
} from 'lucide-react'
import { Header } from '../components/layout/Header'
import { Card, CardContent, Button } from '../components/common'
import { useUpdateCheck } from '../hooks/useUpdateCheck'
import { t, tf, getDateLocale } from '../lib/i18n'

function sanitizeHtml(html: string): string {
  const div = document.createElement('div')
  div.innerHTML = html
  div.querySelectorAll('script, iframe, object, embed, form').forEach(el => el.remove())
  div.querySelectorAll('*').forEach(el => {
    Array.from(el.attributes).forEach(attr => {
      if (attr.name.startsWith('on') || attr.value.startsWith('javascript:')) {
        el.removeAttribute(attr.name)
      }
    })
  })
  return div.innerHTML
}

interface UpdateCheckResult {
  current_version: string
  latest_version: string
  update_available: boolean
  download_url: string
  changelog: string
  release_date: string
  last_checked: string
}

function BoostContentIcon({ className }: { className?: string }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none" className={className}>
      <rect x="0" y="0" width="64" height="64" rx="14" fill="#3BC2D0"/>
      <g transform="translate(12, 12) scale(1.67)" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" fill="none">
        <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
      </g>
    </svg>
  )
}

function ToggleSwitch({ checked, onChange, disabled }: {
  checked: boolean
  onChange: () => void
  disabled?: boolean
}) {
  return (
    <button
      type="button"
      role="switch"
      aria-checked={checked}
      onClick={onChange}
      disabled={disabled}
      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-bc-primary focus:ring-offset-2 border-none ${
        checked ? 'bg-bc-primary' : 'bg-bc-gray-300'
      } ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}`}
    >
      <span className={`absolute h-4 w-4 rounded-full bg-white shadow transition-all duration-200 ${
        checked ? 'inset-inline-end-1' : 'inset-inline-start-1'
      }`} />
    </button>
  )
}

export default function UpdatesPage() {
  const [checkResult, setCheckResult] = useState<UpdateCheckResult | null>(null)
  const [isChecking, setIsChecking] = useState(false)
  const [isUpdating, setIsUpdating] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [successMessage, setSuccessMessage] = useState<string | null>(null)
  const [autoUpdate, setAutoUpdate] = useState(true)
  const [autoUpdateLoading, setAutoUpdateLoading] = useState(false)

  const { clearCache } = useUpdateCheck()

  const currentVersion = window.bmaiSettings?.version || '1.0.0'
  const rawApiUrl = window.bmaiSettings?.apiUrl || '/wp-json/bmai/v1/'
  const apiUrl = rawApiUrl.replace(/\/+$/, '') + '/'
  const nonce = window.bmaiSettings?.nonce || ''

  useEffect(() => {
    checkForUpdates()
    fetchAutoUpdateSetting()
  }, [])

  const fetchAutoUpdateSetting = useCallback(async () => {
    try {
      const response = await fetch(`${apiUrl}updates/auto-update`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
        credentials: 'same-origin',
      })
      if (response.ok) {
        const data = await response.json()
        if (data.success && data.data) {
          setAutoUpdate(data.data.auto_update)
        }
      }
    } catch { /* default stays true */ }
  }, [apiUrl, nonce])

  const toggleAutoUpdate = useCallback(async () => {
    const newValue = !autoUpdate
    setAutoUpdateLoading(true)
    try {
      const response = await fetch(`${apiUrl}updates/auto-update`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
        credentials: 'same-origin',
        body: JSON.stringify({ auto_update: newValue }),
      })
      if (response.ok) {
        const data = await response.json()
        if (data.success && data.data) {
          setAutoUpdate(data.data.auto_update)
        }
      }
    } catch { /* revert on error */ }
    finally { setAutoUpdateLoading(false) }
  }, [autoUpdate, apiUrl, nonce])

  const [updaterUnavailable, setUpdaterUnavailable] = useState(false)

  async function checkForUpdates() {
    setIsChecking(true)
    setError(null)
    setSuccessMessage(null)
    try {
      const response = await fetch(`${apiUrl}updates/check`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
        credentials: 'same-origin',
      })
      if (response.status === 403 || response.status === 404) {
        setUpdaterUnavailable(true)
        return
      }
      if (!response.ok) throw new Error(t('Error checking updates') + ` (${response.status})`)
      const data = await response.json()
      if (data.success !== false) {
        setCheckResult(data.data || data)
      } else {
        throw new Error(data.message || t('Error checking updates'))
      }
    } catch (err: any) {
      setError(err.message || t('Cannot check updates. Try again later.'))
    } finally {
      setIsChecking(false)
    }
  }

  async function installUpdate() {
    if (!checkResult?.update_available || !checkResult?.download_url?.startsWith('https://')) return
    setIsUpdating(true)
    setError(null)
    setSuccessMessage(null)
    try {
      const response = await fetch(`${apiUrl}updates/install`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
        credentials: 'same-origin',
        body: JSON.stringify({ download_url: checkResult.download_url, version: checkResult.latest_version }),
      })
      if (!response.ok) throw new Error(t('Error installing update') + ` (${response.status})`)
      const data = await response.json()
      if (data.success !== false) {
        const backendMessage = typeof data.message === 'string' && data.message
          ? `${t(data.message)} `
          : ''
        setSuccessMessage(`${backendMessage}${tf('Updated successfully to version %s! Refresh the page.', checkResult.latest_version)}`.trim())
        setCheckResult(prev => prev ? { ...prev, update_available: false, current_version: prev.latest_version } : null)
        clearCache()
      } else {
        throw new Error(data.message || t('Error installing update'))
      }
    } catch (err: any) {
      setError(err.message || t('Cannot install update. Try manually.'))
    } finally {
      setIsUpdating(false)
    }
  }

  const versionAvailableParts = t('Version %s available').split('%s')

  if (updaterUnavailable) {
    return (
      <div className="min-h-screen">
        <Header
          title={t('Updates')}
          subtitle={t('Check and install plugin updates')}
          helpContent={[t('Updates are managed through WordPress.org')]}
        />
        <div className="p-6">
          <Card padding="none">
            <CardContent className="p-6 text-center">
              <div className="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <CheckCircle className="w-6 h-6 text-blue-500" />
              </div>
              <h2 className="text-lg font-semibold text-bc-gray-800 mb-2">{t('Updates are managed through WordPress.org')}</h2>
              <p className="text-sm text-bc-gray-500">
                {t('Check for plugin updates in the WordPress Dashboard under Plugins or Dashboard → Updates.')}
              </p>
            </CardContent>
          </Card>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen">
      <Header
        title={t('Updates')}
        subtitle={t('Check and install plugin updates')}
        onRefresh={checkForUpdates}
        isRefreshing={isChecking}
        helpContent={[
          t('The plugin checks for updates automatically. You can also click Refresh to check manually.'),
          t('When an update is available, click "Install Update" to download and install it.'),
          t('Enable "Automatic Updates" to install new versions automatically when they are released.'),
          t('The changelog shows what changed in each version.'),
        ]}
      />

      <div className="p-6 space-y-6">

        {/* Status Messages */}
        {error && (
          <div className="p-4 bg-red-50 border border-red-200 rounded-bc flex items-start gap-3">
            <AlertTriangle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
            <div>
              <p className="font-medium text-red-800">{t('Error')}</p>
              <p className="text-sm text-red-700">{error}</p>
            </div>
          </div>
        )}

        {successMessage && (
          <div className="p-4 bg-green-50 border border-green-200 rounded-bc flex items-start gap-3">
            <CheckCircle className="w-5 h-5 text-green-500 flex-shrink-0 mt-0.5" />
            <div>
              <p className="font-medium text-green-800">{t('Success')}</p>
              <p className="text-sm text-green-700">{successMessage}</p>
            </div>
          </div>
        )}

        {/* Current Version + Update Status */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Current Version Card */}
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-2 mb-4">
                <Package className="w-5 h-5 text-bc-gray-600" />
                <h2 className="text-lg font-semibold text-bc-gray-800">{t('Current Version')}</h2>
              </div>
              <div className="flex items-center justify-between">
                <div>
                  <div className="text-3xl font-bold text-bc-primary">
                    v{checkResult?.current_version || currentVersion}
                  </div>
                  <p className="text-sm text-bc-gray-500 mt-1">BoostMedia AI Content Generator for WordPress</p>
                </div>
                <BoostContentIcon className="w-16 h-16" />
              </div>
              {checkResult?.last_checked && (
                <div className="mt-4 pt-4 border-t border-bc-gray-100">
                  <p className="text-xs text-bc-gray-400">
                    {t('Last check:')} {new Date(checkResult.last_checked).toLocaleString(getDateLocale())}
                  </p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* Update Status Card */}
          <Card padding="none">
            <CardContent className="p-6">
              <div className="flex items-center gap-2 mb-4">
                <Download className="w-5 h-5 text-bc-gray-600" />
                <h2 className="text-lg font-semibold text-bc-gray-800">{t('Update Status')}</h2>
              </div>

              {isChecking ? (
                <div className="flex flex-col items-center justify-center py-8">
                  <Loader2 className="w-8 h-8 text-bc-primary animate-spin mb-3" />
                  <p className="text-sm text-bc-gray-500">{t('Checking for updates...')}</p>
                </div>
              ) : checkResult?.update_available ? (
                <div className="space-y-4">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 bg-amber-100 rounded-bc flex items-center justify-center">
                      <AlertTriangle className="w-5 h-5 text-amber-500" />
                    </div>
                    <div>
                      <p className="font-semibold text-bc-gray-800">{t('Update available!')}</p>
                      <p className="text-sm text-bc-gray-500">
                        {versionAvailableParts[0]}<span className="font-mono font-bold text-bc-primary">{checkResult.latest_version}</span>{versionAvailableParts[1]}
                      </p>
                    </div>
                  </div>

                  {checkResult.release_date && (
                    <p className="text-xs text-bc-gray-400">
                      {t('Released:')} {new Date(checkResult.release_date).toLocaleDateString(getDateLocale())}
                    </p>
                  )}

                  <Button
                    variant="primary"
                    onClick={installUpdate}
                    disabled={isUpdating}
                    loading={isUpdating}
                    className="w-full"
                    icon={isUpdating ? undefined : <Download className="w-4 h-4" />}
                  >
                    {isUpdating ? t('Installing...') : tf('Update to version v%s', checkResult.latest_version)}
                  </Button>

                  {checkResult.download_url?.startsWith('https://') && (
                    <a
                      href={checkResult.download_url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="flex items-center justify-center gap-2 text-sm text-bc-gray-500 hover:text-bc-primary transition-colors"
                    >
                      <ExternalLink className="w-3.5 h-3.5" />
                      {t('Manual download')}
                    </a>
                  )}
                </div>
              ) : checkResult ? (
                <div className="flex flex-col items-center justify-center py-8">
                  <div className="w-12 h-12 bg-green-100 rounded-full flex items-center justify-center mb-3">
                    <CheckCircle className="w-6 h-6 text-green-500" />
                  </div>
                  <p className="font-semibold text-bc-gray-800">{t('Your version is up to date!')}</p>
                  <p className="text-sm text-bc-gray-500 mt-1">
                    {tf('BoostMedia AI Content Generator v%s is the latest version', checkResult.current_version)}
                  </p>
                </div>
              ) : (
                <div className="flex flex-col items-center justify-center py-8">
                  <p className="text-sm text-bc-gray-500">{t('Click the refresh button to check for updates')}</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Changelog */}
        {checkResult?.changelog && checkResult.update_available && (
          <Card padding="none">
            <CardContent className="p-6">
              <h2 className="text-lg font-semibold text-bc-gray-800 mb-4">
                {tf("What's new in version v%s", checkResult.latest_version)}
              </h2>
              <div
                className="prose prose-sm max-w-none text-bc-gray-600"
                dangerouslySetInnerHTML={{ __html: sanitizeHtml(checkResult.changelog || '') }}
              />
            </CardContent>
          </Card>
        )}

        {/* Auto-update Toggle */}
        <Card padding="none">
          <CardContent className="p-6">
            <div className="flex items-center gap-2 mb-4">
              <RefreshCw className="w-5 h-5 text-bc-gray-600" />
              <h2 className="text-lg font-semibold text-bc-gray-800">{t('Automatic Updates')}</h2>
            </div>
            <div className="flex items-center justify-between">
              <div>
                <label className="text-sm font-medium text-bc-gray-700">{t('Background automatic updates')}</label>
                <p className="text-xs text-bc-gray-500">
                  {t('When enabled, WordPress will install new versions of BoostMedia AI Content Generator automatically in the background.')}
                </p>
              </div>
              <ToggleSwitch
                checked={autoUpdate}
                onChange={toggleAutoUpdate}
                disabled={autoUpdateLoading}
              />
            </div>
            <div className={`mt-3 text-xs rounded-bc px-3 py-2 ${
              autoUpdate ? 'bg-green-50 text-green-700' : 'bg-amber-50 text-amber-700'
            }`}>
              {autoUpdate
                ? t('Automatic updates enabled. New versions will be installed automatically.')
                : t('Automatic updates disabled. You will need to update manually from this page.')}
            </div>
          </CardContent>
        </Card>

        {/* Info Card */}
        <Card padding="none">
          <CardContent className="p-4">
            <div className="p-3 bg-blue-50 rounded-bc text-sm text-blue-700">
              <p className="font-medium mb-1">{t('About updates')}</p>
              <ul className="list-disc list-inside space-y-1 text-blue-600">
                <li>{t('Updates are checked automatically from time to time')}</li>
                <li>{t('You can also check manually from this page at any time')}</li>
                <li>{t('It is recommended to back up the site before updating')}</li>
                <li>{t('After updating, clear browser cache and refresh the admin page')}</li>
              </ul>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
