// @ts-nocheck
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, Trash2, Cpu, CheckCircle, XCircle } from 'lucide-react'
import Button from '@/components/common/Button'
import Input from '@/components/common/Input'
import Modal from '@/components/common/Modal'
import { supabase } from '@/lib/supabase'
import { toast } from '@/lib/toast'

export default function IntegracaoIATab() {
  const queryClient = useQueryClient()
  const [modalOpen, setModalOpen] = useState(false)
  const [formData, setFormData] = useState({
    provider: 'openai',
    api_key: '',
    modelo_padrao: 'gpt-4',
    ativo: false,
  })
  
  const { data: integracoes } = useQuery({
    queryKey: ['integracoes-ia'],
    queryFn: async () => {
      const { data, error } = await supabase
        .from('integracao_ia')
        .select('*')
        .order('created_at', { ascending: false })
      
      if (error) throw error
      return data
    },
  })
  
  const createMutation = useMutation({
    mutationFn: async (data: typeof formData) => {
      const { error } = await supabase
        .from('integracao_ia')
        .insert([{
          ...data,
          api_key_encriptada: data.api_key, // TODO: Encriptar
        } as any])
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['integracoes-ia'] })
      toast.success('Integração configurada')
      setModalOpen(false)
    },
  })
  
  const deleteMutation = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase
        .from('integracao_ia')
        .delete()
        .eq('id', id)
      
      if (error) throw error
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['integracoes-ia'] })
      toast.success('Integração removida')
    },
  })
  
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-semibold text-gray-900 dark:text-gray-100">Integrações com IA</h2>
          <p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
            Configure APIs de IA para processamento automático de documentos
          </p>
        </div>
        <Button onClick={() => setModalOpen(true)}>
          <Plus size={20} className="mr-2" />
          Nova Integração
        </Button>
      </div>
      
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {integracoes && integracoes.length > 0 ? (
          integracoes.map((integracao) => (
            <div key={integracao.id} className="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
              <div className="flex items-start justify-between mb-4">
                <div className="flex items-center gap-3">
                  <div className="p-2 bg-primary-100 dark:bg-blue-900 rounded-lg">
                    <Cpu className="text-primary dark:text-blue-400" size={24} />
                  </div>
                  <div>
                    <h3 className="font-semibold text-gray-900 dark:text-gray-100 capitalize">
                      {integracao.provider}
                    </h3>
                    <p className="text-sm text-gray-600 dark:text-gray-400">{integracao.modelo_padrao}</p>
                  </div>
                </div>
                {integracao.ativo ? (
                  <CheckCircle size={20} className="text-green-500 dark:text-green-400" />
                ) : (
                  <XCircle size={20} className="text-gray-400 dark:text-gray-500" />
                )}
              </div>
              
              <div className="space-y-2 text-sm">
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Status:</span>
                  <span className={integracao.ativo ? 'text-green-600 dark:text-green-400' : 'text-gray-600 dark:text-gray-400'}>
                    {integracao.ativo ? 'Ativo' : 'Inativo'}
                  </span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600 dark:text-gray-400">Tokens máx:</span>
                  <span className="text-gray-900 dark:text-gray-100">{integracao.maximo_tokens}</span>
                </div>
              </div>
              
              <div className="flex gap-2 mt-4">
                <button className="flex-1 text-blue-600 dark:text-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900 py-2 rounded transition-colors">
                  <Edit size={16} className="inline mr-1" />
                  Editar
                </button>
                <button 
                  onClick={() => deleteMutation.mutate(integracao.id)}
                  className="flex-1 text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900 py-2 rounded transition-colors"
                >
                  <Trash2 size={16} className="inline mr-1" />
                  Remover
                </button>
              </div>
            </div>
          ))
        ) : (
          <div className="col-span-3 text-center py-12 text-gray-500 dark:text-gray-400">
            Nenhuma integração configurada
          </div>
        )}
      </div>
      
      <Modal
        isOpen={modalOpen}
        onClose={() => setModalOpen(false)}
        title="Nova Integração IA"
      >
        <div className="space-y-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
              Provider
            </label>
            <select
              value={formData.provider}
              onChange={(e) => setFormData(prev => ({ ...prev, provider: e.target.value }))}
              className="input-field dark:bg-gray-700 dark:border-gray-600 dark:text-gray-100"
            >
              <option value="openai">OpenAI</option>
              <option value="claude">Claude (Anthropic)</option>
              <option value="gemini">Gemini (Google)</option>
            </select>
          </div>
          
          <Input
            label="API Key"
            type="password"
            value={formData.api_key}
            onChange={(e) => setFormData(prev => ({ ...prev, api_key: e.target.value }))}
            placeholder="sk-..."
            required
          />
          
          <Input
            label="Modelo Padrão"
            value={formData.modelo_padrao}
            onChange={(e) => setFormData(prev => ({ ...prev, modelo_padrao: e.target.value }))}
            placeholder="gpt-4"
            required
          />
          
          <label className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={formData.ativo}
              onChange={(e) => setFormData(prev => ({ ...prev, ativo: e.target.checked }))}
              className="text-primary focus:ring-primary"
            />
            <span className="text-sm font-medium text-gray-700 dark:text-gray-300">Ativar integração</span>
          </label>
          
          <div className="flex justify-end gap-3 pt-4">
            <Button variant="outline" onClick={() => setModalOpen(false)}>
              Cancelar
            </Button>
            <Button
              onClick={() => createMutation.mutate(formData)}
              isLoading={createMutation.isPending}
            >
              Criar
            </Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}


