'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';

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 AccountRow({ account, firm, hideDead }: { account: AccountState; firm: FirmConfig; hideDead: 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">
                    {account.name}
                </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">Inactive</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>
                                : <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 }: {
    state: FirmState;
    firm: FirmConfig;
    deleteMode: boolean;
    selected: boolean;
    onToggle: () => void;
    hideDead: boolean;
}) {
    const [open, setOpen] = useState(true);

    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>
                    </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>
                ) : (
                    state.accounts.map((acc) => (
                        <AccountRow key={acc.id} account={acc} firm={firm} hideDead={hideDead} />
                    ))
                )
            )}
        </>
    );
}

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 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
        }
    };

    useEffect(() => {
        fetchConfig();

        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 interval = setInterval(fetchState, 5000);
        return () => clearInterval(interval);
    }, []);

    // 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>
                                <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>
                <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">
                                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Account</th>
                                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Balance</th>
                                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Day P&L</th>
                                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Days Traded</th>
                                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Target</th>
                                <th className="px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-slate-400">Status</th>
                            </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}
                                        />
                                    );
                                })
                            )}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    );
}
