'use client'

import { useState, useEffect } from 'react'
import { getAISettings, updateAISettings } from '@/app/actions/ai-settings'
import { getSystemConfig } from '@/lib/config'
import { Switch } from '@/components/ui/switch'
import { Badge } from '@/components/ui/badge'
import { Zap, TrendingUp, Activity, Settings, Brain, Tag, Globe, Sparkles } from 'lucide-react'
import { AdminMetrics } from '@/components/admin-metrics'
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'

interface FeatureState {
  titleSuggestions: boolean
  semanticSearch: boolean
  paragraphRefactor: boolean
  memoryEcho: boolean
  languageDetection: boolean
  autoLabeling: boolean
}

interface ProviderInfo {
  name: string
  status: string
}

export function AdminAIPageClient({
  initialFeatures,
  providers,
}: {
  initialFeatures: FeatureState
  providers: ProviderInfo[]
}) {
  const [features, setFeatures] = useState<FeatureState>(initialFeatures)
  const [saving, setSaving] = useState<string | null>(null)
  const { t } = useLanguage()

  const handleToggle = async (key: keyof FeatureState, value: boolean) => {
    setSaving(key)
    setFeatures(prev => ({ ...prev, [key]: value }))
    try {
      await updateAISettings({ [key]: value })
      toast.success(t('admin.ai.settingUpdated'))
    } catch {
      toast.error(t('admin.ai.updateFailedShort'))
      setFeatures(prev => ({ ...prev, [key]: !value }))
    } finally {
      setSaving(null)
    }
  }

  const featureList = [
    {
      key: 'titleSuggestions' as const,
      label: t('admin.ai.titleSuggestions'),
      description: t('admin.ai.titleSuggestionsDesc'),
      icon: <Sparkles className="h-4 w-4 text-yellow-500" />,
    },

    {
      key: 'paragraphRefactor' as const,
      label: t('admin.ai.aiAssistant'),
      description: t('admin.ai.aiAssistantDesc'),
      icon: <Brain className="h-4 w-4 text-purple-500" />,
    },

    {
      key: 'memoryEcho' as const,
      label: t('admin.ai.memoryEchoFeature'),
      description: t('admin.ai.memoryEchoFeatureDesc'),
      icon: <Zap className="h-4 w-4 text-amber-500" />,
    },
    {
      key: 'languageDetection' as const,
      label: t('admin.ai.languageDetection'),
      description: t('admin.ai.languageDetectionDesc'),
      icon: <Globe className="h-4 w-4 text-green-500" />,
    },
    {
      key: 'autoLabeling' as const,
      label: t('admin.ai.autoLabeling'),
      description: t('admin.ai.autoLabelingDesc'),
      icon: <Tag className="h-4 w-4 text-rose-500" />,
    },
  ]

  const aiMetrics = [
    {
      title: t('admin.ai.activeFeatures'),
      value: String(Object.values(features).filter(Boolean).length) + ' / ' + featureList.length,
      trend: { value: 0, isPositive: true },
      icon: <Zap className="h-5 w-5 text-yellow-600 dark:text-yellow-400" />,
    },
    {
      title: t('admin.ai.successRate'),
      value: '100%',
      trend: { value: 0, isPositive: true },
      icon: <TrendingUp className="h-5 w-5 text-green-600 dark:text-green-400" />,
    },
    {
      title: t('admin.ai.avgResponseTime'),
      value: '—',
      trend: { value: 0, isPositive: true },
      icon: <Activity className="h-5 w-5 text-primary dark:text-primary-foreground" />,
    },
    {
      title: t('admin.ai.configuredProviders'),
      value: String(providers.filter(p => p.status !== 'Not Configured').length),
      icon: <Settings className="h-5 w-5 text-purple-600 dark:text-purple-400" />,
    },
  ]

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">
            {t('admin.ai.pageTitle')}
          </h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            {t('admin.ai.pageDescription')}
          </p>
        </div>
        <Link href="/admin/settings">
          <Button variant="outline">
            <Settings className="mr-2 h-4 w-4" />
            {t('admin.ai.configure')}
          </Button>
        </Link>
      </div>

      <AdminMetrics metrics={aiMetrics} />

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Feature Toggles */}
        <div className="bg-white dark:bg-zinc-900 rounded-lg shadow overflow-hidden border border-gray-200 dark:border-gray-800 p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            {t('admin.ai.features')}
          </h2>
          <div className="space-y-4">
            {featureList.map(({ key, label, description, icon }) => (
              <div
                key={key}
                className="flex items-center justify-between p-3 bg-gray-50 dark:bg-zinc-800 rounded-lg"
              >
                <div className="flex items-center gap-3 flex-1 min-w-0">
                  {icon}
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-gray-900 dark:text-white truncate">
                      {label}
                    </p>
                    <p className="text-xs text-gray-500 dark:text-gray-400 truncate">
                      {description}
                    </p>
                  </div>
                </div>
                <Switch
                  checked={features[key]}
                  onCheckedChange={(v) => handleToggle(key, v)}
                  disabled={saving === key}
                  className="ml-3 flex-shrink-0"
                />
              </div>
            ))}
          </div>
        </div>

        {/* AI Provider Status */}
        <div className="bg-white dark:bg-zinc-900 rounded-lg shadow overflow-hidden border border-gray-200 dark:border-gray-800 p-6">
          <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
            {t('admin.ai.providerStatus')}
          </h2>
          <div className="space-y-3">
            {providers.map((provider) => (
              <div
                key={provider.name}
                className="flex items-center justify-between p-3 bg-gray-50 dark:bg-zinc-800 rounded-lg"
              >
                <p className="text-sm font-medium text-gray-900 dark:text-white">
                  {provider.name}
                </p>
                <span
                  className={`px-2 py-1 text-xs font-medium rounded-full ${
                    provider.status === 'Connected' || provider.status === 'Available'
                      ? 'text-green-700 dark:text-green-400 bg-green-100 dark:bg-green-900'
                      : 'text-gray-600 dark:text-gray-400 bg-gray-100 dark:bg-gray-800'
                  }`}
                >
                  {provider.status}
                </span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="bg-white dark:bg-zinc-900 rounded-lg shadow overflow-hidden border border-gray-200 dark:border-gray-800 p-6">
        <h2 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
          {t('admin.ai.recentRequests')}
        </h2>
        <p className="text-gray-600 dark:text-gray-400">
          {t('admin.ai.comingSoon')}
        </p>
      </div>
    </div>
  )
}
