'use client';

import { useState, useEffect } from 'react';

interface Attribute {
  key: string;
  type: string;
  required: boolean;
  array: boolean;
  size?: number;
}

interface CollectionInfo {
  id: string;
  name?: string;
  attributes?: Attribute[];
  totalAttributes?: number;
  status: string;
  error?: string;
}

interface Analysis {
  required: string[];
  existing: string[];
  missing: string[];
  hasAllRequired: boolean;
}

interface ApiResponse {
  success: boolean;
  collections: Record<string, CollectionInfo>;
  analysis: Record<string, Analysis>;
  timestamp: string;
  error?: string;
  details?: string;
}

export default function VerificarAtributos() {
  const [data, setData] = useState<ApiResponse | null>(null);
  const [loading, setLoading] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    try {
      const response = await fetch('/api/verificar-atributos');
      const result = await response.json();
      setData(result);
    } catch (error) {
      console.error('Erro ao buscar dados:', error);
    } finally {
      setLoading(false);
    }
  };

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

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'success': return 'text-green-600';
      case 'error': return 'text-red-600';
      default: return 'text-gray-600';
    }
  };

  const getAnalysisColor = (hasAllRequired: boolean) => {
    return hasAllRequired ? 'text-green-600' : 'text-red-600';
  };

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 p-8">
        <div className="max-w-6xl mx-auto">
          <h1 className="text-3xl font-bold text-gray-900 mb-8">Verificação de Atributos</h1>
          <div className="text-center py-8">
            <div className="text-lg text-gray-600">Carregando informações das collections...</div>
          </div>
        </div>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="min-h-screen bg-gray-50 p-8">
        <div className="max-w-6xl mx-auto">
          <h1 className="text-3xl font-bold text-gray-900 mb-8">Verificação de Atributos</h1>
          <div className="text-center py-8">
            <div className="text-lg text-red-600">Erro ao carregar dados</div>
            <button 
              onClick={fetchData}
              className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
            >
              Tentar Novamente
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-6xl mx-auto">
        <div className="flex justify-between items-center mb-8">
          <h1 className="text-3xl font-bold text-gray-900">Verificação de Atributos</h1>
          <button 
            onClick={fetchData}
            className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            Atualizar
          </button>
        </div>

        {!data.success && (
          <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-6">
            <strong>Erro:</strong> {data.error}
            {data.details && <div className="mt-2"><strong>Detalhes:</strong> {data.details}</div>}
          </div>
        )}

        {/* Resumo da Análise */}
        {data.analysis && (
          <div className="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">📊 Resumo da Análise</h2>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {Object.entries(data.analysis).map(([collectionName, analysis]) => (
                <div key={collectionName} className="border rounded-lg p-4">
                  <h3 className="font-semibold text-lg mb-2">{collectionName}</h3>
                  <div className={`text-sm font-medium mb-2 ${getAnalysisColor(analysis.hasAllRequired)}`}>
                    {analysis.hasAllRequired ? '✅ Todos os atributos configurados' : '❌ Atributos faltando'}
                  </div>
                  
                  {analysis.existing.length > 0 && (
                    <div className="mb-2">
                      <div className="text-sm font-medium text-green-600">Existentes:</div>
                      <div className="text-sm text-gray-600">{analysis.existing.join(', ')}</div>
                    </div>
                  )}
                  
                  {analysis.missing.length > 0 && (
                    <div className="mb-2">
                      <div className="text-sm font-medium text-red-600">Faltando:</div>
                      <div className="text-sm text-gray-600">{analysis.missing.join(', ')}</div>
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>
        )}

        {/* Detalhes das Collections */}
        <div className="space-y-6">
          {Object.entries(data.collections).map(([collectionName, info]) => (
            <div key={collectionName} className="bg-white rounded-lg shadow-md p-6">
              <div className="flex justify-between items-start mb-4">
                <h2 className="text-xl font-semibold text-gray-900">{collectionName}</h2>
                <span className={`text-sm font-medium ${getStatusColor(info.status)}`}>
                  {info.status === 'success' ? '✅ Conectado' : '❌ Erro'}
                </span>
              </div>

              <div className="text-sm text-gray-600 mb-4">
                <strong>ID:</strong> {info.id}
              </div>

              {info.status === 'error' ? (
                <div className="bg-red-50 border border-red-200 rounded p-4">
                  <div className="text-red-700">
                    <strong>Erro:</strong> {info.error}
                  </div>
                </div>
              ) : (
                <div>
                  <div className="mb-4">
                    <strong>Nome:</strong> {info.name} | 
                    <strong> Total de Atributos:</strong> {info.totalAttributes}
                  </div>

                  {info.attributes && info.attributes.length > 0 ? (
                    <div className="overflow-x-auto">
                      <table className="min-w-full table-auto border-collapse border border-gray-300">
                        <thead>
                          <tr className="bg-gray-100">
                            <th className="border border-gray-300 px-4 py-2 text-left">Atributo</th>
                            <th className="border border-gray-300 px-4 py-2 text-left">Tipo</th>
                            <th className="border border-gray-300 px-4 py-2 text-left">Obrigatório</th>
                            <th className="border border-gray-300 px-4 py-2 text-left">Array</th>
                            <th className="border border-gray-300 px-4 py-2 text-left">Tamanho</th>
                          </tr>
                        </thead>
                        <tbody>
                          {info.attributes.map((attr, index) => (
                            <tr key={index} className={index % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
                              <td className="border border-gray-300 px-4 py-2 font-medium">{attr.key}</td>
                              <td className="border border-gray-300 px-4 py-2">{attr.type}</td>
                              <td className="border border-gray-300 px-4 py-2">
                                {attr.required ? '✅ Sim' : '❌ Não'}
                              </td>
                              <td className="border border-gray-300 px-4 py-2">
                                {attr.array ? '✅ Sim' : '❌ Não'}
                              </td>
                              <td className="border border-gray-300 px-4 py-2">{attr.size || 'N/A'}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  ) : (
                    <div className="text-gray-500 italic">Nenhum atributo encontrado</div>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>

        <div className="mt-8 text-sm text-gray-500 text-center">
          Última atualização: {new Date(data.timestamp).toLocaleString('pt-BR')}
        </div>
      </div>
    </div>
  );
}