import React, { useState } from 'react';
import { Modal } from '../Modal';
import { Input } from '../Input';
import { Button } from '../Button';
import { Select } from '../Select';
import { stockService, type StockItem } from '../../services/stockService';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';

interface StockOutModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: () => void;
    item: StockItem;
}

export const StockOutModal: React.FC<StockOutModalProps> = ({ isOpen, onClose, onSuccess, item }) => {
    const { isGuest } = useAuth();
    const { showGuestWarning } = useToast();
    const [loading, setLoading] = useState(false);
    const [type, setType] = useState<'CONSUMPTION' | 'ADJUSTMENT'>('CONSUMPTION');
    const [quantity, setQuantity] = useState('');

    // Adjustment fields
    const [reason, setReason] = useState('');

    // Consumption fields
    const [requester, setRequester] = useState('');
    const [date, setDate] = useState(new Date().toISOString().split('T')[0]);

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

        if (isGuest()) {
            showGuestWarning();
            return;
        }

        const qtyNum = Number(quantity);
        if (!qtyNum || qtyNum <= 0) {
            alert('Quantidade deve ser maior que zero.');
            return;
        }

        if (type === 'ADJUSTMENT' && !reason) {
            alert('Motivo é obrigatório para ajustes.');
            return;
        }

        if (type === 'CONSUMPTION' && !requester) {
            alert('Solicitante é obrigatório para consumo.');
            return;
        }

        setLoading(true);

        try {
            if (type === 'ADJUSTMENT') {
                // Adjust can be positive or negative, but here we frame it as "Stock Out" mostly?
                // Actually the requirement is "Two systems of Stock Out". So Adjustment implies REMOVING?
                // Or "Correction" which could be adding? 
                // Let's assume this modal is generic, but usually used for outs.
                // However, "Baixa por ajuste técnico" implies reducing. 
                // But typically adjustment allows both. Let's send negative quantity for reducing.

                await stockService.adjust(item._id!, {
                    quantityDelta: -qtyNum, // Negative for removal
                    reason
                });
            } else {
                await stockService.consume(item._id!, {
                    quantityConsumed: qtyNum,
                    requester,
                    date
                });
            }
            onSuccess();
        } catch (error: any) {
            console.error('Error processing stock out:', error);
            alert(error.response?.data?.error || 'Erro ao realizar baixa.');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal
            isOpen={isOpen}
            onClose={onClose}
            title={`Realizar Baixa - ${item.rrNumber}`}
        >
            <form onSubmit={handleSubmit} className="space-y-4">
                <div className="bg-surface-soft p-4 rounded-xl border border-border/40 mb-4">
                    <p className="text-sm font-semibold text-text-muted">Item Selecionado:</p>
                    <p className="text-lg font-bold text-text-main">
                        {typeof item.dataSheetId === 'object' ? item.dataSheetId.name : 'Produto'}
                    </p>
                    <p className="text-sm text-text-secondary">Lote: {item.batchNumber} | Cor: {item.color || '-'}</p>
                    <p className="text-sm text-text-secondary mt-1">
                        Disponível: <span className="font-bold text-green-500">{item.quantity} {item.unit}</span>
                    </p>
                </div>

                <Select
                    label="Tipo de Baixa"
                    name="type"
                    value={type}
                    onChange={(e) => setType(e.target.value as any)}
                    options={[
                        { label: 'Consumo em Obra', value: 'CONSUMPTION' },
                        { label: 'Ajuste Técnico / Perda', value: 'ADJUSTMENT' }
                    ]}
                />

                <Input
                    label="Quantidade a Baixar"
                    name="quantity"
                    type="number"
                    value={quantity}
                    onChange={(e) => setQuantity(e.target.value)}
                    required
                    placeholder={`Max: ${item.quantity}`}
                />

                {type === 'ADJUSTMENT' ? (
                    <Input
                        label="Motivo do Ajuste"
                        name="reason"
                        value={reason}
                        onChange={(e) => setReason(e.target.value)}
                        placeholder="Ex: Material vencido, Pote danificado, Desperdício teste..."
                        required
                    />
                ) : (
                    <>
                        <Input
                            label="Solicitante (Encarregado/Pintor)"
                            name="requester"
                            value={requester}
                            onChange={(e) => setRequester(e.target.value)}
                            required
                        />
                        <Input
                            label="Data do Consumo"
                            name="date"
                            type="date"
                            value={date}
                            onChange={(e) => setDate(e.target.value)}
                            required
                        />
                    </>
                )}

                <div className="flex justify-end gap-2 mt-6">
                    <Button type="button" variant="ghost" onClick={onClose} disabled={loading}>
                        Cancelar
                    </Button>
                    <Button type="submit" variant="danger" disabled={loading}>
                        {loading ? 'Processando...' : 'Confirmar Baixa'}
                    </Button>
                </div>
            </form>
        </Modal>
    );
};
