import { useEffect, useState } from 'react';
import { supabase } from '../lib/supabaseClient';
import { useAuth } from '../components/AuthContext';
import { tableNameStocks } from '../lib/const';
import { EntryForm } from '../components/EntryForm';
import { Pencil, Trash2, Copy as CopyIcon, Search, Plus, Filter, LayoutGrid, Clock, ShieldCheck, Activity } from 'lucide-react';
import type { BotState } from '../hooks/useWebSocket';
import { DEFAULT_BOT_STATE } from '../hooks/useWebSocket';

interface Entry {
    stock_instance_id: string;
    symbol: string;
    active: boolean;
    user_id: string;
    buy_price?: string;
    sell_price?: string;
    buy_time?: string;
    sell_time?: string;
    quantity?: string;
    filled_quantity?: string;
    notes?: string;
    status: string;
    is_crypto: boolean;
    is_real_trade: boolean;
    label?: string;
    entry_price?: string;
    gain_threshold_for_sell?: string;
    drop_threshold_for_buy?: string;
}

export const filterEntriesByTab = (entries: Entry[], activeTab: string) =>
    entries.filter((entry) => {
        switch (activeTab) {
            case 'paperActive':
                return !entry.is_real_trade && entry.active && entry.status !== 'sellCompleted';
            case 'paperCompleted':
                return !entry.is_real_trade && entry.status === 'sellCompleted';
            case 'realActive':
                return entry.is_real_trade && entry.active && entry.status !== 'sellCompleted';
            case 'realCompleted':
                return entry.is_real_trade && entry.status === 'sellCompleted';
            case 'inactive':
                return !entry.active;
            default:
                return false;
        }
    });

export const buildClonedEntryPayload = (entry: Entry, generatedId: string) => {
    const rest = { ...entry } as Record<string, unknown>;
    delete rest.stock_instance_id;
    delete rest.id;
    delete rest.created_at;
    delete rest.updated_at;

    return {
        ...rest,
        stock_instance_id: generatedId,
        active: false,
        status: 'active'
    };
};

interface EntriesTabProps {
  botState?: BotState;
}

const ENTRY_STATE_MAP = [
  { label: 'LOCKED', test: (entry: Entry) => entry.status?.toLowerCase().includes('lock') || entry.active },
  { label: 'BLOCKED', test: (entry: Entry) => ['blocked', 'cooldown', 'waiting'].some(term => entry.status?.toLowerCase().includes(term)) },
  { label: 'ORPHAN', test: (entry: Entry) => ['orphan', 'stale', 'reconcile'].some(term => entry.status?.toLowerCase().includes(term)) },
];

const deriveEntryState = (entry: Entry, botState: BotState): string => {
  const orderMatch = botState.orders.find(o => o.symbol === entry.symbol);
  const status = (entry.status || '').toLowerCase();
  const orderStatus = (orderMatch?.status || '').toLowerCase();

  if (ENTRY_STATE_MAP[0].test(entry)) return 'LOCKED';
  if (ENTRY_STATE_MAP[1].test(entry)) return 'BLOCKED';
  if (orderStatus.includes('pending') || orderStatus.includes('submitted') || status.includes('submitted')) return 'SUBMITTED';
  if (orderStatus.includes('filled') || orderStatus.includes('confirmed') || status.includes('filled') || status.includes('confirmed')) return 'CONFIRMED';
  if (ENTRY_STATE_MAP[2].test(entry)) return 'ORPHAN';
  return 'Unknown';
};

const NAV_TABS = [
    { id: "paperActive", label: "Paper Active", icon: <Activity size={14} /> },
    { id: "realActive", label: "Real Execution", icon: <ShieldCheck size={14} /> },
    { id: "paperCompleted", label: "Paper Archive", icon: <Clock size={14} /> },
    { id: "realCompleted", label: "Real Archive", icon: <ShieldCheck size={14} /> },
    { id: "inactive", label: "Suspended", icon: <Filter size={14} /> }
] as const;

const tabClass = (isActive: boolean) =>
    `px-6 py-3 rounded-[1.5rem] text-[10px] font-black uppercase tracking-widest transition-all flex items-center gap-3 whitespace-nowrap ${isActive ? "bg-white text-black shadow-xl" : "text-gray-500 hover:text-gray-300"}`;

