import React, { useState, useEffect } from 'react';
import axios from 'axios';

const API_BASE = "http://localhost:5000/api";

export default function Dashboard() {
    const [tables, setTables] = useState({});
    const [activeTable, setActiveTable] = useState('');
    const [searchQuery, setSearchQuery] = useState('');
    const [counts, setCounts] = useState({});
    const [loading, setLoading] = useState(true);

    // This constant defines tables that should be hidden from the UI
    const HIDDEN_TABLES = ['user', 'users'];

    const isVisibleTable = (tableName) => !HIDDEN_TABLES.includes(tableName.toLowerCase());

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

    const fetchInitialData = async () => {
        try {
            const res = await axios.get(`${API_BASE}/data/all`);
            setTables(res.data);
            
            // Filter out hidden tables when setting the active table
            const visibleTables = Object.keys(res.data).filter(isVisibleTable);
            setActiveTable(visibleTables[0]);
            
            visibleTables.forEach(tableName => fetchCount(tableName));
            setLoading(false);
        } catch (err) {
            setLoading(false);
        }
    };

    const fetchCount = async (tableName) => {
        try {
            const res = await axios.get(`${API_BASE}/meta/count/${tableName}`);
            setCounts(prev => ({ ...prev, [tableName]: res.data.count }));
        } catch (err) { }
    };

    const handleSearch = async () => {
        if (!searchQuery) return fetchInitialData();
        try {
            const res = await axios.get(`${API_BASE}/search/${activeTable}?q=${searchQuery}`);
            setTables(prev => ({ ...prev, [activeTable]: res.data }));
        } catch (err) { }
    };

    if (loading) return (
        <div className="min-h-screen flex items-center justify-center bg-slate-50">
            <div className="flex flex-col items-center gap-3">
                <div className="w-8 h-8 border-4 border-indigo-600 border-t-transparent rounded-full animate-spin"></div>
                <span className="text-slate-500 text-xs font-bold uppercase tracking-widest">Loading Dashboard...</span>
            </div>
        </div>
    );

    return (
        <div className="min-h-screen bg-slate-50 p-6 lg:p-12">
            <div className="max-w-7xl mx-auto space-y-8">
                <header className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-3xl font-extrabold text-slate-900 tracking-tight">Executive Dashboard</h1>
                        <p className="text-slate-500 text-sm mt-1">Real-time oversight of enterprise operations.</p>
                    </div>
                    <div className="flex items-center gap-2 px-4 py-2 bg-emerald-50 text-emerald-700 rounded-full border border-emerald-100 text-xs font-bold uppercase tracking-wide">
                        <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
                        System Operational
                    </div>
                </header>

                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6">
                    {Object.keys(tables).filter(isVisibleTable).map((tableName) => (
                        <button 
                            key={tableName} 
                            onClick={() => { setActiveTable(tableName); setSearchQuery(''); }}
                            className={`group p-6 rounded-3xl border text-left transition-all duration-300 ${activeTable === tableName ? 'bg-indigo-600 border-indigo-600 shadow-xl shadow-indigo-200' : 'bg-white border-slate-200 hover:shadow-lg hover:border-indigo-200'}`}
                        >
                            <p className={`text-[10px] font-black uppercase tracking-widest mb-2 ${activeTable === tableName ? 'text-indigo-200' : 'text-slate-400'}`}>
                                {tableName}
                            </p>
                            <h4 className={`text-4xl font-black ${activeTable === tableName ? 'text-white' : 'text-slate-900'}`}>
                                {counts[tableName] || 0}
                            </h4>
                        </button>
                    ))}
                </div>

                <div className="bg-white rounded-3xl border border-slate-200 shadow-sm overflow-hidden">
                    <div className="p-6 sm:px-8 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                        <h3 className="font-bold text-slate-900 uppercase tracking-wide text-sm">{activeTable} Ledger</h3>
                        <div className="flex items-center gap-2">
                            <input 
                                type="text" 
                                placeholder="Search records..."
                                className="bg-slate-50 border border-slate-200 text-sm px-4 py-2.5 rounded-xl w-full sm:w-64 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-400 outline-none transition-all"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                            />
                            <button onClick={handleSearch} className="px-6 py-2.5 bg-slate-900 hover:bg-black text-white text-sm font-bold rounded-xl transition-all">
                                Filter
                            </button>
                        </div>
                    </div>

                    <div className="overflow-x-auto">
                        <table className="w-full text-left">
                            <thead className="bg-slate-50 text-slate-500 text-[10px] uppercase font-black tracking-widest">
                                <tr>
                                    {tables[activeTable]?.[0] && Object.keys(tables[activeTable][0]).map(col => (
                                        <th key={col} className="px-8 py-5">{col.replace(/_/g, ' ')}</th>
                                    ))}
                                    <th className="px-8 py-5 text-right">Status</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-50">
                                {tables[activeTable]?.map((row, idx) => (
                                    <tr key={idx} className="hover:bg-indigo-50/30 transition-colors">
                                        {Object.values(row).map((val, i) => (
                                            <td key={i} className="px-8 py-5 text-sm font-medium text-slate-700">
                                                {val?.toString().includes('T00:00:00') ? new Date(val).toLocaleDateString() : val}
                                            </td>
                                        ))}
                                        <td className="px-8 py-5 text-right">
                                            <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-emerald-50 text-emerald-700 text-[10px] font-black uppercase">
                                                <span className="w-1.5 h-1.5 rounded-full bg-emerald-500"></span> Active
                                            </span>
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    );
}
