import React, { useState, useEffect, useCallback } from 'react';
import { Modal } from '../Modal';
import { Button } from '../Button';
import { Edit, Trash2, Plus } from 'lucide-react';
import { DiluentRegistrationModal } from './DiluentRegistrationModal';
import { getDataSheets, deleteDataSheet } from '../../services/dataSheetService';
import type { TechnicalDataSheet } from '../../types';
import { useAuth } from '../../context/useAuth';
import { useToast } from '../../hooks/useToast';

interface DiluentListModalProps {
    isOpen: boolean;
    onClose: () => void;
}

export const DiluentListModal: React.FC<DiluentListModalProps> = ({ isOpen, onClose }) => {
    const { isAdmin } = useAuth();
    const { showToast } = useToast();
    const [diluents, setDiluents] = useState<TechnicalDataSheet[]>([]);
    const [loading, setLoading] = useState(false);

    // State for the registration/edit modal
    const [showFormModal, setShowFormModal] = useState(false);
    const [selectedDiluent, setSelectedDiluent] = useState<TechnicalDataSheet | undefined>(undefined);

    const fetchDiluents = useCallback(async () => {
        setLoading(true);
        try {
            const response = await getDataSheets();
            // Filter only THINNER types
            const filtered = response.data.filter(ds =>
                ds.type === 'THINNER' || ds.type === 'DILUENTE'
            );
            setDiluents(filtered);
        } catch (error) {
            console.error('Error fetching diluents:', error);
            showToast('Erro ao carregar lista de diluentes.', 'error');
        } finally {
            setLoading(false);
        }
    }, [showToast]);

    useEffect(() => {
        if (isOpen) {
            fetchDiluents();
        }
    }, [isOpen, fetchDiluents]);

    const handleDelete = async (id: string, name: string) => {
        if (confirm(`Tem certeza que deseja excluir o diluente "${name}" ? `)) {
            try {
                await deleteDataSheet(id);
                showToast('Diluente excluído com sucesso.', 'success');
                fetchDiluents();
            } catch (error) {
                console.error('Error deleting diluent:', error);
                showToast('Erro ao excluir diluente.', 'error');
            }
        }
    };

    const handleEdit = (diluent: TechnicalDataSheet) => {
        setSelectedDiluent(diluent);
        setShowFormModal(true);
    };

    const handleNew = () => {
        setSelectedDiluent(undefined);
        setShowFormModal(true);
    };

    return (
        <>
            <Modal
                isOpen={isOpen}
                onClose={onClose}
                title="Gerenciar Diluentes"
                maxWidth="max-w-4xl"
            >
                <div className="space-y-4">
                    <div className="flex justify-between items-center">
                        <p className="text-text-muted text-sm">
                            Lista de diluentes cadastrados no sistema.
                        </p>
                        {isAdmin() && (
                            <Button onClick={handleNew} className="flex items-center gap-2">
                                <Plus size={16} />
                                Novo Diluente
                            </Button>
                        )}
                    </div>

                    <div className="bg-surface rounded-xl border border-border/40 overflow-hidden">
                        {loading ? (
                            <div className="p-8 text-center text-text-muted">Carregando...</div>
                        ) : diluents.length === 0 ? (
                            <div className="p-8 text-center text-text-muted">Nenhum diluente encontrado.</div>
                        ) : (
                            <div className="overflow-x-auto">
                                <table className="w-full">
                                    <thead className="bg-surface-soft border-b border-border/40">
                                        <tr>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-text-muted uppercase">Nome</th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-text-muted uppercase">Fabricante</th>
                                            <th className="px-6 py-3 text-left text-xs font-bold text-text-muted uppercase">Estoque Mín.</th>
                                            <th className="px-6 py-3 text-right text-xs font-bold text-text-muted uppercase">Ações</th>
                                        </tr>
                                    </thead>
                                    <tbody className="divide-y divide-border/40">
                                        {diluents.map((diluent) => (
                                            <tr key={diluent._id || diluent.id} className="hover:bg-surface-hover transition-colors">
                                                <td className="px-6 py-3 text-sm font-medium text-text-main">
                                                    {diluent.name}
                                                </td>
                                                <td className="px-6 py-3 text-sm text-text-secondary">
                                                    {diluent.manufacturer}
                                                    {diluent.manufacturerCode && (
                                                        <span className="text-xs text-text-muted block">
                                                            {diluent.manufacturerCode}
                                                        </span>
                                                    )}
                                                </td>
                                                <td className="px-6 py-3 text-sm text-text-secondary">
                                                    {diluent.minStock ? `${diluent.minStock} L` : '-'}
                                                </td>
                                                <td className="px-6 py-3 text-right flex justify-end gap-2">
                                                    {isAdmin() && (
                                                        <>
                                                            <button
                                                                onClick={() => handleEdit(diluent)}
                                                                className="p-1.5 text-primary hover:bg-primary/10 rounded-lg transition-colors"
                                                                title="Editar"
                                                            >
                                                                <Edit size={16} />
                                                            </button>
                                                            <button
                                                                onClick={() => handleDelete(diluent._id || diluent.id, diluent.name)}
                                                                className="p-1.5 text-red-500 hover:bg-red-500/10 rounded-lg transition-colors"
                                                                title="Excluir"
                                                            >
                                                                <Trash2 size={16} />
                                                            </button>
                                                        </>
                                                    )}
                                                </td>
                                            </tr>
                                        ))}
                                    </tbody>
                                </table>
                            </div>
                        )}
                    </div>

                    <div className="flex justify-end pt-4">
                        <Button variant="ghost" onClick={onClose}>
                            Fechar
                        </Button>
                    </div>
                </div>
            </Modal>

            {showFormModal && (
                <DiluentRegistrationModal
                    isOpen={showFormModal}
                    onClose={() => setShowFormModal(false)}
                    onSuccess={() => {
                        fetchDiluents();
                        setShowFormModal(false);
                    }}
                    initialData={selectedDiluent}
                />
            )}
        </>
    );
};