export const EntriesTab = ({ botState = DEFAULT_BOT_STATE }: EntriesTabProps) => {
    const { user } = useAuth();
    const [entries, setEntries] = useState<Entry[]>([]);
    const [editingEntry, setEditingEntry] = useState<Entry | null>(null);
    const [activeTab, setActiveTab] = useState("paperActive");
    const [isAdding, setIsAdding] = useState(false);

    // Filter Logic
    const filteredEntries = filterEntriesByTab(entries, activeTab);

    const fetchEntries = async () => {
        if (!user) return;
        try {
            const { data, error } = await supabase
                .from(tableNameStocks)
                .select("*")
                .eq("user_id", user.id)
                .order("created_at", { ascending: false });

            if (error) throw error;
            setEntries(data || []);
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : String(err);
            console.error("Error fetching entries:", message);
        }
    };

    useEffect(() => {
        fetchEntries();
    }, [user]);

    const handleDelete = async (id: string) => {
        if (!confirm('⚠️ CRITICAL: Permanently delete this entry from neural watchlist?')) return;
        await supabase.from(tableNameStocks).delete().eq('stock_instance_id', id);
        fetchEntries();
    };

    const handleClone = async (entry: Entry) => {
        await supabase.from(tableNameStocks).insert([{
            ...buildClonedEntryPayload(entry, crypto.randomUUID())
        }]);
        fetchEntries();
    };

    const entryCards = filteredEntries.map((entry) => {
        const entryState = deriveEntryState(entry, botState);
        return (
            <div key={entry.stock_instance_id} className="group relative rounded-[2.5rem] p-1 transition-all duration-500 bg-white/[0.01] hover:bg-gradient-to-br hover:from-green-500/10 hover:to-transparent">
                <div className="bg-[#0a0b0d] border border-white/5 rounded-[2.4rem] p-8 h-full flex flex-col transition-all group-hover:border-white/10 group-hover:shadow-2xl">

                    {/* Card Top */}
                    <div className="flex items-start justify-between mb-8">
                        <div className="space-y-1">
                            <h4 className="text-2xl font-black text-white tracking-tight group-hover:text-green-400 transition-colors uppercase">{entry.symbol}</h4>
                            <div className="flex items-center gap-2">
                                            <span className={`px-2 py-0.5 rounded text-[9px] font-black tracking-widest uppercase ${entry.is_real_trade ? 'bg-blue-500/20 text-blue-400' : 'bg-purple-500/20 text-purple-400'}`}>
                                    {entry.is_real_trade ? 'REAL-UNIT' : 'PAPER-VOID'}
                                </span>
                                {entry.label && (
                                    <span className="px-2 py-0.5 bg-white/5 rounded text-[9px] font-black text-gray-500 uppercase tracking-widest border border-white/5">
                                        {entry.label}
                                    </span>
                                )}
                            </div>
                        </div>
                        <div className="flex gap-2 opacity-0 group-hover:opacity-100 transition-all translate-y-2 group-hover:translate-y-0">
                            <button onClick={() => setEditingEntry(entry)} className="p-3 bg-white/5 rounded-2xl text-gray-400 hover:text-white hover:bg-white/10 transition-all"><Pencil size={16} /></button>
                            <button onClick={() => handleClone(entry)} className="p-3 bg-white/5 rounded-2xl text-gray-400 hover:text-green-400 hover:bg-green-500/10 transition-all"><CopyIcon size={16} /></button>
                            <button onClick={() => handleDelete(entry.stock_instance_id)} className="p-3 bg-red-500/10 rounded-2xl text-red-500 hover:bg-red-500/20 transition-all"><Trash2 size={16} /></button>
                        </div>
                    </div>

                    {/* Metrics Grid */}
                    <div className="grid grid-cols-2 gap-4 mb-8">
                        <div className="bg-white/[0.02] p-5 rounded-3xl border border-white/5">
                            <span className="block text-[8px] text-gray-600 font-black uppercase tracking-[0.2em] mb-2">Entry Price</span>
                            <span className="text-xl font-black text-white font-mono">${entry.buy_price || '0.00'}</span>
                        </div>
                        <div className="bg-white/[0.02] p-5 rounded-3xl border border-white/5">
                            <span className="block text-[8px] text-gray-600 font-black uppercase tracking-[0.2em] mb-2">Target Exit</span>
                            <span className="text-xl font-black text-white font-mono">${entry.sell_price || '---'}</span>
                        </div>
                        <div className="bg-white/[0.02] p-4 rounded-3xl border border-white/5">
                            <span className="block text-[8px] text-gray-600 font-black uppercase tracking-[0.2em] mb-1">Quantity/Lot</span>
                            <span className="text-xs font-black text-gray-400 font-mono">{entry.quantity} UNITS</span>
                        </div>
                        <div className="bg-white/[0.02] p-4 rounded-3xl border border-white/5">
                            <span className="block text-[8px] text-gray-600 font-black uppercase tracking-[0.2em] mb-1">Status</span>
                            <span className={`text-[10px] font-black tracking-widest uppercase ${entry.active ? 'text-green-400 animate-pulse' : 'text-gray-600'}`}>
                                {entry.active ? 'SCANNING' : 'INACTIVE'}
                            </span>
                        </div>
                    </div>

                    <div className="entry-state-row mb-6">
                        <span className="text-[9px] text-gray-500 font-black uppercase tracking-[0.2em]">Entry State</span>
                        <span className={`entry-state-pill state-${entryState.toLowerCase().replace(/[^a-z]/g, '')}`}>
                            {entryState}
                        </span>
                    </div>

                    {/* Entry Notes/Context */}
                    <div className="flex-grow">
                        <span className="block text-[8px] text-gray-600 font-black uppercase tracking-[0.2em] mb-3">Neural Context</span>
                        <p className="text-[10px] font-bold text-gray-500 leading-relaxed uppercase italic">
                            {entry.notes || 'No manual notes injection provided for this asset cluster.'}
                        </p>
                    </div>

                    {/* ID Context */}
                    <div className="mt-8 pt-6 border-t border-white/5 flex items-center justify-between">
                        <div className="flex items-center gap-2">
                            <div className="w-6 h-6 rounded-full bg-white/5 flex items-center justify-center text-[10px] text-gray-600 font-black">
                                ID
                            </div>
                            <span className="text-[8px] text-gray-700 font-mono select-all truncate max-w-[150px]">{entry.stock_instance_id}</span>
                        </div>
                        <ShieldCheck size={14} className="text-gray-800" />
                    </div>
                </div>
            </div>
        );
    });

    const navTabs = NAV_TABS;

    return (
        <div className="entries-tab space-y-10 animate-in fade-in duration-500">

            {/* 1. HEADER & GLOBAL ACTIONS */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-6 px-4">
                <div className="flex items-center gap-4">
                    <div className="w-14 h-14 bg-green-500/10 border border-green-500/20 rounded-2xl flex items-center justify-center text-green-400 shadow-2xl">
                        <Search size={30} />
                    </div>
                    <div>
                        <h2 className="text-3xl font-black text-white tracking-tighter uppercase">Watchlist & Entries</h2>
                        <p className="text-gray-500 text-[10px] font-black uppercase tracking-[0.2em] opacity-60">Neural Opportunity Cluster</p>
                    </div>
                </div>

                <button
                    onClick={() => { setIsAdding(!isAdding); setEditingEntry(null); }}
                    className={`flex items-center gap-3 px-8 py-4 rounded-[2rem] text-xs font-black uppercase tracking-widest transition-all ${isAdding ? 'bg-red-500/10 text-red-400 border border-red-500/20' : 'bg-white text-black shadow-2xl hover:scale-105'
                        }`}
                >
                    {isAdding ? <X size={18} /> : <Plus size={18} />}
                    {isAdding ? 'Cancel Entry' : 'Manual Entry Injection'}
                </button>
            </div>

            {/* 2. FORM DRAWER (IF ADDING/EDITING) */}
            {(isAdding || editingEntry) && (
                <div className="bg-[#0a0b0d] border border-white/10 rounded-[3rem] p-10 shadow-2xl animate-in zoom-in-95 duration-300">
                    <div className="flex items-center justify-between mb-8">
                        <h3 className="text-lg font-black text-white uppercase tracking-tight flex items-center gap-3">
                            <Plus size={20} className="text-green-400" />
                            {editingEntry ? `Update Identity: ${editingEntry.symbol}` : 'New Opportunity Initialization'}
                        </h3>
                        <button onClick={() => { setIsAdding(false); setEditingEntry(null); }} className="text-gray-500 hover:text-white"><X size={20} /></button>
                    </div>
                    <div className="max-w-4xl">
                        <EntryForm
                            onSuccess={() => { fetchEntries(); setEditingEntry(null); setIsAdding(false); }}
                            initialData={editingEntry}
                        />
                    </div>
                </div>
            )}

            {/* 3. NAVIGATION CLUSTERS */}
            <div className="flex items-center p-1.5 bg-black/40 border border-white/5 rounded-[2rem] self-start shadow-2xl overflow-x-auto no-scrollbar max-w-full">
                {navTabs.map((tab) => (
                    <button
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id)}
                        className={tabClass(activeTab === tab.id)}
                    >
                        {tab.icon} {tab.label}
                    </button>
                ))}
            </div>
            {/* 4. CARDS GRID */}
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3 gap-8">
                {entryCards}
                {filteredEntries.length === 0 && (
                    <div className="col-span-full py-32 text-center bg-white/[0.02] border border-dashed border-white/5 rounded-[3rem]">
                        <LayoutGrid size={48} className="mx-auto mb-6 text-gray-800 opacity-40" />
                        <p className="text-sm font-black text-gray-700 uppercase tracking-[0.3em] opacity-40">Cluster Context Null</p>
                    </div>
                )}
            </div>
        </div>
    );
};

const X = ({ size }: { size: number }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M18 6 6 18" /><path d="m6 6 12 12" /></svg>
);
