import { useState, useEffect } from 'react';
import type { FormEvent } from 'react';
import { useAuth } from '../components/AuthContext';
import { tradingRuntime } from '../lib/runtime';
import { createManualEntry, updateManualEntry } from '../lib/manualEntriesApi';
import { getPlatformAccessToken } from '../lib/authSession';
import { createRequestId } from '../../../shared/request-id.js';
import { Button, Checkbox, Input } from './ui/Primitives';

interface EntryFormProps {
    onSuccess: () => void;
    initialData?: any;
}

const numericInputClass = 'font-mono text-right';
const checkboxLabelClass = 'flex min-h-10 cursor-pointer items-center gap-2 rounded-[var(--bl-radius-control)] border border-[var(--border)] bg-[var(--card-elevated)] px-3 text-sm text-[var(--foreground)] transition hover:border-[var(--primary)]';

export function EntryForm({ onSuccess, initialData }: EntryFormProps) {
    const { user } = useAuth();
    const [formData, setFormData] = useState({
        symbol: '',
        label: '',
        status: 'active',
        active: true,
        quantity: '',
        filled_quantity: '',
        entry_price: '',
        buy_price: '',
        sell_price: '',
        gain_threshold_for_sell: '',
        drop_threshold_for_buy: '',
        buy_time: '',
        sell_time: '',
        notes: '',
        is_real_trade: false,
        is_crypto: false,
        execute_order: false,
    });

    useEffect(() => {
        if (initialData) {
            setFormData({
                ...initialData,
                quantity: initialData.quantity || '',
                filled_quantity: initialData.filled_quantity || '',
                entry_price: initialData.entry_price || '',
                buy_price: initialData.buy_price || '',
                sell_price: initialData.sell_price || '',
                gain_threshold_for_sell: initialData.gain_threshold_for_sell || '',
                drop_threshold_for_buy: initialData.drop_threshold_for_buy || '',
                buy_time: initialData.buy_time || '',
                sell_time: initialData.sell_time || '',
                // Preserve execute_order as false on edit init
                execute_order: false,
            });
        } else {
            // Reset form for new entry
            setFormData({
                symbol: '',
                label: '',
                status: 'active',
                active: true,
                quantity: '',
                filled_quantity: '',
                entry_price: '',
                buy_price: '',
                sell_price: '',
                gain_threshold_for_sell: '',
                drop_threshold_for_buy: '',
                buy_time: '',
                sell_time: '',
                notes: '',
                is_real_trade: false,
                is_crypto: false,
                execute_order: false,
            });
        }
    }, [initialData]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
        const { name, value, type } = e.target;
        setFormData(prev => ({
            ...prev,
            [name]: type === 'checkbox' ? (e.target as HTMLInputElement).checked : value,
        }));
    };

    const handleSubmit = async (e: FormEvent) => {
        e.preventDefault();

        if (!user) return;

        try {
            const payload = {
                ...formData,
                user_id: user.id,
                // Convert numeric fields
                quantity: formData.quantity ? parseFloat(formData.quantity) : null,
                filled_quantity: formData.filled_quantity ? parseFloat(formData.filled_quantity) : null,
                entry_price: formData.entry_price ? parseFloat(formData.entry_price) : null,
                buy_price: formData.buy_price ? parseFloat(formData.buy_price) : null,
                sell_price: formData.sell_price ? parseFloat(formData.sell_price) : null,
                gain_threshold_for_sell: formData.gain_threshold_for_sell ? parseFloat(formData.gain_threshold_for_sell) : null,
                drop_threshold_for_buy: formData.drop_threshold_for_buy ? parseFloat(formData.drop_threshold_for_buy) : null,
                buy_time: formData.buy_time ? formData.buy_time : null,
                sell_time: formData.sell_time ? formData.sell_time : null,
                updated_at: new Date().toISOString(),
            };

            // Remove temp fields from DB payload
            delete (payload as any).execute_order;

            // --- REAL TRADE EXECUTION ---
            if (formData.execute_order && !initialData) {
                if (!Number.isFinite(payload.quantity) || !payload.symbol.trim()) {
                    alert('Symbol and a valid quantity are required to execute a trade.');
                    return;
                }
                // Determine side (Buy if buying, Sell if selling - simplistic for now assuming Entry = Buy)
                // If closing, we handle differently (via close button usually), but here handle Entry.

                const apiPayload = {
                    symbol: payload.symbol,
                    side: 'buy',
                    qty: payload.quantity,
                    type: 'market',
                    price: payload.buy_price,
                    sl: payload.drop_threshold_for_buy,
                    tp: payload.gain_threshold_for_sell
                };

                const confirmTrade = window.confirm(`EXECUTE LIVE TRADE (via Bot)?\n(Note: Uses currently configured Bot account)\n\nSymbol: ${payload.symbol}\nSide: BUY\nQty: ${payload.quantity}`);
                if (!confirmTrade) return;

                const apiUrl = tradingRuntime.tradingApiUrl;
                const accessToken = await getPlatformAccessToken();
                const response = await fetch(`${apiUrl}/api/trade`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${accessToken}`,
                        'x-request-id': createRequestId('web-entry')
                    },
                    body: JSON.stringify(apiPayload)
                });

                const resData = await response.json();
                if (!resData.success) {
                    throw new Error(`Execution Failed: ${resData.error}`);
                }

                alert(`Trade Executed! Order ID: ${resData.orderId}`);
            }

            if (initialData?.stock_instance_id) {
                await updateManualEntry(initialData.stock_instance_id, payload);
            } else {
                await createManualEntry({ ...payload, stock_instance_id: crypto.randomUUID() });
            }

            onSuccess();

            // Reset only if not editing
            if (!initialData) {
                setFormData(prev => ({ ...prev, symbol: '', label: '', notes: '' }));
            }
        } catch (error: any) {
            alert(`Error saving entry: ${error.message}`);
        }
    };

    return (
        <div className="entry-form-container">
            {!initialData && (
                <div className="tab-header mb-4">
                    <h2>New Entry / Watchlist</h2>
                    <p>Add a position or watchlist item.</p>
                </div>
            )}

            <form onSubmit={handleSubmit} className="space-y-5 rounded-[var(--bl-radius-card)] border border-[var(--border)] bg-[var(--card)] p-5 shadow-[var(--bl-shadow-card)]">
                <section className="rounded-[var(--bl-radius-card)] border border-[var(--border)] bg-[var(--card-elevated)] p-5">
                    <div className="mb-4">
                        <div className="text-sm font-bold text-[var(--foreground)]">Instrument</div>
                        <p className="mt-1 text-sm leading-6 text-[var(--muted-foreground)]">Name the opportunity and choose whether it is a watch item, trade journal entry, or crypto setup.</p>
                    </div>
                    <div className="grid gap-4 md:grid-cols-2">
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Symbol</span>
                            <Input type="text" name="symbol" required value={formData.symbol} onChange={handleChange} placeholder="BTC/USD" />
                        </label>
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Tag</span>
                            <Input type="text" name="label" value={formData.label} onChange={handleChange} placeholder="Swing" />
                        </label>
                    </div>
                    <div className="mt-4 grid gap-3 md:grid-cols-3">
                        <div className={checkboxLabelClass} title="Places actual order on Bot">
                            <Checkbox name="execute_order" checked={formData.execute_order} onChange={handleChange} label="Execute" />
                        </div>
                        <div className={checkboxLabelClass} title="Marks as Active Trade in Journal">
                            <Checkbox name="is_real_trade" checked={formData.is_real_trade} onChange={handleChange} label="Trade" />
                        </div>
                        <div className={checkboxLabelClass}>
                            <Checkbox name="is_crypto" checked={formData.is_crypto} onChange={handleChange} label="Crypto" />
                        </div>
                    </div>
                </section>

                <section className="rounded-[var(--bl-radius-card)] border border-[var(--border)] bg-[var(--card-elevated)] p-5">
                    <div className="mb-4">
                        <div className="text-sm font-bold text-[var(--foreground)]">Pricing and risk</div>
                        <p className="mt-1 text-sm leading-6 text-[var(--muted-foreground)]">Capture the planned entry, size, stop loss, take profit, and optional exit price.</p>
                    </div>
                    <div className="grid gap-4 md:grid-cols-3">
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Buy price</span>
                            <Input type="number" name="buy_price" step="any" value={formData.buy_price} onChange={handleChange} className={`${numericInputClass} text-[var(--bl-success)]`} placeholder="0.00" />
                        </label>
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Quantity</span>
                            <Input type="number" name="quantity" step="any" value={formData.quantity} onChange={handleChange} className={numericInputClass} placeholder="0" />
                        </label>
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Buy time</span>
                            <Input type="datetime-local" name="buy_time" value={formData.buy_time ? new Date(formData.buy_time).toISOString().slice(0, 16) : ''} onChange={(e) => setFormData(prev => ({ ...prev, buy_time: new Date(e.target.value).toISOString() }))} className="font-mono" />
                        </label>
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Stop loss</span>
                            <Input type="number" name="drop_threshold_for_buy" step="any" value={formData.drop_threshold_for_buy} onChange={handleChange} className={`${numericInputClass} text-[var(--bl-danger)]`} placeholder="SL" />
                        </label>
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Take profit</span>
                            <Input type="number" name="gain_threshold_for_sell" step="any" value={formData.gain_threshold_for_sell} onChange={handleChange} className={`${numericInputClass} text-[var(--bl-info)]`} placeholder="TP" />
                        </label>
                        <label className="ux-field-stack">
                            <span className="ux-field-label">Exit price</span>
                            <Input type="number" name="sell_price" step="any" value={formData.sell_price} onChange={handleChange} className={`${numericInputClass} text-[var(--bl-info-strong)]`} placeholder="Exit" />
                            {formData.sell_price && formData.buy_price && (
                                <span className={`text-xs font-bold ${(Number(formData.sell_price) - Number(formData.buy_price)) * Number(formData.quantity || 0) >= 0 ? 'text-[var(--bl-success)]' : 'text-[var(--bl-danger)]'}`}>
                                    Estimated P/L ${((Number(formData.sell_price) - Number(formData.buy_price)) * Number(formData.quantity || 1)).toFixed(2)}
                                </span>
                            )}
                        </label>
                    </div>
                </section>

                <section className="rounded-[var(--bl-radius-card)] border border-[var(--border)] bg-[var(--card-elevated)] p-5">
                    <label className="ux-field-stack">
                        <span className="ux-field-label">Strategy notes</span>
                        <Input type="text" name="notes" value={formData.notes} onChange={handleChange} placeholder="Add strategy notes here..." />
                    </label>
                </section>

                <div className="flex flex-col gap-3 rounded-[var(--bl-radius-card)] border border-[var(--border)] bg-[var(--card-elevated)] p-4 md:flex-row md:items-center md:justify-between">
                    <p className="text-sm leading-6 text-[var(--muted-foreground)]">Review the symbol, sizing, and risk fields before saving this manual entry.</p>
                    <div className="flex items-center justify-end gap-2">
                        {initialData && (
                            <Button type="button" onClick={onSuccess} variant="ghost">
                                Cancel
                            </Button>
                        )}
                        <Button type="submit">
                            {initialData ? 'Update' : 'Add'}
                        </Button>
                    </div>
                </div>
            </form>
        </div>
    );
}
