import React, { useEffect, useState, useMemo } from 'react';
import { prafrotService } from '../services/prafrotService';
import ExcelTable from '../components/ExcelTable';
import { Plus, Search, Settings, Save, X, Edit, Trash2 } from 'lucide-react';
import { 
  Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogDescription 
} from "@/components/ui/dialog";

// --- Components Styled ---
const SidebarItem = ({ active, label, onClick }) => (
  <button
    onClick={onClick}
    className={`w-full text-left px-4 py-3 text-sm font-medium transition-colors border-l-2 ${
      active 
        ? 'bg-orange-50 dark:bg-orange-500/10 text-orange-600 dark:text-orange-500 border-orange-500' 
        : 'text-slate-600 dark:text-slate-400 hover:bg-slate-50 dark:hover:bg-[#2a2a2a] border-transparent'
    }`}
  >
    {label}
  </button>
);

const DarkButton = ({ children, variant = 'primary', className = '', ...props }) => {
  const baseClass = "px-4 py-2 rounded-lg font-bold text-sm transition-all shadow-lg active:scale-95 flex items-center justify-center gap-2";
  const variants = {
    primary: "bg-orange-600 hover:bg-orange-500 text-white shadow-orange-500/10",
    secondary: "bg-slate-100 dark:bg-[#2a2a2a] hover:bg-slate-200 dark:hover:bg-[#333] text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-[#333]",
    ghost: "bg-transparent hover:bg-slate-100 dark:hover:bg-[#2a2a2a] text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-white",
    danger: "bg-red-500/10 hover:bg-red-500/20 text-red-600 dark:text-red-500 border border-red-500/20"
  };
  
  return (
    <button className={`${baseClass} ${variants[variant]} ${className}`} {...props}>
      {children}
    </button>
  );
};

const DarkInput = ({ label, ...props }) => (
  <div className="space-y-2">
    {label && <label className="text-[11px] uppercase font-bold text-slate-500 dark:text-slate-400 tracking-wider ml-1 block">{label}</label>}
    <input 
      className="w-full bg-slate-50 dark:bg-[#141414] border border-slate-200 dark:border-[#333] rounded-lg px-3 py-2.5 text-sm text-slate-700 dark:text-slate-200 focus:outline-none focus:border-orange-500 focus:ring-1 focus:ring-orange-500 transition-all placeholder:text-slate-400 dark:placeholder:text-slate-700"
      {...props}
    />
  </div>
);

