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;
}

export const AdminStandards: React.FC<AdminStandardsProps> = ({ apiKey, provider, model, endpoint }) => {
  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);

  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(
        { 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;

      await fetch('/api/standards', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(parsed)
      });
      
      setGeneratedJson('');
      setStandardName('');
      fetchStandards(selectedCategory);
    } catch (e) {
      setJsonError("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>;

  return (
    <div className="animate-fade-in space-y-8">
      {/* Selector */}
      <div className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 p-5">
        <label className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Selecione a Categoria de Material</label>
        <select 
          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 className="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-1">Nome exato da Norma</label>
                <input 
                  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 || !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>

              {!apiKey && (
                <p className="text-red-500 text-xs">Configure a Chave da API no painel inicial 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 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
                    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>
                    <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>
  );
};
