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

import { useState, useCallback } from 'react'
import { FileText, Sparkles, Clock, AlertTriangle } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { Header } from '../components/layout/Header'
import { StatsCard, QuickActions, RecentActivity, PostTypesOverview, OnboardingBanner } from '../components/dashboard'
import { useStats } from '../hooks'
import { useOnboarding } from '../hooks/useOnboarding'
import { t } from '../lib/i18n'

function OnboardingBannerFallback() {
  const { isSetupComplete } = useOnboarding()
  if (!isSetupComplete) return null
  return <OnboardingBanner />
}

function SetupProgress() {
  const { state, setupStepsRemaining, isSetupComplete } = useOnboarding()
  const navigate = useNavigate()

  if (isSetupComplete) return null

  const steps = [
    { key: 'usageSeen' as const, label: t('Usage & Costs'), path: '/usage', icon: '\u{1F4B0}', done: state.usageSeen },
    { key: 'contentTypesSeen' as const, label: t('Content Types'), path: '/post-types', icon: '\u{1F4CB}', done: state.contentTypesSeen },
    { key: 'linksSeen' as const, label: t('Links'), path: '/links', icon: '\u{1F517}', done: state.linksSeen },
    { key: 'reportersSeen' as const, label: t('Reporters'), path: '/reporters', icon: '\u{270D}\uFE0F', done: state.reportersSeen },
  ]

  const nextStep = steps.find(s => !s.done)

  return (
    <div className="mb-6 rounded-bc-md border border-bc-primary/30 bg-gradient-to-l from-bc-primary/5 to-transparent p-5">
      <h2 className="text-lg font-bold mb-1">
        {'\u{1F389}'} {t('Welcome to BoostMedia AI Content Generator!')}
      </h2>
      <p className="text-sm text-bc-gray-600 mb-4">
        {t('You received 60 free BoostCoins to get started. Let\'s set up the plugin in 4 simple steps:')}
      </p>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 mb-4">
        {steps.map((step) => (
          <button
            key={step.key}
            type="button"
            onClick={() => navigate(step.path)}
            className={`flex items-center gap-2 rounded-bc p-2.5 text-sm font-medium transition-all text-start cursor-pointer border-none
              ${step.done
                ? 'bg-green-50 text-green-700 border border-green-200'
                : 'bg-white text-bc-gray-600 border border-bc-gray-200 hover:border-bc-primary hover:bg-bc-primary/5'
              }`}
          >
            <span className="text-lg">{step.done ? '\u2705' : step.icon}</span>
            <span>{step.label}</span>
          </button>
        ))}
      </div>

      {nextStep && (
        <button
          type="button"
          onClick={() => navigate(nextStep.path)}
          className="inline-flex items-center gap-2 rounded-bc bg-bc-primary px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-bc-primary-dark cursor-pointer border-none"
        >
          {setupStepsRemaining === 4
            ? t('Start setup')
            : t('Continue setup')}
        </button>
      )}
    </div>
  )
}

export default function Dashboard() {
  const { stats, loading, error, refetch } = useStats()
  const [isRefreshing, setIsRefreshing] = useState(false)

  const handleRefresh = useCallback(async () => {
    setIsRefreshing(true)
    await refetch()
    setIsRefreshing(false)
  }, [refetch])

  return (
    <div className="min-h-screen">
      {/* Header */}
      <Header
        title={t('Dashboard')}
        subtitle={t('Welcome to BoostMedia AI Content Generator - AI content creation for your site')}
        onRefresh={handleRefresh}
        isRefreshing={isRefreshing}
        helpContent={[
          t('The dashboard shows an overview of your content generation activity and quick actions.'),
          t('Use the setup steps to configure the plugin for your site.'),
          t('Quick actions let you scan content types, create content, or access settings.'),
        ]}
      />

      {/* Content */}
      <div className="p-6">
        {/* Setup Progress (shown during onboarding) */}
        <SetupProgress />

        {/* Original onboarding banner (shown after setup when no content generated yet) */}
        <OnboardingBannerFallback />

        {/* Error Banner */}
        {error && (
          <div className="mb-4 p-3 rounded-bc bg-red-50 border border-red-200 text-sm text-red-600">
            {t('Failed to load dashboard data. Please try refreshing.')}
          </div>
        )}

        {/* Stats Grid */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
          <StatsCard
            title={t('Content Types')}
            value={loading ? '...' : stats ? (stats.total_post_types || 0) : '—'}
            icon={<FileText className="w-6 h-6" />}
            color="primary"
            subtitle={t('Custom post types')}
            helpText={t('Number of custom post types detected on your site, including posts, pages, and custom types from JetEngine or ACF.')}
          />
          <StatsCard
            title={t('Content created')}
            value={loading ? '...' : stats ? (stats.total_generated || 0) : '—'}
            icon={<Sparkles className="w-6 h-6" />}
            color="accent"
            subtitle={t('Total AI-generated posts')}
            helpText={t('Total posts created by BoostMedia AI Content Generator so far.')}
          />
          <StatsCard
            title={t('Pending Publication')}
            value={loading ? '...' : stats ? (stats.pending_publish || 0) : '—'}
            icon={<Clock className="w-6 h-6" />}
            color="warning"
            subtitle={t('Awaiting approval')}
            helpText={t('Posts that were created but not yet published. They are waiting for your review and approval.')}
          />
          <StatsCard
            title={t('Errors')}
            value={loading ? '...' : stats ? (stats.total_errors || 0) : '—'}
            icon={<AlertTriangle className="w-6 h-6" />}
            color={stats?.total_errors && stats.total_errors > 0 ? 'error' : 'success'}
            subtitle={
              stats?.total_errors && stats.total_errors > 0
                ? t('Needs attention')
                : t('All good')
            }
            helpText={t('Errors that occurred during content creation or publishing. Check Logs for details.')}
          />
        </div>

        {/* Main Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Left Column */}
          <div className="space-y-6">
            <QuickActions onScanComplete={handleRefresh} />
            <RecentActivity />
          </div>

          {/* Right Column */}
          <div className="space-y-6">
            <PostTypesOverview />

            {/* Welcome Card */}
            <div className="bg-gradient-to-br from-bc-primary to-bc-primary-dark rounded-bc-md shadow-bc-lg p-6 text-white">
              <h3 className="text-xl font-bold mb-2 text-white">{t('Welcome! 🎉')}</h3>
              <p className="text-white/90 mb-4">
                {t('BoostMedia AI Content Generator lets you create quality content in your site\'s style using AI. Start by scanning your site to identify content types.')}
              </p>
              <div className="flex flex-wrap gap-3 text-sm">
                <span className="bg-white/20 px-3 py-1 rounded-full">{t('✨ AI Content Creation')}</span>
                <span className="bg-white/20 px-3 py-1 rounded-full">{t('📊 Style Analysis')}</span>
                <span className="bg-white/20 px-3 py-1 rounded-full">{t('⏰ Scheduled Publishing')}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Footer Info */}
        <div className="mt-8 text-center text-bc-gray-400 text-sm">
          <p>
            BoostMedia AI Content Generator v{window.bmaiSettings?.version || '?'} • 
            <a
              href="https://boostmedia.co.il"
              target="_blank"
              rel="noopener noreferrer"
              className="text-bc-primary hover:underline mx-1"
            >
              Boost Media LTD
            </a>
            • Made with ❤️ in Israel
          </p>
        </div>
      </div>
    </div>
  )
}
