'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import type { FirmConfig, FirmState, AccountState, AccountConfig } from '@/types';

type SortKey = 'name' | 'balance' | 'dayPnL' | 'daysTraded' | 'target' | 'status';
type SortDir = 'asc' | 'desc';

function statusRank(account: AccountState): number {
    if (isAccountDead(account)) return 0;
    if (!account.active) return 1;
    if (!account.hasPosition) {
        if (account.targetHit) return 4; // Target Hit — most accomplished
        return 2; // Flat
    }
    return 3; // In Trade
}

function getAccountConfig(name: string, firm: FirmConfig): AccountConfig | undefined {
    return [...firm.accounts]
        .sort((a, b) => b.prefix.length - a.prefix.length)
        .find((a) => name.startsWith(a.prefix));
}

function fmt(value: number) {
    return value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

/** Returns true when an account's balance has breached Tradovate's auto-liquidation floor. */
function isAccountDead(account: AccountState): boolean {
    return account.autoLiqThreshold > 0 && account.amount <= account.autoLiqThreshold;
}

function SettingsIcon() {
    return (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="3" />
            <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
        </svg>
    );
}

function ChevronIcon({ open }: { open: boolean }) {
    return (
        <svg className={`chevron${open ? ' open' : ''}`} width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="6 9 12 15 18 9" />
        </svg>
    );
}

function DetailsIcon() {
    return (
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
            <polyline points="15 3 21 3 21 9" />
            <line x1="10" y1="14" x2="21" y2="3" />
        </svg>
    );
}

function EyeIcon() {
    return (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
            <circle cx="12" cy="12" r="3" />
        </svg>
    );
}

function EyeOffIcon() {
    return (
        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94" />
            <path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19" />
            <line x1="1" y1="1" x2="23" y2="23" />
        </svg>
    );
}

function maskName(name: string, privacy: boolean): string {
    if (!privacy) return name;
    const visible = name.slice(0, 5);
    const hidden = name.slice(5);
    return hidden.length > 0 ? visible + '•'.repeat(hidden.length) : visible;
}

function SortHeader({ label, col, sortKey, sortDir, onSort }: {
    label: string;
    col: SortKey;
    sortKey: SortKey | null;
    sortDir: SortDir;
    onSort: (col: SortKey) => void;
}) {
    const active = sortKey === col;
    return (
        <th
            className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider cursor-pointer select-none transition-colors group"
            onClick={() => onSort(col)}
        >
            <div className="flex items-center gap-1">
                <span className={active ? 'text-slate-600' : 'text-slate-400 group-hover:text-slate-500'}>
                    {label}
                </span>
                <span className={`text-[10px] ${active ? 'text-slate-500' : 'text-slate-300 group-hover:text-slate-400'}`}>
                    {active ? (sortDir === 'asc' ? '↑' : '↓') : '↕'}
                </span>
            </div>
        </th>
    );
}

function AccountRow({ account, firm, hideDead, privacy }: { account: AccountState; firm: FirmConfig; hideDead: boolean; privacy: boolean }) {
    const cfg = getAccountConfig(account.name, firm);
    const dead = isAccountDead(account);

    if (hideDead && dead) return null;

    const pnlColor = account.realizedPnL > 0 ? 'text-green-600 font-medium' : account.realizedPnL < 0 ? 'text-red-600 font-medium' : 'text-slate-400';

    return (
        <tr className={`border-b border-slate-100 hover:bg-slate-50 transition-colors${!account.active || dead ? ' opacity-50' : ''}`}>
            <td className="px-4 py-3">
                <div className="flex items-center gap-2 font-medium text-slate-800 pl-4 font-mono">
                    {maskName(account.name, privacy)}
                </div>
            </td>
            <td className="px-4 py-3 text-slate-600 tabular-nums">${fmt(account.amount)}</td>
            <td className={`px-4 py-3 tabular-nums ${pnlColor}`}>
                {account.realizedPnL >= 0 ? '+' : ''}${fmt(account.realizedPnL)}
            </td>
            <td className="px-4 py-3 text-slate-600 tabular-nums">
                {account.daysTraded} / {cfg?.minTradingDays ?? '—'}
            </td>
            <td className="px-4 py-3 text-slate-600 tabular-nums">
                ${cfg?.profitTarget?.toLocaleString() ?? '—'}
            </td>
            <td className="px-4 py-3">
                <div className="flex items-center justify-between">
                    {dead
                        ? <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-slate-800 text-white">Dead</span>
                        : !account.active
                            ? <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-700">Hit DLL</span>
                            : account.hasPosition
                                ? <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-blue-100 text-blue-700">In Trade</span>
                                : account.targetHit
                                    ? <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-green-100 text-green-700">Target Hit</span>
                                    : <span className="inline-block px-2.5 py-0.5 rounded-full text-xs font-semibold bg-slate-100 text-slate-500">Flat</span>}
                    <Link
                        href={`/accounts/${account.id}`}
                        className="text-slate-400 hover:text-slate-600 hover:bg-slate-200 p-1 rounded-md transition-colors inline-flex"
                        title="View details"
                        onClick={(e) => e.stopPropagation()}
                    >
                        <DetailsIcon />
                    </Link>
                </div>
            </td>
        </tr>
    );
}

function FirmRows({ state, firm, deleteMode, selected, onToggle, hideDead, privacy, sortKey, sortDir, tradeSymbol }: {
    state: FirmState;
    firm: FirmConfig;
    deleteMode: boolean;
    selected: boolean;
    onToggle: () => void;
    hideDead: boolean;
    privacy: boolean;
    sortKey: SortKey | null;
    sortDir: SortDir;
    tradeSymbol: string;
}) {
    const [open, setOpen] = useState(true);

    const sortedAccounts = sortKey === null ? state.accounts : [...state.accounts].sort((a, b) => {
        const dir = sortDir === 'asc' ? 1 : -1;
        switch (sortKey) {
            case 'name':       return dir * a.name.localeCompare(b.name);
            case 'balance':    return dir * (a.amount - b.amount);
            case 'dayPnL':     return dir * (a.realizedPnL - b.realizedPnL);
            case 'daysTraded': return dir * (a.daysTraded - b.daysTraded);
            case 'target': {
                const at = getAccountConfig(a.name, firm)?.profitTarget ?? 0;
                const bt = getAccountConfig(b.name, firm)?.profitTarget ?? 0;
                return dir * (at - bt);
            }
            case 'status':     return dir * (statusRank(a) - statusRank(b));
            default:           return 0;
        }
    });

    return (
        <>
            <tr
                className="border-t border-slate-200 bg-slate-50 hover:bg-slate-100 cursor-pointer select-none transition-colors"
                onClick={() => setOpen((o) => !o)}
            >
                <td className="px-4 py-3.5">
                    <div className="flex items-center gap-2.5">
                        {deleteMode && (
                            <input
                                type="checkbox"
                                checked={selected}
                                onChange={onToggle}
                                onClick={(e) => e.stopPropagation()}
                                className="w-4 h-4 accent-red-500 cursor-pointer flex-shrink-0"
                            />
                        )}
                        <span className="font-bold text-sm text-slate-800">{state.firm}</span>
                        {firm.bannedSymbols?.includes(tradeSymbol) && (
                            <span className="text-xs bg-red-100 text-red-700 px-1.5 py-0.5 rounded font-semibold">
                                {tradeSymbol} BANNED
                            </span>
                        )}
                    </div>
                </td>
                <td /><td /><td /><td />
                <td className="px-4 py-3.5">
                    <div className="flex items-center justify-end gap-1">
                        <Link
                            href={`/firms/${firm.id}/settings`}
                            className="text-slate-400 hover:text-slate-600 hover:bg-slate-200 p-1 rounded-md transition-colors inline-flex"
                            onClick={(e) => e.stopPropagation()}
                            title="Settings"
                        >
                            <SettingsIcon />
                        </Link>
                        <ChevronIcon open={open} />
                    </div>
                </td>
            </tr>

            {open && (
                state.accounts.length === 0 ? (
                    <tr>
                        <td colSpan={6} className="px-4 py-5 pl-12 text-sm text-slate-400 italic">
                            Waiting for data...
                        </td>
                    </tr>
                ) : (
                    sortedAccounts.map((acc) => (
                        <AccountRow key={acc.id} account={acc} firm={firm} hideDead={hideDead} privacy={privacy} />
                    ))
                )
            )}
        </>
    );
}


interface SchedulerStatus {
    running: boolean;
    action: 'Buy' | 'Sell' | 'Random';
    symbol: string;
    lastRun: string | null;
}

export default function Home() {
    const router = useRouter();
    const [config, setConfig] = useState<FirmConfig[]>([]);
    const [firms, setFirms] = useState<FirmState[]>([]);
    const [deleteMode, setDeleteMode] = useState(false);
    const [selected, setSelected] = useState<Set<number>>(new Set());
    const [hideDead, setHideDead] = useState(false);
    const [privacy, setPrivacy] = useState(false);
    const [sortKey, setSortKey] = useState<SortKey | null>(null);
    const [sortDir, setSortDir] = useState<SortDir>('asc');

    // Trade controls
    const [scheduler, setScheduler] = useState<SchedulerStatus>({ running: false, action: 'Buy', symbol: 'NQ', lastRun: null });
    const [enabledSymbols, setEnabledSymbols] = useState<string[]>([]);
    const [tradeSymbol, setTradeSymbol] = useState('');
    const [tradeAction, setTradeAction] = useState<'Buy' | 'Sell' | 'Random'>('Buy');
    const [tradeLoading, setTradeLoading] = useState(false);

    const handleSort = (col: SortKey) => {
        if (sortKey === col) {
            setSortDir((d) => d === 'asc' ? 'desc' : 'asc');
        } else {
            setSortKey(col);
            setSortDir('asc');
        }
    };

    const fetchConfig = async () => {
        try {
            const res = await fetch('/api/firms');
            if (res.ok) {
                const data: FirmConfig[] = await res.json();
                setConfig(data);
            }
        } catch {
            // server not running yet
        }
    };

    const fetchScheduler = async () => {
        try {
            const res = await fetch('/api/auto-trade');
            if (res.ok) setScheduler(await res.json());
        } catch { /* ignore */ }
    };

    useEffect(() => {
        fetch('/api/instruments')
            .then((r) => r.json() as Promise<{ symbol: string; enabled: boolean }[]>)
            .then((instruments) => {
                const syms = instruments.filter((i) => i.enabled).map((i) => i.symbol);
                setEnabledSymbols(syms);
                setTradeSymbol((prev) => prev || syms[0] || 'NQ');
            })
            .catch(() => {});

        fetchConfig();
        fetchScheduler();

        const fetchState = async () => {
            try {
                const res = await fetch('/api/state');
                if (res.ok) {
                    const data: FirmState[] = await res.json();
                    setFirms(data);
                }
            } catch {
                // server not running yet
            }
        };

        fetchState();
        const stateInterval = setInterval(fetchState, 5000);
        const schedulerInterval = setInterval(fetchScheduler, 5000);
        return () => { clearInterval(stateInterval); clearInterval(schedulerInterval); };
    }, []);

    const handleStart = async () => {
        setTradeLoading(true);
        try {
            await fetch('/api/trade', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: tradeAction, symbol: tradeSymbol }),
            });
            await fetchScheduler();
        } finally {
            setTradeLoading(false);
        }
    };

    const handleStop = async () => {
        await fetch('/api/auto-trade', { method: 'DELETE' });
        setScheduler((s) => ({ ...s, running: false, lastRun: null }));
    };

    // Count dead accounts across all firms for the toggle button label
    const deadCount = firms.reduce((total, firmState) => {
        const firmCfg = config.find((c) => c.firm === firmState.firm);
        if (!firmCfg) return total;
        return total + firmState.accounts.filter((acc) => isAccountDead(acc)).length;
    }, 0);

    const handleConfirmDelete = async () => {
        await Promise.all(
            [...selected].map((id) =>
                fetch(`/api/firms/${id}`, { method: 'DELETE' }).catch(() => {})
            )
        );
        setSelected(new Set());
        setDeleteMode(false);
        fetchConfig();
    };

    const toggleSelected = (id: number) => {
        setSelected((prev) => {
            const next = new Set(prev);
            if (next.has(id)) next.delete(id);
            else next.add(id);
            return next;
        });
    };

    return (
        <div className="min-h-screen bg-slate-50 p-8">
            <div className="max-w-7xl mx-auto">
                <div className="flex items-center justify-between mb-6">
                    <h1 className="text-2xl font-bold text-slate-900">AutoTrader</h1>
                    <div className="flex items-center gap-2">
                        {deleteMode ? (
                            <>
                                {selected.size > 0 && (
                                    <button
                                        onClick={handleConfirmDelete}
                                        className="px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 text-sm font-semibold rounded-lg transition-colors"
                                    >
                                        Confirm Delete ({selected.size})
                                    </button>
                                )}
                                <button
                                    onClick={() => { setDeleteMode(false); setSelected(new Set()); }}
                                    className="px-4 py-2 text-sm text-slate-600 hover:text-slate-800 border border-slate-200 bg-white rounded-lg transition-colors"
                                >
                                    Cancel
                                </button>
                            </>
                        ) : (
                            <>
                                {deadCount > 0 && (
                                    <button
                                        onClick={() => setHideDead((h) => !h)}
                                        className={`px-4 py-2 text-sm font-semibold rounded-lg transition-colors border ${
                                            hideDead
                                                ? 'bg-slate-800 text-white border-slate-800 hover:bg-slate-700'
                                                : 'bg-white text-slate-600 border-slate-200 hover:bg-slate-100'
                                        }`}
                                    >
                                        {hideDead ? `Show Dead (${deadCount})` : `Hide Dead (${deadCount})`}
                                    </button>
                                )}
                                <button
                                    onClick={() => router.push('/add')}
                                    className="px-4 py-2 bg-green-100 hover:bg-green-200 text-green-700 text-sm font-semibold rounded-lg transition-colors"
                                >
                                    + Add New
                                </button>
                                <button
                                    onClick={() => setDeleteMode(true)}
                                    className="px-4 py-2 bg-red-100 hover:bg-red-200 text-red-700 text-sm font-semibold rounded-lg transition-colors"
                                >
                                    Delete
                                </button>
                                <button
                                    onClick={() => setPrivacy((p) => !p)}
                                    className={`px-3 py-2 rounded-lg transition-colors inline-flex items-center ${privacy ? 'text-blue-600 bg-blue-50 hover:bg-blue-100' : 'text-slate-400 hover:text-slate-600 hover:bg-slate-100'}`}
                                    title={privacy ? 'Show account names' : 'Hide account names'}
                                >
                                    {privacy ? <EyeOffIcon /> : <EyeIcon />}
                                </button>
                                <Link
                                    href="/settings"
                                    className="px-3 py-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-lg transition-colors inline-flex items-center"
                                    title="Global Settings"
                                >
                                    <SettingsIcon />
                                </Link>
                            </>
                        )}
                    </div>
                </div>
                {/* ── Trade Controls ── */}
                <div className="bg-white border border-slate-200 rounded-xl px-4 py-3 mb-4 shadow-sm flex items-center gap-3">
                    {scheduler.running ? (
                        <>
                            <span className="w-2 h-2 rounded-full bg-green-500 animate-pulse flex-shrink-0" />
                            <span className="text-sm font-semibold text-green-700">
                                {scheduler.symbol} · {scheduler.action}
                            </span>
                            {scheduler.lastRun && (
                                <span className="text-xs text-slate-400">
                                    last run {new Date(scheduler.lastRun).toLocaleTimeString()}
                                </span>
                            )}
                            <button
                                onClick={handleStop}
                                className="ml-auto px-4 py-1.5 bg-red-100 hover:bg-red-200 text-red-700 text-sm font-semibold rounded-lg transition-colors"
                            >
                                ■ Stop
                            </button>
                        </>
                    ) : (
                        <>
                            <span className="w-2 h-2 rounded-full bg-slate-300 flex-shrink-0" />
                            <span className="text-sm text-slate-400 font-medium">Idle</span>
                            <div className="flex items-center gap-2 ml-3">
                                <select
                                    value={tradeSymbol}
                                    onChange={(e) => setTradeSymbol(e.target.value)}
                                    className="rounded-lg border border-slate-200 bg-slate-50 px-2.5 py-1.5 text-sm font-mono text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
                                >
                                    {enabledSymbols.map((s) => <option key={s} value={s}>{s}</option>)}
                                    <option value="Random">Random</option>
                                </select>
                                <div className="flex rounded-lg border border-slate-200 overflow-hidden text-sm font-semibold">
                                    <button
                                        onClick={() => setTradeAction('Buy')}
                                        className={`px-3 py-1.5 transition-colors ${tradeAction === 'Buy' ? 'bg-green-500 text-white' : 'text-slate-500 hover:bg-slate-50'}`}
                                    >
                                        Buy
                                    </button>
                                    <button
                                        onClick={() => setTradeAction('Sell')}
                                        className={`px-3 py-1.5 transition-colors border-l border-slate-200 ${tradeAction === 'Sell' ? 'bg-red-500 text-white' : 'text-slate-500 hover:bg-slate-50'}`}
                                    >
                                        Sell
                                    </button>
                                    <button
                                        onClick={() => setTradeAction('Random')}
                                        className={`px-3 py-1.5 transition-colors border-l border-slate-200 ${tradeAction === 'Random' ? 'bg-purple-500 text-white' : 'text-slate-500 hover:bg-slate-50'}`}
                                    >
                                        Random
                                    </button>
                                </div>
                            </div>
                            <button
                                onClick={handleStart}
                                disabled={tradeLoading}
                                className="ml-auto px-4 py-1.5 bg-blue-500 hover:bg-blue-600 disabled:opacity-50 text-white text-sm font-semibold rounded-lg transition-colors"
                            >
                                {tradeLoading ? 'Starting…' : '▶ Start'}
                            </button>
                        </>
                    )}
                </div>

                <div className="w-full bg-white border border-slate-200 rounded-xl overflow-hidden shadow-sm">
                    <table className="w-full text-sm border-collapse">
                        <thead>
                            <tr className="border-b border-slate-200 bg-slate-50">
                                <SortHeader label="Account"     col="name"       sortKey={sortKey} sortDir={sortDir} onSort={handleSort} />
                                <SortHeader label="Balance"     col="balance"    sortKey={sortKey} sortDir={sortDir} onSort={handleSort} />
                                <SortHeader label="Day P&L"     col="dayPnL"     sortKey={sortKey} sortDir={sortDir} onSort={handleSort} />
                                <SortHeader label="Days Traded" col="daysTraded" sortKey={sortKey} sortDir={sortDir} onSort={handleSort} />
                                <SortHeader label="Target"      col="target"     sortKey={sortKey} sortDir={sortDir} onSort={handleSort} />
                                <SortHeader label="Status"      col="status"     sortKey={sortKey} sortDir={sortDir} onSort={handleSort} />
                            </tr>
                        </thead>
                        <tbody>
                            {config.length === 0 ? (
                                <tr>
                                    <td colSpan={6} className="px-4 py-8 text-center text-sm text-slate-400 italic">
                                        No firms yet — click + Add New to get started
                                    </td>
                                </tr>
                            ) : (
                                config.map((cfg) => {
                                    const state = firms.find((f) => f.firm === cfg.firm) ?? { firm: cfg.firm, connected: false, accounts: [] };
                                    return (
                                        <FirmRows
                                            key={cfg.id}
                                            state={state}
                                            firm={cfg}
                                            deleteMode={deleteMode}
                                            selected={selected.has(cfg.id)}
                                            onToggle={() => toggleSelected(cfg.id)}
                                            hideDead={hideDead}
                                            privacy={privacy}
                                            sortKey={sortKey}
                                            sortDir={sortDir}
                                            tradeSymbol={tradeSymbol}
                                        />
                                    );
                                })
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
}
