import React, { useState, useEffect } from 'react';
import { Modal } from '../Modal';
import { Input } from '../Input';
import { Button } from '../Button';
import { Select } from '../Select';
import { Trash2, Plus, Box, Calculator } from 'lucide-react';
import api from '../../services/api';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';
import { type ApplicationRecord, type Part, type Inspection } from '../../types';

interface CreateControlRecordModalProps {
    isOpen: boolean;
    onClose: () => void;
    onSuccess: () => void;
    projectId: string;
    initialData?: ApplicationRecord;
    availableParts: Part[];
    existingRecords?: ApplicationRecord[];
    availableBatches?: Inspection[];
}

interface BatchItem {
    partId: string;
    quantity: number; // This is now WEIGHT in KG
}

export const CreateControlRecordModal: React.FC<CreateControlRecordModalProps> = ({
    isOpen, onClose, onSuccess, projectId, initialData, availableParts, existingRecords = [], availableBatches = []
}) => {
    const { isGuest } = useAuth();
    const { showGuestWarning } = useToast();
    const [loading, setLoading] = useState(false);

    // Batch Composition State
    const [items, setItems] = useState<BatchItem[]>([]);
    const [selectedPartId, setSelectedPartId] = useState('');
    const [quantity, setQuantity] = useState('');

    const [formData, setFormData] = useState({
        coatStage: '',
        pieceDescription: '',
        date: '',
        operator: '',
        realWeight: '',
        volumeUsed: '',
        areaPainted: '',
        wetThicknessAvg: '',
        dryThicknessCalc: '',
        method: '',
        diluentUsed: '',
        notes: ''
    });

    useEffect(() => {
        if (initialData) {
            setFormData({
                coatStage: initialData.coatStage || '',
                pieceDescription: initialData.pieceDescription || '',
                date: initialData.date ? new Date(initialData.date).toISOString().split('T')[0] : '',
                operator: initialData.operator || '',
                realWeight: initialData.realWeight?.toString() || '',
                volumeUsed: initialData.volumeUsed?.toString() || '',
                areaPainted: initialData.areaPainted?.toString() || '',
                wetThicknessAvg: initialData.wetThicknessAvg?.toString() || '',
                dryThicknessCalc: initialData.dryThicknessCalc?.toString() || '',
                method: initialData.method || '',
                diluentUsed: initialData.diluentUsed?.toString() || '',
                notes: initialData.notes || ''
            });
            // Use existing items if available
            setItems(initialData.items || []);
        } else {
            setFormData({
                coatStage: '',
                pieceDescription: '',
                date: '',
                operator: '',
                realWeight: '',
                volumeUsed: '',
                areaPainted: '',
                wetThicknessAvg: '',
                dryThicknessCalc: '',
                method: '',
                diluentUsed: '',
                notes: ''
            });
            setItems([]);
        }
        setSelectedPartId('');
        setQuantity('');
    }, [initialData, isOpen]);

    const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
        setFormData({ ...formData, [e.target.name]: e.target.value });
    };

    const getPartBalance = (partId: string): number => {
        const part = availableParts.find(p => p.id === partId);
        if (!part) return 0;

        // Total estimated weight of the part/lot
        const totalEstimatedWeight = part.weight || 0;

        // Sum of weight already used in OTHER records (exclude current record if editing)
        let usedWeight = 0;
        existingRecords.forEach(record => {
            // If we are editing, ignore the current record's usage from the "existing" sum
            // so we don't double count or block the user from keeping the same value.
            if (initialData && record.id === initialData.id) return;

            const recordItems = record.items || [];
            recordItems.forEach(item => {
                if (item.partId === partId) {
                    usedWeight += item.quantity;
                }
            });
        });

        // Also subtract weight currently in the staging list (items) BUT exclude the one we might be adding/editing? 
        // Actually, `items` state reflects the *current* session. 
        // If we add multiple chunks of the same part in one session (unlikely but possible), we should sum them up.
        // For simple validation of "Next Add", we check: (Used + CurrentItems + NewAmount) <= Total

        const currentSessionWeight = items
            .filter(i => i.partId === partId)
            .reduce((sum, i) => sum + i.quantity, 0);

        return totalEstimatedWeight - (usedWeight + currentSessionWeight);
    };

    const addItem = () => {
        if (!selectedPartId || !quantity || Number(quantity) <= 0) return;

        const weightToAdd = Number(quantity);
        const part = availableParts.find(p => p.id === selectedPartId);

        if (!part) return;

        // Validation Logic
        const balance = getPartBalance(selectedPartId);

        // Allow a small margin of error (e.g. 1%) or strict? 
        // User requested: "se extrapolar ... o sistema nao aceita"
        if (weightToAdd > balance) {
            alert(`Quantidade excede o saldo disponível para esta peça.\n\nEstimado Total: ${part.weight} kg\nSaldo Disponível: ${balance.toFixed(2)} kg`);
            return;
        }

        const newItem = { partId: selectedPartId, quantity: weightToAdd };
        const newItems = [...items, newItem];
        setItems(newItems);

        // Auto-calc totals
        updateTotals(newItems);

        setSelectedPartId('');
        setQuantity('');
    };

    const removeItem = (index: number) => {
        const newItems = items.filter((_, i) => i !== index);
        setItems(newItems);
        updateTotals(newItems);
    };

    const updateTotals = (currentItems: BatchItem[]) => {
        let totalWeight = 0;
        let totalArea = 0;

        currentItems.forEach(item => {
            const part = availableParts.find(p => p.id === item.partId);
            if (part && part.weight && part.weight > 0) {
                // Item quantity IS the weight now
                const weightUsed = item.quantity;
                totalWeight += weightUsed;

                // Calculate area proportional to weight used based on part definition
                // Area Ratio = Total Area / Total Weight
                // Used Area = Weight Used * Ratio
                const areaRatio = (part.area || 0) / part.weight;
                totalArea += weightUsed * areaRatio;
            }
        });

        setFormData(prev => ({
            ...prev,
            realWeight: totalWeight > 0 ? totalWeight.toFixed(1) : prev.realWeight,
            areaPainted: totalArea > 0 ? totalArea.toFixed(1) : prev.areaPainted
        }));
    };

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

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

        setLoading(true);
        try {
            const payload = {
                ...formData,
                projectId,
                realWeight: parseFloat(formData.realWeight),
                volumeUsed: parseFloat(formData.volumeUsed),
                areaPainted: parseFloat(formData.areaPainted),
                wetThicknessAvg: parseFloat(formData.wetThicknessAvg),
                dryThicknessCalc: parseFloat(formData.dryThicknessCalc),
                diluentUsed: parseFloat(formData.diluentUsed),
                items: items.map(i => ({ partId: i.partId, quantity: Number(i.quantity) }))
            };

            if (initialData) {
                await api.put(`/application-records/${initialData.id}`, payload);
            } else {
                await api.post('/application-records', payload);
            }

            onSuccess();
            onClose();
        } catch (error) {
            console.error('Error saving record', error);
            alert('Erro ao salvar registro');
        } finally {
            setLoading(false);
        }
    };

    return (
        <Modal isOpen={isOpen} onClose={onClose} title={initialData ? "Editar Lote de Pintura" : "Novo Lote de Pintura"}>
            <form onSubmit={handleSubmit} className="space-y-4">

                {/* Batch Identification */}
                <div className="p-4 bg-surface-soft rounded-xl border border-border/40 space-y-4">
                    <div className="flex items-center gap-2 mb-2 pb-2 border-b border-border/20">
                        <Box className="w-4 h-4 text-primary" />
                        <span className="text-xs font-bold text-text-muted uppercase tracking-widest">Identificação do Lote</span>
                    </div>

                    {availableBatches && availableBatches.length > 0 ? (
                        <div className="space-y-2">
                            <Select
                                name="batchSelect"
                                label="Selecionar Lote (Inspeção)"
                                options={[
                                    { label: 'Selecione um lote...', value: '' },
                                    ...availableBatches.map(b => ({ label: (b.batch || '').split('(')[0].trim(), value: b.id })),
                                    { label: 'Outro / Manual', value: 'manual' }
                                ]}
                                onChange={(e) => {
                                    const val = e.target.value;
                                    if (val === 'manual' || val === '') {
                                        setFormData(prev => ({ ...prev, pieceDescription: '' }));
                                    } else {
                                        const selectedBatch = availableBatches.find(b => b.id === val);
                                        if (selectedBatch) {
                                            // Extract "Lote-XX" from "Lote-XX (date...)" if needed, or just use label
                                            // Calculate Avg EPS
                                            let avgEPS = '';
                                            if (selectedBatch.epsPoints && selectedBatch.epsPoints.length > 0) {
                                                // epsPoints are (number | null)[]
                                                const validPoints = selectedBatch.epsPoints.filter(p => p !== null && p > 0) as number[];
                                                if (validPoints.length > 0) {
                                                    const sum = validPoints.reduce((a, b) => a + b, 0);
                                                    avgEPS = (sum / validPoints.length).toFixed(1);
                                                }
                                            }

                                            setFormData(prev => ({
                                                ...prev,
                                                pieceDescription: selectedBatch.batch || '',
                                                dryThicknessCalc: avgEPS
                                                // wetThicknessAvg: ... Need solidsVolume etc.
                                            }));
                                        }
                                    }
                                }}
                                value={availableBatches.find(b => b.batch === formData.pieceDescription)?.id || (formData.pieceDescription ? 'manual' : '')}
                            />
                            {((!availableBatches.some(b => b.batch === formData.pieceDescription) && formData.pieceDescription !== '') || (availableBatches.find(b => b.batch === formData.pieceDescription)?.id === undefined && formData.pieceDescription === '') || formData.pieceDescription === '') && (
                                <div className={availableBatches.some(b => b.batch === formData.pieceDescription) ? 'hidden' : ''}>
                                    <Input
                                        name="pieceDescription"
                                        placeholder="Ou digite manualmente..."
                                        value={formData.pieceDescription}
                                        onChange={handleChange}
                                    />
                                </div>
                            )}
                        </div>
                    ) : (
                        <Input
                            name="pieceDescription"
                            label="Nome/Número do Lote"
                            placeholder="Ex: Lote 01/2024 - Estrutura Principal"
                            value={formData.pieceDescription}
                            onChange={handleChange}

                        />
                    )}

                    <div className="grid grid-cols-2 gap-4">
                        <Select
                            name="coatStage"
                            label="Demão Aplicada"
                            options={[
                                { label: 'Primer / Fundo', value: 'primer' },
                                { label: 'Intermediária', value: 'intermediate' },
                                { label: 'Acabamento', value: 'finish' },
                                { label: 'Stripe Coat', value: 'stripe_coat' }
                            ]}
                            value={formData.coatStage}
                            onChange={handleChange}
                        />
                        <Input name="date" label="Data de Aplicação" type="date" value={formData.date} onChange={handleChange} />
                    </div>
                </div>

                {/* Batch Composition */}
                <div className="p-4 bg-primary/5 rounded-xl border border-primary/10 space-y-4">
                    <div className="flex items-center justify-between mb-2">
                        <div className="flex items-center gap-2">
                            <Calculator className="w-4 h-4 text-primary" />
                            <span className="text-xs font-bold text-text-muted uppercase tracking-widest">Composição do Lote</span>
                        </div>
                        <span className="text-[10px] text-text-muted bg-white/50 px-2 py-1 rounded-md">
                            {items.length} itens adicionados
                        </span>
                    </div>

                    <div className="grid grid-cols-[1fr_80px_auto] gap-2 items-end">
                        <Select
                            name="partSelector"
                            label="Adicionar Peça / Geometria"
                            options={availableParts.map(p => {
                                // Calculate balance for display if needed, but keeping it simple for select
                                return {
                                    label: `${p.description} (Total: ${p.weight}kg)`,
                                    value: p.id
                                };
                            })}
                            value={selectedPartId}
                            onChange={(e) => setSelectedPartId(e.target.value)}
                        />
                        <Input
                            name="qty"
                            label="Qtd (Kg)"
                            type="number"
                            min="0.1"
                            step="0.1"
                            value={quantity}
                            onChange={(e) => setQuantity(e.target.value)}
                        />
                        <Button type="button" onClick={addItem} size="sm" className="h-10 w-10 mb-0.5 px-0" title="Adicionar Item" aria-label="Adicionar Item">
                            <Plus size={18} />
                        </Button>
                    </div>

                    {/* Items List */}
                    {items.length > 0 && (
                        <div className="bg-surface rounded-lg border border-border/40 overflow-hidden max-h-40 overflow-y-auto">
                            <table className="w-full text-xs text-left">
                                <thead className="bg-surface-soft text-text-muted font-bold uppercase sticky top-0">
                                    <tr>
                                        <th className="px-3 py-2">Peça</th>
                                        <th className="px-3 py-2 text-center">Peso Lançado</th>
                                        <th className="px-3 py-2 text-right">Área Calc.</th>
                                        <th className="w-8"></th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border/20">
                                    {items.map((item, idx) => {
                                        const part = availableParts.find(p => p.id === item.partId);
                                        if (!part) return null;

                                        const areaRatio = (part.weight && part.weight > 0) ? ((part.area || 0) / part.weight) : 0;
                                        const areaCalculated = item.quantity * areaRatio;

                                        return (
                                            <tr key={idx} className="hover:bg-surface-hover/50">
                                                <td className="px-3 py-2 truncate max-w-[150px]">{part.description}</td>
                                                <td className="px-3 py-2 text-center font-bold text-primary">{item.quantity.toFixed(1)} kg</td>
                                                <td className="px-3 py-2 text-right text-text-muted">
                                                    {areaCalculated.toFixed(2)} m²
                                                </td>
                                                <td className="px-3 py-2 text-right">
                                                    <button
                                                        type="button"
                                                        onClick={() => removeItem(idx)}
                                                        className="text-text-muted hover:text-error transition-colors"
                                                        title="Remover Item"
                                                        aria-label="Remover Item"
                                                    >
                                                        <Trash2 size={12} />
                                                    </button>
                                                </td>
                                            </tr>
                                        );
                                    })}
                                </tbody>
                            </table>
                        </div>
                    )}
                </div>

                {/* Calculated Results / Manual Override */}
                <div className="grid grid-cols-2 gap-4">
                    <div className="relative">
                        <Input name="areaPainted" label="Área Total (m²)" type="number" step="0.1" value={formData.areaPainted} onChange={handleChange} />
                        {items.length > 0 && <div className="absolute top-0 right-0 text-[9px] text-green-600 font-bold bg-green-100 px-1.5 py-0.5 rounded">Calculado</div>}
                    </div>
                    <div className="relative">
                        <Input name="realWeight" label="Peso Total (kg)" type="number" step="0.1" value={formData.realWeight} onChange={handleChange} />
                        {items.length > 0 && <div className="absolute top-0 right-0 text-[9px] text-green-600 font-bold bg-green-100 px-1.5 py-0.5 rounded">Calculado</div>}
                    </div>
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <Input name="volumeUsed" label="Volume de Tinta Gasto (L)" type="number" step="0.1" value={formData.volumeUsed} onChange={handleChange} />
                    <Input name="diluentUsed" label="Diluente (L)" type="number" step="0.1" value={formData.diluentUsed} onChange={handleChange} />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <Input name="operator" label="Pintor Responsável" value={formData.operator} onChange={handleChange} />
                    <Select
                        name="method"
                        label="Método de Aplicação"
                        options={[
                            { label: 'Pistola Airless', value: 'airless' },
                            { label: 'Pistola Convencional', value: 'conventional' },
                            { label: 'Rolo / Trincha', value: 'roller' },
                        ]}
                        value={formData.method}
                        onChange={handleChange}
                    />
                </div>

                <div className="grid grid-cols-2 gap-4">
                    <Input name="wetThicknessAvg" label="Esp. Úmida (μm)" type="number" value={formData.wetThicknessAvg} onChange={handleChange} />
                    <Input name="dryThicknessCalc" label="Esp. Seca Calc (μm)" type="number" value={formData.dryThicknessCalc} onChange={handleChange} />
                </div>

                <div className="flex flex-col gap-1 w-full">
                    <label className="text-[10px] font-bold text-primary uppercase tracking-[0.15em] ml-1 mb-1">Observações</label>
                    <textarea
                        name="notes"
                        aria-label="Observações"
                        className="flex min-h-[80px] w-full rounded-xl border bg-[var(--input-bg)] border-[var(--input-border)] text-[var(--input-text)] px-4 py-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary disabled:opacity-50 transition-all font-medium placeholder:text-[var(--input-placeholder)]"
                        value={formData.notes}
                        onChange={handleChange}
                    />
                </div>

                <div className="flex justify-end gap-2 mt-6">
                    <Button type="button" variant="ghost" onClick={onClose} disabled={loading}>Cancelar</Button>
                    <Button type="submit" disabled={loading}>{loading ? 'Salvando...' : (initialData ? 'Salvar Edição' : 'Criar Lote')}</Button>
                </div>
            </form>
        </Modal>
    );
};
