import { useEffect, useState } from 'react';
import { useAuth } from '../components/AuthContext';
import { EntryForm } from '../components/EntryForm';
import { Pencil, Trash2, Copy as CopyIcon, Plus, Filter, LayoutGrid, Clock, ShieldCheck, Activity, X } from 'lucide-react';
import type { BotState } from '../hooks/useWebSocket';
import { DEFAULT_BOT_STATE } from '../hooks/useWebSocket';
import { createManualEntry, deleteManualEntry, fetchManualEntries, type ManualEntryPayload } from '../lib/manualEntriesApi';
import { Button } from '../components/ui/Primitives';

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;
    workflow_type?: string;
    holding_mode?: string;
    automation_state?: string;
}

export const filterEntriesByTab = (entries: Entry[], activeTab: string) =>
    entries.filter((entry) => {
        if (String(entry.workflow_type || '').trim().toLowerCase() === 'simple') {
            return false;
        }
        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) =>
    `min-h-9 rounded-lg px-3 text-xs font-semibold transition flex items-center gap-2 whitespace-nowrap ${isActive ? "border border-[var(--border-strong)] bg-[var(--accent-soft)] text-[var(--foreground)] shadow-sm" : "text-[var(--muted-foreground)] hover:bg-[var(--muted)] hover:text-[var(--foreground)]"}`;

const entryModeClass = (isRealTrade: boolean) =>
    `entry-mode-pill ${isRealTrade ? 'is-real' : 'is-paper'}`;

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);
    const [loading, setLoading] = useState(false);
    const [feedback, setFeedback] = useState<{ tone: 'success' | 'error'; message: string } | null>(null);

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

    const fetchEntries = async () => {
        if (!user) return;
        setLoading(true);
        try {
            const data = await fetchManualEntries();
            setEntries(data as Entry[]);
            setFeedback((current) => current?.tone === 'error' ? null : current);
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : String(err);
            console.error("Error fetching entries:", message);
            setFeedback({ tone: 'error', message: `Failed to load watchlist entries: ${message}` });
        } finally {
            setLoading(false);
        }
    };

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

    const handleDelete = async (id: string) => {
        if (!confirm('Permanently delete this watchlist entry?')) return;
        try {
            await deleteManualEntry(id);
            setFeedback({ tone: 'success', message: 'Watchlist entry deleted.' });
            await fetchEntries();
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : String(err);
            setFeedback({ tone: 'error', message: `Failed to delete entry: ${message}` });
        }
    };

    const handleClone = async (entry: Entry) => {
        try {
            await createManualEntry(buildClonedEntryPayload(entry, crypto.randomUUID()) as unknown as ManualEntryPayload);
            setFeedback({ tone: 'success', message: `${entry.symbol} cloned as a suspended entry.` });
            await fetchEntries();
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : String(err);
            setFeedback({ tone: 'error', message: `Failed to clone entry: ${message}` });
        }
    };

    const entryCards = filteredEntries.map((entry) => {
        const entryState = deriveEntryState(entry, botState);
        return (
            <article key={entry.stock_instance_id} className="entry-card group">
                    <div className="mb-5 flex items-start justify-between gap-4">
                        <div className="min-w-0 space-y-2">
                            <h4 className="m-0 truncate text-xl font-semibold tracking-tight text-[var(--foreground)]">{entry.symbol}</h4>
                            <div className="flex items-center gap-2">
                                <span className={entryModeClass(entry.is_real_trade)}>
                                    {entry.is_real_trade ? 'Real' : 'Paper'}
                                </span>
                                {entry.label && (
                                    <span className="rounded-full border border-[var(--border)] bg-[var(--muted)] px-2.5 py-1 text-[11px] font-semibold text-[var(--muted-foreground)]">
                                        {entry.label}
                                    </span>
                                )}
                            </div>
                        </div>
                        <div className="flex shrink-0 gap-1 opacity-100 transition md:opacity-0 md:group-hover:opacity-100">
                            <Button type="button" onClick={() => setEditingEntry(entry)} variant="ghost" size="icon" aria-label={`Edit ${entry.symbol}`}><Pencil size={15} /></Button>
                            <Button type="button" onClick={() => handleClone(entry)} variant="ghost" size="icon" aria-label={`Clone ${entry.symbol}`}><CopyIcon size={15} /></Button>
                            <Button type="button" onClick={() => handleDelete(entry.stock_instance_id)} variant="ghost" size="icon" aria-label={`Delete ${entry.symbol}`} className="text-[var(--destructive)] hover:bg-[var(--bl-danger-muted)]"><Trash2 size={15} /></Button>
                        </div>
                    </div>

                    <div className="mb-5 grid grid-cols-2 gap-3">
                        <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/60 p-4">
                            <span className="mb-1 block text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">Entry</span>
                            <span className="font-mono text-base font-semibold text-[var(--foreground)]">${entry.buy_price || '0.00'}</span>
                        </div>
                        <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/60 p-4">
                            <span className="mb-1 block text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">Target</span>
                            <span className="font-mono text-base font-semibold text-[var(--foreground)]">${entry.sell_price || '---'}</span>
                        </div>
                        <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/60 p-4">
                            <span className="mb-1 block text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">Quantity</span>
                            <span className="font-mono text-sm font-semibold text-[var(--foreground)]">{entry.quantity || '—'}</span>
                        </div>
                        <div className="rounded-xl border border-[var(--border)] bg-[var(--muted)]/60 p-4">
                            <span className="mb-1 block text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">Status</span>
                            <span className={`text-sm font-semibold ${entry.active ? 'text-[var(--bl-success)]' : 'text-[var(--muted-foreground)]'}`}>
                                {entry.active ? 'Active' : 'Inactive'}
                            </span>
                        </div>
                    </div>

                    <div className="mb-5 flex items-center justify-between gap-3 rounded-xl border border-[var(--border)] bg-[var(--card-elevated)] px-3 py-2">
                        <span className="text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">Entry state</span>
                        <span className={`entry-state-pill state-${entryState.toLowerCase().replace(/[^a-z]/g, '')}`}>
                            {entryState}
                        </span>
                    </div>

                    <div className="flex-grow">
                        <span className="mb-2 block text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--muted-foreground)]">Notes</span>
                        <p className="m-0 text-sm leading-6 text-[var(--muted-foreground)]">
                            {entry.notes || 'No notes added yet.'}
                        </p>
                    </div>

                    <div className="mt-5 flex items-center justify-between gap-3 border-t border-[var(--border)] pt-4">
                        <span className="truncate font-mono text-[11px] text-[var(--muted-foreground)]">{entry.stock_instance_id}</span>
                        <ShieldCheck size={15} className="shrink-0 text-[var(--muted-foreground)]" />
                    </div>
            </article>
        );
    });

    const navTabs = NAV_TABS;

    return (
        <div className="entries-tab ux-page-stack animate-in fade-in duration-500">

            <div className="ux-section-header">
                <div>
                    <h2 className="ux-section-title text-lg">Watchlist entries</h2>
                    <p className="ux-section-copy mt-1">Track manual symbols, paper setups, and real execution candidates.</p>
                </div>
                <Button
                    type="button"
                    onClick={() => { setIsAdding(!isAdding); setEditingEntry(null); }}
                    variant={isAdding ? 'outline' : 'primary'}
                    className="flex items-center gap-2"
                >
                    {isAdding ? <X size={16} /> : <Plus size={16} />}
                    {isAdding ? 'Cancel' : 'Add entry'}
                </Button>
            </div>

            {(isAdding || editingEntry) && (
                <div className="ux-section animate-in zoom-in-95 duration-300">
                    <div className="ux-section-header">
                    <div>
                            <h3 className="ux-section-title">
                                {editingEntry ? `Edit ${editingEntry.symbol}` : 'New watchlist entry'}
                            </h3>
                            <p className="ux-section-copy mt-1">Save a symbol with target prices, quantity, and execution context.</p>
                        </div>
                        <Button type="button" onClick={() => { setIsAdding(false); setEditingEntry(null); }} variant="ghost" size="icon" aria-label="Close entry form"><X size={18} /></Button>
                    </div>
                    <div className="max-w-4xl">
                        <EntryForm
                            onSuccess={() => { fetchEntries(); setEditingEntry(null); setIsAdding(false); }}
                            initialData={editingEntry}
                        />
                    </div>
                </div>
            )}

            <div className="entries-tab-nav flex max-w-full items-center gap-1 overflow-x-auto rounded-xl border border-[var(--border)] bg-[var(--card)] p-1 shadow-sm no-scrollbar">
                {navTabs.map((tab) => (
                    <Button
                        type="button"
                        key={tab.id}
                        onClick={() => setActiveTab(tab.id)}
                        variant="ghost"
                        className={tabClass(activeTab === tab.id)}
                    >
                        {tab.icon} {tab.label}
                    </Button>
                ))}
            </div>
            {feedback && (
                <div className={`watchlist-feedback is-${feedback.tone}`} role="status">
                    {feedback.message}
                </div>
            )}
            <div className="grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3">
                {loading && filteredEntries.length === 0 && (
                    <div className="ux-empty-state col-span-full">
                        <div>
                            <LayoutGrid size={34} className="mx-auto mb-4 text-[var(--muted-foreground)]" />
                            <strong>Loading entries</strong>
                            <span>Fetching your saved watchlist and manual entries.</span>
                        </div>
                    </div>
                )}
                {entryCards}
                {!loading && filteredEntries.length === 0 && (
                    <div className="ux-empty-state col-span-full">
                        <div>
                            <LayoutGrid size={34} className="mx-auto mb-4 text-[var(--muted-foreground)]" />
                            <strong>No entries in this view</strong>
                            <span>Try another status filter or add a new watchlist entry.</span>
                        </div>
                    </div>
                )}
            </div>
        </div>
    );
};
