import { useState, useEffect } from 'react';
import type { FormEvent } from 'react';
import { supabase } from '../lib/supabaseClient';
import { useAuth } from '../components/AuthContext';
import { tableNameStocks } from '../lib/const';
import { tradingRuntime } from '../lib/runtime';

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

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) {
                // 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 { data: sessionData } = await supabase.auth.getSession();
                const accessToken = sessionData.session?.access_token;
                if (!accessToken) {
                    throw new Error('Not authenticated');
                }
                const response = await fetch(`${apiUrl}/api/trade`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${accessToken}`
                    },
                    body: JSON.stringify(apiPayload)
                });

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

                // If success, we continue to save to DB as usual for journaling
                alert(`✅ Trade Executed! Order ID: ${resData.orderId}`);
            }

            if (initialData?.stock_instance_id) {
                // Update
                const { error } = await supabase
                    .from(tableNameStocks)
                    .update(payload)
                    .eq('stock_instance_id', initialData.stock_instance_id);

                if (error) throw error;

                // --- NEW: Log to Trade History if Closing ---
                // If we are adding a sell_price to an open position, we consider it "Closing"
                if (payload.sell_price && !initialData.sell_price && payload.buy_price) {
                    const entryPrice = payload.buy_price;
                    const exitPrice = payload.sell_price;
                    const size = payload.quantity || 0;
                    const pnl = (exitPrice - entryPrice) * size;
                    const pnlPercent = ((exitPrice - entryPrice) / entryPrice) * 100;

                    // Insert into trade_history
                    const { error: historyError } = await supabase
                        .from('trade_history')
                        .insert([{
                            user_id: user.id,
                            symbol: payload.symbol,
                            side: 'BUY',
                            entry_price: entryPrice,
                            exit_price: exitPrice,
                            size: size,
                            pnl: pnl,
                            pnl_percent: pnlPercent,
                            source: 'MANUAL',
                            reason: 'Manual Close',
                            timestamp: Date.now()
                        }]);

                    if (historyError) {
                        console.error("Failed to log manual trade to history:", historyError.message);
                    }
                }

            } else {
                // Insert
                // Remove ID to let DB generate it
                const { error } = await supabase
                    .from(tableNameStocks)
                    .insert([{ ...payload, stock_instance_id: crypto.randomUUID() }]);

                if (error) throw error;

                // --- NEW: Log to Trade History if Creating a Closed Entry (Journaling past trade) ---
                if (payload.sell_price && payload.buy_price) {
                    const entryPrice = payload.buy_price;
                    const exitPrice = payload.sell_price;
                    const size = payload.quantity || 0;
                    const pnl = (exitPrice - entryPrice) * size;
                    const pnlPercent = ((exitPrice - entryPrice) / entryPrice) * 100;

                    // Insert into trade_history
                    const { error: historyError } = await supabase
                        .from('trade_history')
                        .insert([{
                            user_id: user.id,
                            symbol: payload.symbol,
                            side: 'BUY',
                            entry_price: entryPrice,
                            exit_price: exitPrice,
                            size: size,
                            pnl: pnl,
                            pnl_percent: pnlPercent,
                            source: 'MANUAL',
                            reason: 'Manual Log',
                            timestamp: Date.now()
                        }]);

                    if (historyError) {
                        console.error("Failed to log manual trade to history:", historyError.message);
                    }
                }
            }

            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="table-container">
                <table className="pro-table">
                    <thead>
                        <tr>
                            <th style={{ width: '15%' }}>Symbol</th>
                            <th style={{ width: '10%' }}>Tag</th>
                            <th style={{ width: '15%' }}>Options</th>
                            <th style={{ width: '12%' }} className="text-right">Buy Price</th>
                            <th style={{ width: '10%' }} className="text-right">Qty</th>
                            <th style={{ width: '10%' }} className="text-right">Stop Loss</th>
                            <th style={{ width: '10%' }} className="text-right">Take Profit</th>
                            <th style={{ width: '11%' }}>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            {/* Symbol */}
                            <td>
                                <input
                                    type="text"
                                    name="symbol"
                                    required
                                    value={formData.symbol}
                                    onChange={handleChange}
                                    placeholder="BTC/USD"
                                    className="bg-transparent border-b border-gray-600 focus:border-blue-500 outline-none w-full py-1 text-sm text-gray-200 placeholder-gray-600"
                                />
                            </td>

                            {/* Label */}
                            <td>
                                <input
                                    type="text"
                                    name="label"
                                    value={formData.label}
                                    onChange={handleChange}
                                    placeholder="Swing"
                                    className="bg-transparent border-b border-gray-600 focus:border-blue-500 outline-none w-full py-1 text-sm text-gray-200 placeholder-gray-600"
                                />
                            </td>

                            {/* Options (Real/Crypto) */}
                            <td>
                                <div className="flex flex-col gap-1">
                                    <label className="flex items-center cursor-pointer text-xs text-yellow-400 hover:text-yellow-300" title="Places actual order on Bot">
                                        <input
                                            type="checkbox"
                                            name="execute_order"
                                            checked={formData.execute_order}
                                            onChange={handleChange}
                                            className="mr-1.5 accent-yellow-500"
                                        />
                                        ⚡ Execute
                                    </label>
                                    <div className="flex items-center space-x-2">
                                        <label className="flex items-center cursor-pointer text-[10px] text-gray-500 hover:text-gray-300" title="Marks as Active Trade in Journal">
                                            <input
                                                type="checkbox"
                                                name="is_real_trade"
                                                checked={formData.is_real_trade}
                                                onChange={handleChange}
                                                className="mr-1 accent-blue-500 scale-75"
                                            />
                                            Trade
                                        </label>
                                        <label className="flex items-center cursor-pointer text-[10px] text-gray-500 hover:text-gray-300">
                                            <input
                                                type="checkbox"
                                                name="is_crypto"
                                                checked={formData.is_crypto}
                                                onChange={handleChange}
                                                className="mr-1 accent-purple-500 scale-75"
                                            />
                                            Crypto
                                        </label>
                                    </div>
                                </div>
                            </td>

                            {/* Buy Price */}
                            <td>
                                <input
                                    type="number"
                                    name="buy_price"
                                    step="any"
                                    value={formData.buy_price}
                                    onChange={handleChange}
                                    className="bg-transparent border-b border-gray-600 focus:border-green-500 outline-none w-full py-1 text-sm text-right text-green-400 placeholder-gray-700 font-mono"
                                    placeholder="0.00"
                                />
                            </td>

                            {/* Qty */}
                            <td>
                                <input
                                    type="number"
                                    name="quantity"
                                    step="any"
                                    value={formData.quantity}
                                    onChange={handleChange}
                                    className="bg-transparent border-b border-gray-600 focus:border-blue-500 outline-none w-full py-1 text-sm text-right text-gray-200 placeholder-gray-700 font-mono"
                                    placeholder="0"
                                />
                            </td>

                            {/* SL */}
                            <td>
                                <input
                                    type="number"
                                    name="drop_threshold_for_buy"
                                    step="any"
                                    value={formData.drop_threshold_for_buy}
                                    onChange={handleChange}
                                    className="bg-transparent border-b border-gray-600 focus:border-red-500 outline-none w-full py-1 text-sm text-right text-red-400 placeholder-gray-700 font-mono"
                                    placeholder="SL"
                                />
                            </td>

                            {/* TP */}
                            <td>
                                <input
                                    type="number"
                                    name="gain_threshold_for_sell"
                                    step="any"
                                    value={formData.gain_threshold_for_sell}
                                    onChange={handleChange}
                                    className="bg-transparent border-b border-gray-600 focus:border-blue-500 outline-none w-full py-1 text-sm text-right text-blue-400 placeholder-gray-700 font-mono"
                                    placeholder="TP"
                                />
                            </td>

                            {/* Time */}
                            <td>
                                <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="bg-transparent border-b border-gray-600 focus:border-blue-500 outline-none w-full py-1 text-xs text-gray-400 font-mono"
                                />
                            </td>

                            {/* Sell Price (Exit) */}
                            <td className="relative">
                                <input
                                    type="number"
                                    name="sell_price"
                                    step="any"
                                    value={formData.sell_price}
                                    onChange={handleChange}
                                    className="bg-transparent border-b border-gray-600 focus:border-purple-500 outline-none w-full py-1 text-sm text-right text-purple-400 placeholder-gray-700 font-mono"
                                    placeholder="Exit"
                                />
                                {formData.sell_price && formData.buy_price && (
                                    <div className={`absolute top-0 right-0 -mt-3 text-[9px] font-bold ${(Number(formData.sell_price) - Number(formData.buy_price)) * Number(formData.quantity || 0) >= 0
                                        ? 'text-green-500'
                                        : 'text-red-500'
                                        }`}>
                                        ${((Number(formData.sell_price) - Number(formData.buy_price)) * Number(formData.quantity || 1)).toFixed(2)}
                                    </div>
                                )}
                            </td>

                            {/* Actions */}
                            <td>
                                <div className="flex items-center justify-end gap-2">
                                    {initialData && (
                                        <button
                                            type="button"
                                            onClick={onSuccess}
                                            className="text-xs text-gray-500 hover:text-white underline"
                                        >
                                            Cancel
                                        </button>
                                    )}
                                    <button
                                        type="submit"
                                        className="bg-blue-600 hover:bg-blue-500 text-white text-xs px-3 py-1.5 rounded font-medium transition-colors"
                                    >
                                        {initialData ? 'Update' : 'Add'}
                                    </button>
                                </div>
                            </td>
                        </tr>
                        {/* Notes Row */}
                        <tr>
                            <td colSpan={8} className="pt-2 border-t border-gray-800">
                                <input
                                    type="text"
                                    name="notes"
                                    value={formData.notes}
                                    onChange={handleChange}
                                    placeholder="Add strategy notes here..."
                                    className="bg-transparent w-full text-xs text-gray-400 italic outline-none placeholder-gray-700"
                                />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>
        </div>
    );
}
