'use client';

import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Loader2, CheckCircle, XCircle, RefreshCw, Trash2, Database } from 'lucide-react';
import { cleanupAllOrphans } from '@/app/actions/notes';
import { useToast } from '@/components/ui/toast';

export default function SettingsPage() {
  const { addToast } = useToast();
  const [loading, setLoading] = useState(false);
  const [cleanupLoading, setCleanupLoading] = useState(false);
  const [status, setStatus] = useState<'idle' | 'success' | 'error'>('idle');
  const [result, setResult] = useState<any>(null);
  const [config, setConfig] = useState<any>(null);

  const checkConnection = async () => {
    setLoading(true);
    setStatus('idle');
    setResult(null);
    try {
      const res = await fetch('/api/ai/test');
      const data = await res.json();
      
      setConfig({
        provider: data.provider,
        status: res.ok ? 'connected' : 'disconnected'
      });

      if (res.ok) {
        setStatus('success');
        setResult(data);
      } else {
        setStatus('error');
        setResult(data);
      }
    } catch (error: any) {
      console.error(error);
      setStatus('error');
      setResult({ message: error.message, stack: error.stack });
    } finally {
      setLoading(false);
    }
  };

  const handleCleanup = async () => {
    setCleanupLoading(true);
    try {
      const result = await cleanupAllOrphans();
      if (result.success) {
        addToast(`Nettoyage terminé : ${result.count} tags supprimés`, 'success');
      }
    } catch (error) {
      console.error(error);
      addToast("Erreur lors du nettoyage", "error");
    } finally {
      setCleanupLoading(false);
    }
  };

  useEffect(() => {
    checkConnection();
  }, []);

  return (
    <div className="container mx-auto py-10 px-4 max-w-4xl space-y-8">
      <h1 className="text-3xl font-bold mb-8">Paramètres</h1>

      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <div>
              <CardTitle className="flex items-center gap-2">
                Diagnostic IA
                {status === 'success' && <CheckCircle className="text-green-500 w-5 h-5" />}
                {status === 'error' && <XCircle className="text-red-500 w-5 h-5" />}
              </CardTitle>
              <CardDescription>Vérifiez la connexion avec votre fournisseur d'intelligence artificielle.</CardDescription>
            </div>
            <Button variant="outline" size="sm" onClick={checkConnection} disabled={loading}>
              {loading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <RefreshCw className="w-4 h-4 mr-2" />}
              Tester la connexion
            </Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-6">
          
          {/* Configuration Actuelle */}
          <div className="grid grid-cols-2 gap-4">
            <div className="p-4 rounded-lg bg-secondary/50">
              <p className="text-sm font-medium text-muted-foreground mb-1">Provider Configuré</p>
              <p className="text-lg font-mono">{config?.provider || '...'}</p>
            </div>
            <div className="p-4 rounded-lg bg-secondary/50">
              <p className="text-sm font-medium text-muted-foreground mb-1">État API</p>
              <Badge variant={status === 'success' ? 'default' : 'destructive'}>
                {status === 'success' ? 'Opérationnel' : 'Erreur'}
              </Badge>
            </div>
          </div>

          {/* Résultat du Test */}
          {result && (
            <div className="space-y-2">
              <h3 className="text-sm font-medium">Détails du test :</h3>
              <div className={`p-4 rounded-md font-mono text-xs overflow-x-auto ${status === 'error' ? 'bg-red-50 text-red-900 border border-red-200' : 'bg-slate-950 text-slate-50'}`}>
                <pre>{JSON.stringify(result, null, 2)}</pre>
              </div>
              
              {status === 'error' && (
                <div className="text-sm text-red-600 mt-2">
                  <p className="font-bold">Conseil de dépannage :</p>
                  <ul className="list-disc list-inside mt-1">
                    <li>Vérifiez que Ollama tourne (<code>ollama list</code>)</li>
                    <li>Vérifiez l'URL (http://localhost:11434)</li>
                    <li>Vérifiez que le modèle (ex: granite4:latest) est bien téléchargé</li>
                    <li>Regardez le terminal du serveur Next.js pour plus de logs</li>
                  </ul>
                </div>
              )}
            </div>
          )}

        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Database className="w-5 h-5" />
            Maintenance
          </CardTitle>
          <CardDescription>Outils pour maintenir la santé de votre base de données.</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between p-4 border rounded-lg">
            <div>
              <h3 className="font-medium">Nettoyage des tags orphelins</h3>
              <p className="text-sm text-muted-foreground">Supprime les tags qui ne sont plus utilisés par aucune note.</p>
            </div>
            <Button variant="secondary" onClick={handleCleanup} disabled={cleanupLoading}>
              {cleanupLoading ? <Loader2 className="w-4 h-4 animate-spin mr-2" /> : <Trash2 className="w-4 h-4 mr-2" />}
              Nettoyer
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
