'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" />,
    },

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

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

  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-primary" />,
    },
    {
      title: t('admin.ai.successRate'),
      value: '100%',
      trend: { value: 0, isPositive: true },
      icon: <TrendingUp className="h-5 w-5 text-green-600" />,
    },
    {
      title: t('admin.ai.avgResponseTime'),
      value: '—',
      trend: { value: 0, isPositive: true },
      icon: <Activity className="h-5 w-5 text-primary" />,
    },
    {
      title: t('admin.ai.configuredProviders'),
      value: String(providers.filter(p => p.status !== 'Not Configured').length),
      icon: <Settings className="h-5 w-5 text-primary" />,
    },
  ]

  return (
    <div className="space-y-8">
      <div className="flex justify-between items-start">
        <div>
          <h1 className="text-2xl font-bold tracking-tight text-foreground">
            {t('admin.ai.pageTitle')}
          </h1>
          <p className="text-muted-foreground mt-1">
            {t('admin.ai.pageDescription')}
          </p>
        </div>
        <Link href="/admin/settings">
          <Button variant="outline" className="border-border">
            <Settings className="mr-2 h-4 w-4" />
            {t('admin.ai.configure')}
          </Button>
        </Link>
      </div>

      <AdminMetrics metrics={aiMetrics} />

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Feature Toggles */}
        <div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
          <div className="flex items-center gap-3 mb-2">
            <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
              <Zap className="h-5 w-5" />
            </div>
            <div>
              <h2 className="font-semibold text-foreground">{t('admin.ai.features')}</h2>
              <p className="text-sm text-muted-foreground">Activez ou désactivez les fonctionnalités IA</p>
            </div>
          </div>
          <div className="space-y-4 pt-2 border-t border-border">
            {featureList.map(({ key, label, description, icon }) => (
              <div
                key={key}
                className="flex items-start justify-between p-3 bg-muted rounded-lg border border-border/50"
              >
                <div className="flex items-start gap-3 flex-1 min-w-0">
                  <div className="mt-0.5 text-primary">{icon}</div>
                  <div className="min-w-0">
                    <p className="text-sm font-medium text-foreground truncate">
                      {label}
                    </p>
                    <p className="text-xs text-muted-foreground truncate">
                      {description}
                    </p>
                  </div>
                </div>
                <Switch
                  checked={features[key]}
                  onCheckedChange={(v) => handleToggle(key, v)}
                  disabled={saving === key}
                  className="ml-3 mt-0.5 flex-shrink-0"
                />
              </div>
            ))}
          </div>
        </div>

        {/* AI Provider Status */}
        <div className="flex flex-col gap-6">
          <div className="bg-card rounded-lg border border-border p-6 shadow-sm flex flex-col gap-4">
            <div className="flex items-center gap-3 mb-2">
              <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0">
                <Settings className="h-5 w-5" />
              </div>
              <div>
                <h2 className="font-semibold text-foreground">{t('admin.ai.providerStatus')}</h2>
                <p className="text-sm text-muted-foreground">État de vos fournisseurs connectés</p>
              </div>
            </div>
            <div className="space-y-3 pt-2 border-t border-border">
              {providers.map((provider) => (
                <div
                  key={provider.name}
                  className="flex items-center justify-between p-3 bg-muted rounded-lg border border-border/50"
                >
                  <p className="text-sm font-medium text-foreground">
                    {provider.name}
                  </p>
                  <span
                    className={`px-2 py-1 text-xs font-medium rounded-full ${
                      provider.status === 'Connected' || provider.status === 'Available'
                        ? 'text-green-700 bg-green-500/10 border border-green-500/20'
                        : 'text-muted-foreground bg-muted-foreground/10 border border-muted-foreground/20'
                    }`}
                  >
                    {provider.status}
                  </span>
                </div>
              ))}
            </div>
          </div>

          <div className="bg-card rounded-lg border border-border p-6 shadow-sm">
            <h2 className="text-sm font-semibold text-foreground mb-2">
              {t('admin.ai.recentRequests')}
            </h2>
            <div className="p-4 rounded-lg bg-muted border border-border/50 flex flex-col items-center justify-center text-center">
              <Activity className="h-6 w-6 text-muted-foreground mb-2" />
              <p className="text-sm text-muted-foreground">
                {t('admin.ai.comingSoon')}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
