import { useState, useCallback } from 'react';
import { getSellHistory, addSellHistory, updateSellHistory, deleteSellHistory } from '../../../api';
import { emptySellForm, toLocalDatetimeValue } from '../stockUtils';

export default function useSellHistory() {
    const [sellHistory, setSellHistory] = useState([]);
    const [sellHistoryLoading, setSellHistoryLoading] = useState(false);
    const [sellHistoryBroker, setSellHistoryBroker] = useState('ALL');
    const [sellHistoryPeriod, setSellHistoryPeriod] = useState('3M');

    const [sellDrawerOpen, setSellDrawerOpen] = useState(false);

    const [sellFormOpen, setSellFormOpen] = useState(false);
    const [sellEditId, setSellEditId] = useState(null);
    const [sellForm, setSellForm] = useState(emptySellForm());
    const [sellFormSaving, setSellFormSaving] = useState(false);
    const [sellFormError, setSellFormError] = useState('');

    const loadSellHistory = useCallback(async () => {
        setSellHistoryLoading(true);
        try {
            const data = await getSellHistory();
            setSellHistory(data?.records ?? (Array.isArray(data) ? data : []));
        } catch {
            /* 백엔드 미구현 시 빈 배열 유지 */
        } finally {
            setSellHistoryLoading(false);
        }
    }, []);

    /** 매도 후 실현손익 기록 추가 (usePortfolio.handleSell에서 호출) */
    const addSellRecord = async (record) => {
        try {
            const saved = await addSellHistory(record);
            setSellHistory((prev) => [saved ?? record, ...prev]);
        } catch {
            setSellHistory((prev) => [{ ...record, id: Date.now() }, ...prev]);
        }
    };

    const handleDeleteSellRecord = async (id) => {
        setSellHistory((prev) => prev.filter((r) => r.id !== id));
        try {
            await deleteSellHistory(id);
        } catch {
            loadSellHistory();
        }
    };

    const handleSellFormOpen = () => {
        setSellEditId(null);
        setSellForm(emptySellForm());
        setSellFormError('');
        setSellFormOpen(true);
    };

    const handleSellEditStart = (record) => {
        setSellEditId(record.id);
        setSellForm({
            broker: record.broker ?? '',
            ticker: record.ticker ?? '',
            name: record.name ?? '',
            quantity: String(record.quantity ?? ''),
            avg_price: String(record.avg_price ?? ''),
            sell_price: String(record.sell_price ?? ''),
            commission: String(record.commission ?? ''),
            sold_at: toLocalDatetimeValue(record.sold_at),
        });
        setSellFormError('');
        setSellFormOpen(true);
    };

    const handleSellFormClose = () => {
        setSellFormOpen(false);
        setSellEditId(null);
        setSellFormError('');
    };

    const handleSellFormSubmit = async (e) => {
        e.preventDefault();
        setSellFormSaving(true);
        setSellFormError('');

        const qty = Number(sellForm.quantity);
        const avgPrice = Number(sellForm.avg_price);
        const sellPrice = Number(sellForm.sell_price);
        const commission = Number(sellForm.commission) || 0;
        const buyAmount = avgPrice * qty;
        const sellAmount = sellPrice * qty;
        const realizedProfit = sellAmount - buyAmount - commission;
        const realizedRate = buyAmount > 0 ? (realizedProfit / buyAmount) * 100 : 0;

        const payload = {
            broker: sellForm.broker.trim(),
            ticker: sellForm.ticker.trim(),
            name: sellForm.name.trim(),
            quantity: qty, avg_price: avgPrice, sell_price: sellPrice, commission,
            buy_amount: buyAmount, sell_amount: sellAmount,
            realized_profit: realizedProfit, realized_rate: realizedRate,
            sold_at: sellForm.sold_at ? new Date(sellForm.sold_at).toISOString() : new Date().toISOString(),
        };

        try {
            if (sellEditId != null) {
                const updated = await updateSellHistory(sellEditId, payload);
                setSellHistory((prev) =>
                    prev.map((r) => (r.id === sellEditId ? (updated ?? { ...payload, id: sellEditId }) : r))
                );
            } else {
                const saved = await addSellHistory(payload);
                setSellHistory((prev) => [saved ?? { ...payload, id: Date.now() }, ...prev]);
            }
            handleSellFormClose();
        } catch (err) {
            setSellFormError(err?.message ?? String(err));
        } finally {
            setSellFormSaving(false);
        }
    };

    return {
        sellHistory, sellHistoryLoading, loadSellHistory, addSellRecord,
        sellHistoryBroker, setSellHistoryBroker,
        sellHistoryPeriod, setSellHistoryPeriod,
        sellDrawerOpen, setSellDrawerOpen,
        sellFormOpen, sellEditId, sellForm, setSellForm,
        sellFormSaving, sellFormError,
        handleDeleteSellRecord,
        handleSellFormOpen, handleSellEditStart, handleSellFormClose, handleSellFormSubmit,
    };
}