export default function ConfigView() {
  const [configOptions, setConfigOptions] = useState({});
  const [selectedRoute, setSelectedRoute] = useState(null);
  const [items, setItems] = useState([]);
  const [loadingItems, setLoadingItems] = useState(false);
  
  const [searchTerm, setSearchTerm] = useState('');
  
  // Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [editingItem, setEditingItem] = useState(null);
  const [formData, setFormData] = useState({});

  // Fetch Config Options on Mount
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const data = await prafrotService.getListasConfig();
        setConfigOptions(data);
        
        // Select first option by default
        const keys = Object.keys(data);
        if (keys.length > 0) {
          setSelectedRoute(data[keys[0]].rota);
        }
      } catch (error) {
        console.error("Error loading config options:", error);
      }
    };
    loadConfig();
  }, []);

  // Fetch Items when Selected Route changes
  useEffect(() => {
    if (!selectedRoute) return;

    const loadItems = async () => {
      setLoadingItems(true);
      try {
        const data = await prafrotService.getListasByRoute(selectedRoute);
        // Ensure data is array
        const list = Array.isArray(data) ? data : (data.results || []); 
        setItems(list);
      } catch (error) {
        console.error(`Error loading items for ${selectedRoute}:`, error);
        setItems([]);
      } finally {
        setLoadingItems(false);
      }
    };

    loadItems();
    setSearchTerm('');
  }, [selectedRoute]);

  // Derived columns from first item
  const columns = useMemo(() => {
    if (!items || items.length === 0) return [];
    
    const firstItem = items[0];
    const keys = Object.keys(firstItem);
    
    return keys
      .filter(key => {
        const lowerKey = key.toLowerCase();
        // Hide ID, created_at, updated_at, deleted_at, active
        return !lowerKey.startsWith('id') && !['created_at', 'updated_at', 'deleted_at'].includes(lowerKey);
      })
      .map(key => ({
        header: key.toUpperCase().replace(/_/g, ' '),
        field: key,
        width: '200px'
      }));
  }, [items]);

  const filteredItems = useMemo(() => {
    if (!items) return [];
    if (!searchTerm) return items;
    const lower = searchTerm.toLowerCase();
    return items.filter(item => 
      Object.values(item).some(val => 
        String(val).toLowerCase().includes(lower)
      )
    );
  }, [items, searchTerm]);

  // Actions
  const handleOpenModal = (item = null) => {
    if (item) {
      setEditingItem(item);
      setFormData({ ...item });
    } else {
      setEditingItem(null);
      const emptyState = {};
      if (items.length > 0) {
         Object.keys(items[0]).forEach(k => emptyState[k] = '');
      } else {
         // Fallback default fields
         emptyState.label = '';
         emptyState.valor = '';
      }
      setFormData(emptyState);
    }
    setIsModalOpen(true);
  };

  const handleSave = async (e) => {
    e.preventDefault();
    if (!selectedRoute) return;

    try {
      // Create payload sending info as 'valor'
      // We extract all non-ID fields. If there's only one, we map it to 'valor'.
      // If there are multiple, we prioritize fields already named 'valor' or 'value'.
      const payload = {};
      const nonIdKeys = Object.keys(formData).filter(key => {
        const lowerKey = key.toLowerCase();
        return !lowerKey.startsWith('id') && !['created_at', 'updated_at', 'deleted_at'].includes(lowerKey);
      });

      if (nonIdKeys.length === 1) {
        payload.valor = formData[nonIdKeys[0]];
      } else if (nonIdKeys.length > 1) {
        // If multiple, send all but ensure 'valor' is present if 'value' was used
        nonIdKeys.forEach(k => {
          if (k === 'value') payload.valor = formData[k];
          else payload[k] = formData[k];
        });
        if (formData.valor) payload.valor = formData.valor;
      } else {
        // Fallback for empty schema
        payload.label = formData.label;
        payload.valor = formData.valor || formData.value;
      }

      if (editingItem) {
        const idKey = Object.keys(editingItem).find(k => k.toLowerCase().startsWith('id'));
        const idVal = editingItem[idKey];
        
        if (!idVal) {
          alert("Não foi possível identificar o ID deste item.");
          return;
        }

        await prafrotService.updateLista(selectedRoute, idVal, payload);
      } else {
        await prafrotService.createLista(selectedRoute, payload);
      }
      
      const data = await prafrotService.getListasByRoute(selectedRoute);
      setItems(Array.isArray(data) ? data : (data.results || []));
      setIsModalOpen(false);
    } catch (error) {
      console.error("Error saving:", error);
      alert("Erro ao salvar. Verifique o console.");
    }
  };

  const handleDelete = async (item) => {
      if (!window.confirm("Tem certeza que deseja excluir este item?")) return;

      const idKey = Object.keys(item).find(k => k.toLowerCase().startsWith('id'));
      const idVal = item[idKey];

      if (!idVal) {
        alert("Não foi possível identificar o ID deste item para exclusão.");
        return;
      }

      try {
        await prafrotService.deleteLista(selectedRoute, idVal);
        
        // Refresh list
        const data = await prafrotService.getListasByRoute(selectedRoute);
        setItems(Array.isArray(data) ? data : (data.results || []));
      } catch (error) {
        console.error("Erro ao excluir:", error);
        alert("Erro ao excluir o item. Verifique o console.");
      }
  };

  const selectedLabel = configOptions[selectedRoute]?.label || selectedRoute;

  return (
    <div className="flex h-screen bg-slate-50 dark:bg-[#0f0f0f] overflow-hidden">
        {/* Sidebar */}
        <div className="w-64 bg-white dark:bg-[#141414] border-r border-slate-200 dark:border-[#2a2a2a] flex flex-col">
            <div className="p-4 border-b border-slate-200 dark:border-[#2a2a2a]">
                <h2 className="text-lg font-bold text-slate-800 dark:text-white flex items-center gap-2">
                    <Settings className="text-orange-500" size={20} />
                    Configurações
                </h2>
                <p className="text-xs text-slate-500 mt-1">Gerencie as listas do sistema</p>
            </div>
            <div className="flex-1 overflow-y-auto py-2 custom-scrollbar">
                {Object.entries(configOptions).map(([key, opt]) => (
                    <SidebarItem 
                        key={key}
                        active={selectedRoute === opt.rota}
                        label={opt.label}
                        onClick={() => setSelectedRoute(opt.rota)}
                    />
                ))}
            </div>
        </div>

        {/* Main Content */}
        <div className="flex-1 flex flex-col min-w-0">
            {/* Header */}
            <div className="bg-white dark:bg-[#141414] border-b border-slate-200 dark:border-[#2a2a2a] px-8 py-5 flex justify-between items-center">
                <div>
                   <h1 className="text-2xl font-bold text-slate-800 dark:text-white tracking-tight">{selectedLabel}</h1>
                   <p className="text-slate-500 text-sm">Gerenciamento de opções para {selectedLabel?.toLowerCase()}</p>
                </div>
                <div className="flex items-center gap-3">
                    <div className="relative">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
                        <input 
                          className="bg-slate-50 dark:bg-[#1c1c1c] border border-slate-200 dark:border-[#2a2a2a] text-slate-700 dark:text-slate-200 pl-10 pr-4 py-2 rounded-lg text-sm focus:outline-none focus:border-orange-500 w-64"
                          placeholder="Pesquisar..." 
                          value={searchTerm}
                          onChange={e => setSearchTerm(e.target.value)}
                        />
                    </div>
                    <DarkButton onClick={() => handleOpenModal()}>
                        <Plus size={18} /> Novo Item
                    </DarkButton>
                </div>
            </div>

            {/* Table */}
            <div className="flex-1 p-8 overflow-hidden">
                 <div className="h-full bg-white dark:bg-[#141414] rounded-xl shadow-sm border border-slate-200 dark:border-[#2a2a2a] overflow-hidden flex flex-col">
                    {loadingItems ? (
                        <div className="flex-1 flex items-center justify-center text-slate-500">
                            Carregando...
                        </div>
                    ) : (
                        <ExcelTable 
                           data={filteredItems}
                           columns={columns}
                           loading={loadingItems}
                           onEdit={handleOpenModal}
                           onDelete={handleDelete} // Optional
                           // Fallback ID key logic usually generic in ExcelTable or pass rowKey
                           rowKey={(row) => {
                               // Try to find the primary key dynamically
                               const idKey = Object.keys(row).find(k => k.toLowerCase().startsWith('id'));
                               return idKey ? row[idKey] : Math.random();
                           }}
                        />
                    )}
                 </div>
            </div>
        </div>

        {/* Modal */}
        <Dialog open={isModalOpen} onOpenChange={setIsModalOpen}>
            <DialogContent className="max-w-2xl bg-white dark:bg-[#1c1c1c] border-slate-200 dark:border-[#2a2a2a] text-slate-700 dark:text-slate-200">
                <DialogHeader className="border-b border-slate-200 dark:border-[#2a2a2a] pb-4">
                    <DialogTitle className="text-slate-800 dark:text-white">
                        {editingItem ? `Editar ${selectedLabel}` : `Novo Item em ${selectedLabel}`}
                    </DialogTitle>
                </DialogHeader>
                
                <form onSubmit={handleSave} className="py-4 grid grid-cols-1 gap-6 max-h-[60vh] overflow-y-auto custom-scrollbar">
                    {/* Dynamic Form Generation */}
                    {Object.keys(formData).map(key => {
                        // Hide ID fields completely from form
                        const isId = key.toLowerCase().startsWith('id') || key === 'created_at' || key === 'updated_at';
                        if (isId) return null;
                        
                        return (
                            <DarkInput 
                                key={key}
                                label={key.replace(/_/g, ' ')}
                                value={formData[key] || ''}
                                onChange={e => setFormData({...formData, [key]: e.target.value})}
                            />
                        );
                    })}
                     {/* Fallback if formData is empty (new item with unknown schema) */}
                     {Object.keys(formData).length === 0 && (
                         <div className="text-center text-slate-500 p-4">
                            Não é possível criar um item sem conhecer a estrutura. Adicione a lógica de campos manuais se necessário.
                            (Normalmente, campos seriam: Nome, Descrição, etc.)
                            <div className="mt-4 space-y-2">
                                <DarkInput 
                                    label="Label / Nome"
                                    value={formData['label'] || ''}
                                    onChange={e => setFormData({...formData, label: e.target.value})}
                                />
                                 <DarkInput 
                                     label="Valor / Código"
                                     value={formData['valor'] || ''}
                                     onChange={e => setFormData({...formData, valor: e.target.value})}
                                 />
                            </div>
                         </div>
                     )}
                </form>

                <DialogFooter className="border-t border-slate-200 dark:border-[#2a2a2a] pt-4">
                    <DarkButton variant="ghost" onClick={() => setIsModalOpen(false)}>Cancelar</DarkButton>
                    <DarkButton onClick={handleSave}>
                        <Save size={16} /> Salvar
                    </DarkButton>
                </DialogFooter>
            </DialogContent>
        </Dialog>
    </div>
  );
}



