import React, { useState, useEffect } from 'react';
import type { Category } from './AdminCategories';
import { buildStandardWithAI } from '../services/aiService';
import type { AIProvider } from '../types/providers';

interface AdminStandardsProps {
  apiKey: string;
  provider: AIProvider;
  model: string;
  endpoint?: string;
  adminApiKey: string;
  adminModel: string;
  onAdminConfigSave: (key: string, model: string) => void;
}

export const AdminStandards: React.FC<AdminStandardsProps> = ({ apiKey, provider, model, endpoint, adminApiKey, adminModel, onAdminConfigSave }) => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('');
  const [standards, setStandards] = useState<any[]>([]);
  const [isLoadingCats, setIsLoadingCats] = useState(true);
  
  const [isGenerating, setIsGenerating] = useState(false);
  const [standardName, setStandardName] = useState('');
  const [generatedJson, setGeneratedJson] = useState('');
  const [jsonError, setJsonError] = useState<string | null>(null);

  const [localAdminKey, setLocalAdminKey] = useState(adminApiKey);
  const [localAdminModel, setLocalAdminModel] = useState(adminModel);

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

  useEffect(() => {
    if (selectedCategory) {
      fetchStandards(selectedCategory);
    } else {
      setStandards([]);
    }
  }, [selectedCategory]);

  const fetchCategories = async () => {
    try {
      const res = await fetch('/api/categories');
      const data = await res.json();
      setCategories(data);
      if (data.length > 0) setSelectedCategory(data[0].id);
    } catch (e) {
      console.error(e);
    } finally {
      setIsLoadingCats(false);
    }
  };

  const fetchStandards = async (catId: string) => {
    try {
      const res = await fetch(`/api/standards?categoryId=${catId}`);
      const data = await res.json();
      setStandards(data);
    } catch (e) {
      console.error(e);
    }
  };

  const handleGenerate = async () => {
    if (!standardName || !selectedCategory) return;
    
    const cat = categories.find(c => c.id === selectedCategory);
    if (!cat) return;

    setIsGenerating(true);
    setJsonError(null);
    try {
      const jsonObj = await buildStandardWithAI(
        // Use the admin config if provided, otherwise fallback to the global one
        localAdminKey ? { provider: 'openrouter', apiKey: localAdminKey, model: localAdminModel } : { provider, apiKey, model, endpoint },
        standardName,
        cat.description
      );
      setGeneratedJson(JSON.stringify(jsonObj, null, 2));
    } catch (e: any) {
      setJsonError(e.message || "Erro ao gerar a norma.");
    } finally {
      setIsGenerating(false);
    }
  };

  const handleSave = async () => {
    if (!generatedJson) return;
    
    try {
      const parsed = JSON.parse(generatedJson);
      parsed.categoria_id = selectedCategory;

      const res = await fetch('/api/standards', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(parsed)
      });
      
      if (!res.ok) {
        const errData = await res.json().catch(() => ({}));
        throw new Error(errData.error || `Erro do servidor: ${res.status}`);
      }
      
      setGeneratedJson('');
      setStandardName('');
      fetchStandards(selectedCategory);
    } catch (e: any) {
      setJsonError(e.message || "Erro ao salvar: JSON inválido ou falha na rede.");
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('Excluir esta norma? O app não poderá mais validar relatórios contra ela.')) return;
    try {
      await fetch(`/api/standards?id=${id}`, { method: 'DELETE' });
      fetchStandards(selectedCategory);
    } catch (e) {
      console.error(e);
    }
  };

  if (isLoadingCats) return <div className="p-8 text-center">Carregando categorias...</div>;

  const handleEdit = (s: any) => {
    setStandardName(s.codigo);
    setGeneratedJson(JSON.stringify(s, null, 2));
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  return (
    <div className="animate-fade-in space-y-8">
      {/* Admin Engine Config */}
      <div className="bg-slate-50 dark:bg-slate-800/50 rounded-xl border border-slate-200 dark:border-slate-700 p-5">
        <h3 className="text-sm font-bold text-slate-700 dark:text-slate-300 mb-3">Motor de Engenharia IA (Opcional)</h3>
        <p className="text-xs text-slate-500 mb-4">
          Para criar normas perfeitamente estruturadas, recomendamos utilizar um modelo avançado como Claude 3.5 Sonnet ou GPT-4o via OpenRouter, separado do modelo de leitura rápida usado na página inicial.
        </p>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-end">
          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">OpenRouter API Key (Admin)</label>
            <input 
              type="password"
              value={localAdminKey}
              onChange={e => setLocalAdminKey(e.target.value)}
              placeholder="sk-or-v1-..."
              className="w-full rounded-md border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-3 py-1.5 text-sm"
            />
          </div>
          <div>
            <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-1">Modelo de Alta Precisão</label>
            <input 
              type="text"
              value={localAdminModel}
              onChange={e => setLocalAdminModel(e.target.value)}
              placeholder="ex: anthropic/claude-3.5-sonnet"
              className="w-full rounded-md border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-3 py-1.5 text-sm font-mono"
            />
          </div>
        </div>
        <button 
          onClick={() => onAdminConfigSave(localAdminKey, localAdminModel)}
          className="mt-3 px-4 py-1.5 bg-slate-200 dark:bg-slate-700 hover:bg-slate-300 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200 text-xs font-bold rounded transition-all"
        >
          Salvar Cérebro Admin na Memória
        </button>
      </div>

      {/* Selector */}
      <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
        <label htmlFor="category-select" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Selecione a Categoria de Material</label>
        <select 
          id="category-select"
          title="Selecione a Categoria"
          value={selectedCategory} 
          onChange={e => setSelectedCategory(e.target.value)}
          className="w-full rounded-lg border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-4 py-2 text-slate-900 dark:text-white"
        >
          {categories.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
        </select>
      </div>

      {selectedCategory && (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          
          {/* Builder */}
          <div className="bg-gradient-to-br from-indigo-50 to-blue-50 dark:from-slate-800 dark:to-slate-900 rounded-xl shadow-sm border border-indigo-100 dark:border-slate-700 p-5">
            <h3 className="text-lg font-bold text-indigo-900 dark:text-indigo-300 mb-4 flex items-center gap-2">
              <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
              Construtor Assistido por IA
            </h3>
            
            <div className="space-y-4">
              <div>
                <label htmlFor="standard-name" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Nome exato da Norma</label>
                <input 
                  id="standard-name"
                  type="text" 
                  value={standardName}
                  onChange={e => setStandardName(e.target.value)}
                  placeholder="Ex: ASTM A572 Grau 50"
                  className="w-full rounded-lg border-slate-300 dark:border-slate-600 bg-white dark:bg-slate-700 px-4 py-2 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-indigo-500"
                />
              </div>

              <button 
                onClick={handleGenerate}
                disabled={isGenerating || !standardName || !(localAdminKey || apiKey)}
                className="w-full bg-indigo-600 hover:bg-indigo-700 disabled:opacity-50 text-white font-bold py-2.5 rounded-lg transition-all"
              >
                {isGenerating ? 'Analisando e Extraindo Limites...' : 'Gerar Estrutura com IA'}
              </button>

              {!(localAdminKey || apiKey) && (
                <p className="text-red-500 text-xs">Configure uma Chave de IA (Admin ou Global) primeiro.</p>
              )}

              {jsonError && (
                <div className="p-3 bg-red-100 text-red-700 rounded-lg text-sm">{jsonError}</div>
              )}

              {generatedJson && (
                <div className="mt-6 animate-fade-in">
                  <label htmlFor="json-editor" className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1 flex justify-between">
                    <span>Valide e corrija os parâmetros abaixo:</span>
                    <span className="text-xs bg-yellow-100 text-yellow-800 px-2 py-0.5 rounded">Human-in-the-Loop</span>
                  </label>
                  <textarea
                    id="json-editor"
                    title="Editor JSON da Norma"
                    placeholder="O JSON gerado pela IA aparecerá aqui..."
                    value={generatedJson}
                    onChange={e => setGeneratedJson(e.target.value)}
                    className="w-full h-80 font-mono text-sm rounded-lg border-slate-300 dark:border-slate-600 bg-slate-50 dark:bg-slate-950 p-4 text-slate-800 dark:text-slate-300 outline-none focus:ring-2 focus:ring-indigo-500"
                  />
                  <button 
                    onClick={handleSave}
                    className="mt-4 w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 rounded-lg transition-all flex justify-center items-center gap-2"
                  >
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" /></svg>
                    Validar e Salvar Norma na Base
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* List */}
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
            <h3 className="text-lg font-bold text-slate-800 dark:text-slate-200 mb-4">Normas Ativas</h3>
            
            <div className="space-y-3">
              {standards.length === 0 ? (
                <p className="text-sm text-slate-500">Nenhuma norma cadastrada nesta categoria ainda.</p>
              ) : (
                standards.map(s => (
                  <div key={s.id} className="p-4 rounded-lg border border-slate-200 dark:border-slate-700 bg-slate-50 dark:bg-slate-800/50 flex justify-between items-start">
                    <div>
                      <h4 className="font-bold text-slate-800 dark:text-white">{s.codigo}</h4>
                      <p className="text-xs text-slate-500 dark:text-slate-400 mt-1">{s.produto_especifico}</p>
                      
                      <div className="mt-3 flex flex-wrap gap-2">
                        {Object.keys(s.parametros_controle || {}).map(grupo => (
                          <span key={grupo} className="text-[10px] uppercase font-bold bg-slate-200 dark:bg-slate-700 text-slate-600 dark:text-slate-300 px-2 py-1 rounded">
                            {grupo}: {Object.keys(s.parametros_controle[grupo] || {}).length} specs
                          </span>
                        ))}
                      </div>
                    </div>
                    <div className="flex gap-2">
                      <button 
                        onClick={() => handleEdit(s)}
                        className="text-indigo-500 hover:text-indigo-700 p-2"
                        title="Editar JSON"
                      >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" /></svg>
                      </button>
                      <button 
                        onClick={() => handleDelete(s.id)}
                        className="text-red-500 hover:text-red-700 p-2"
                        title="Excluir"
                      >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                      </button>
                    </div>
                  </div>
                ))
              )}
            </div>
          </div>

        </div>
      )}
    </div>
  );
};
