import React, { useState, useEffect, useCallback } from 'react';
import api from '../services/api';
import type { IInstrument, CreateInstrumentDTO } from '../types/Instrument';
import { Plus, Search, Edit2, Trash2, Calendar, Gauge, XCircle } from 'lucide-react';
import { useAuth } from '../context/useAuth';
import { useToast } from '../context/ToastContext';

const InstrumentList: React.FC = () => {
    const [instruments, setInstruments] = useState<IInstrument[]>([]);
    const [loading, setLoading] = useState(true);
    const [searchTerm, setSearchTerm] = useState('');
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [editingInstrument, setEditingInstrument] = useState<IInstrument | null>(null);
    const { showToast } = useToast();
    const { isAdmin } = useAuth();

    // Form State
    const [formData, setFormData] = useState<CreateInstrumentDTO>({
        name: '',
        type: '',
        manufacturer: '',
        modelName: '',
        serialNumber: '',
        calibrationDate: '',
        calibrationExpirationDate: '',
        status: 'active',
        notes: ''
    });

    const fetchInstruments = useCallback(async () => {
        try {
            setLoading(true);
            const response = await api.get('/instruments');
            setInstruments(response.data);
        } catch (error) {
            console.error('Failed to fetch instruments', error);
            showToast('Erro ao carregar instrumentos', 'error');
        } finally {
            setLoading(false);
        }
    }, [showToast]);

    useEffect(() => {
        fetchInstruments();
    }, [fetchInstruments]);

    const handleOpenModal = (instrument?: IInstrument) => {
        if (instrument) {
            setEditingInstrument(instrument);
            setFormData({
                name: instrument.name,
                type: instrument.type,
                manufacturer: instrument.manufacturer || '',
                modelName: instrument.modelName || '',
                serialNumber: instrument.serialNumber,
                calibrationDate: instrument.calibrationDate ? instrument.calibrationDate.split('T')[0] : '',
                calibrationExpirationDate: instrument.calibrationExpirationDate ? instrument.calibrationExpirationDate.split('T')[0] : '',
                status: instrument.status,
                notes: instrument.notes || ''
            });
        } else {
            setEditingInstrument(null);
            setFormData({
                name: '',
                type: '',
                manufacturer: '',
                modelName: '',
                serialNumber: '',
                calibrationDate: '',
                calibrationExpirationDate: '',
                status: 'active',
                notes: ''
            });
        }
        setIsModalOpen(true);
    };

    const handleDelete = async (id: string) => {
        if (!confirm('Tem certeza que deseja excluir este instrumento?')) return;
        try {
            await api.delete(`/instruments/${id}`);
            setInstruments(instruments.filter(i => i._id !== id));
            showToast('Instrumento excluído com sucesso', 'success');
        } catch (error) {
            console.error('Failed to delete instrument', error);
            showToast('Erro ao excluir instrumento', 'error');
        }
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            if (editingInstrument) {
                const response = await api.put(`/instruments/${editingInstrument._id}`, formData);
                setInstruments(instruments.map(i => i._id === editingInstrument._id ? response.data : i));
                showToast('Instrumento atualizado com sucesso', 'success');
            } else {
                const response = await api.post('/instruments', formData);
                setInstruments([...instruments, response.data]);
                showToast('Instrumento criado com sucesso', 'success');
            }
            setIsModalOpen(false);
        } catch (error) {
            console.error('Failed to save instrument', error);
            showToast('Erro ao salvar instrumento', 'error');
        }
    };

    const getStatusColor = (status: string) => {
        switch (status) {
            case 'active': return 'bg-green-500/10 text-green-500';
            case 'inactive': return 'bg-gray-500/10 text-gray-500';
            case 'maintenance': return 'bg-yellow-500/10 text-yellow-500';
            case 'expired': return 'bg-red-500/10 text-red-500';
            default: return 'bg-gray-500/10 text-gray-500';
        }
    };

    const getStatusLabel = (status: string) => {
        switch (status) {
            case 'active': return 'Ativo';
            case 'inactive': return 'Inativo';
            case 'maintenance': return 'Manutenção';
            case 'expired': return 'Vencido';
            default: return status;
        }
    };

    const filteredInstruments = instruments.filter(i =>
        i.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        i.serialNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
        i.type.toLowerCase().includes(searchTerm.toLowerCase())
    );

    return (
        <div className="space-y-6">
            <div className="flex justify-between items-center">
                <div>
                    <h1 className="text-2xl font-bold text-text-main">Instrumentos de Medição</h1>
                    <p className="text-text-muted text-sm">Gerencie seus instrumentos e calibrações</p>
                </div>
                {isAdmin() && (
                    <button
                        onClick={() => handleOpenModal()}
                        className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl hover:bg-primary-dark transition-colors shadow-lg shadow-primary/20"
                    >
                        <Plus size={20} />
                        Novo Instrumento
                    </button>
                )}
            </div>

            {/* Search Bar */}
            <div className="relative">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" size={20} />
                <input
                    type="text"
                    placeholder="Buscar por nome, serial ou tipo..."
                    value={searchTerm}
                    onChange={(e) => setSearchTerm(e.target.value)}
                    className="w-full pl-10 pr-4 py-3 bg-surface rounded-xl border border-border/40 focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                />
            </div>

            {/* List */}
            {loading ? (
                <div className="text-center py-10 text-text-muted">Carregando...</div>
            ) : filteredInstruments.length === 0 ? (
                <div className="text-center py-20 bg-surface rounded-2xl border border-border/40 border-dashed">
                    <Gauge size={48} className="mx-auto text-text-muted/50 mb-4" />
                    <h3 className="text-lg font-bold text-text-main">Nenhum instrumento encontrado</h3>
                    <p className="text-text-muted text-sm mt-1">Cadastre seus instrumentos para controlar a calibração.</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    {filteredInstruments.map((instrument) => (
                        <div key={instrument._id} className="bg-surface p-5 rounded-2xl border border-border/40 hover:border-primary/50 transition-all group">
                            <div className="flex justify-between items-start mb-4">
                                <div className="p-3 bg-primary/10 rounded-xl text-primary">
                                    <Gauge size={24} />
                                </div>
                                <span className={`px-2 py-1 rounded-lg text-xs font-bold uppercase ${getStatusColor(instrument.status)}`}>
                                    {getStatusLabel(instrument.status)}
                                </span>
                            </div>

                            <h3 className="text-lg font-bold text-text-main mb-1">{instrument.name}</h3>
                            <p className="text-sm text-text-muted mb-4">{instrument.type} • {instrument.manufacturer}</p>

                            <div className="space-y-2 mb-6">
                                <div className="flex items-center gap-2 text-sm text-text-secondary">
                                    <span className="font-mono bg-surface-hover px-1.5 rounded text-xs">S/N: {instrument.serialNumber}</span>
                                </div>
                                {instrument.calibrationExpirationDate && (
                                    <div className="flex items-center gap-2 text-sm">
                                        <Calendar size={14} className={new Date(instrument.calibrationExpirationDate) < new Date() ? "text-red-500" : "text-text-muted"} />
                                        <span className={new Date(instrument.calibrationExpirationDate) < new Date() ? "text-red-500 font-bold" : "text-text-secondary"}>
                                            Vence: {new Date(instrument.calibrationExpirationDate).toLocaleDateString()}
                                        </span>
                                    </div>
                                )}
                            </div>

                            {isAdmin() && (
                                <div className="flex gap-2 pt-4 border-t border-border/40">
                                    <button
                                        onClick={() => handleOpenModal(instrument)}
                                        className="flex-1 py-2 rounded-lg bg-surface-hover hover:bg-surface-hover/80 text-text-main text-sm font-semibold transition-colors flex items-center justify-center gap-2"
                                    >
                                        <Edit2 size={16} /> Editar
                                    </button>
                                    <button
                                        onClick={() => handleDelete(instrument._id)}
                                        className="p-2 rounded-lg hover:bg-red-500/10 text-text-muted hover:text-red-500 transition-colors"
                                        title="Excluir Instrumento"
                                        aria-label="Excluir Instrumento"
                                    >
                                        <Trash2 size={18} />
                                    </button>
                                </div>
                            )}
                        </div>
                    ))}
                </div>
            )}

            {/* Modal */}
            {isModalOpen && (
                <div className="fixed inset-0 bg-black/60 backdrop-blur-sm z-50 flex items-center justify-center p-4">
                    <div className="bg-surface w-full max-w-lg rounded-2xl shadow-2xl border border-border/40 p-6 animate-in fade-in zoom-in duration-200">
                        <div className="flex justify-between items-center mb-6">
                            <h2 className="text-xl font-bold text-text-main">
                                {editingInstrument ? 'Editar Instrumento' : 'Novo Instrumento'}
                            </h2>
                            <button onClick={() => setIsModalOpen(false)} className="text-text-muted hover:text-text-main" title="Fechar Modal">
                                <XCircle size={24} />
                            </button>
                        </div>

                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-xs font-bold text-text-muted uppercase mb-1">Nome</label>
                                    <input
                                        type="text"
                                        required
                                        value={formData.name}
                                        onChange={e => setFormData({ ...formData, name: e.target.value })}
                                        className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                        placeholder="Ex: Higrômetro"
                                    />
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-text-muted uppercase mb-1">Tipo</label>
                                    <input
                                        type="text"
                                        required
                                        value={formData.type}
                                        onChange={e => setFormData({ ...formData, type: e.target.value })}
                                        className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                        placeholder="Ex: Ambiental"
                                    />
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-xs font-bold text-text-muted uppercase mb-1">Fabricante</label>
                                    <input
                                        type="text"
                                        value={formData.manufacturer}
                                        onChange={e => setFormData({ ...formData, manufacturer: e.target.value })}
                                        className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                        placeholder="Ex: Minipa"
                                        title="Fabricante do instrumento"
                                    />
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-text-muted uppercase mb-1">Modelo</label>
                                    <input
                                        type="text"
                                        value={formData.modelName}
                                        onChange={e => setFormData({ ...formData, modelName: e.target.value })}
                                        className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                        placeholder="Ex: ET-2000"
                                        title="Modelo do instrumento"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-text-muted uppercase mb-1">Número de Série</label>
                                <input
                                    type="text"
                                    required
                                    value={formData.serialNumber}
                                    onChange={e => setFormData({ ...formData, serialNumber: e.target.value })}
                                    className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main font-mono"
                                    placeholder="Ex: 123456"
                                    title="Número de série"
                                />
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div>
                                    <label className="block text-xs font-bold text-text-muted uppercase mb-1">Data Calibração</label>
                                    <input
                                        type="date"
                                        value={formData.calibrationDate}
                                        onChange={e => setFormData({ ...formData, calibrationDate: e.target.value })}
                                        className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                        title="Data da última calibração"
                                    />
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-text-muted uppercase mb-1">Vencimento</label>
                                    <input
                                        type="date"
                                        value={formData.calibrationExpirationDate}
                                        onChange={e => setFormData({ ...formData, calibrationExpirationDate: e.target.value })}
                                        className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                        title="Data de vencimento da calibração"
                                    />
                                </div>
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-text-muted uppercase mb-1">Status</label>
                                <select
                                    value={formData.status}
                                    onChange={e => setFormData({ ...formData, status: e.target.value as IInstrument['status'] })}
                                    className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main"
                                    title="Status do instrumento"
                                >
                                    <option value="active">Ativo</option>
                                    <option value="inactive">Inativo</option>
                                    <option value="maintenance">Em Manutenção</option>
                                    <option value="expired">Vencido</option>
                                </select>
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-text-muted uppercase mb-1">Observações</label>
                                <textarea
                                    value={formData.notes}
                                    onChange={e => setFormData({ ...formData, notes: e.target.value })}
                                    rows={3}
                                    className="w-full px-3 py-2 bg-surface-soft rounded-lg border border-border/40 focus:border-primary outline-none text-text-main resize-none"
                                    placeholder="Observações adicionais..."
                                    title="Observações"
                                />
                            </div>

                            <div className="flex gap-3 pt-4">
                                <button
                                    type="button"
                                    onClick={() => setIsModalOpen(false)}
                                    className="flex-1 py-3 rounded-xl bg-surface-hover text-text-main font-bold hover:bg-surface-hover/80 transition-colors"
                                >
                                    Cancelar
                                </button>
                                <button
                                    type="submit"
                                    className="flex-1 py-3 rounded-xl bg-primary text-white font-bold hover:bg-primary-dark transition-colors shadow-lg shadow-primary/20"
                                >
                                    Salvar
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>
    );
};

export default InstrumentList;
