
import React, { useEffect, useState } from 'react';
import { CondoService } from '../services/mockDb';
import { Ticket, TicketStatus, TicketPriority, TicketCategory, TicketAttachment, TicketComment } from '../types';
import { MessageSquareWarning, Plus, Search, Filter, Paperclip, X, CheckCircle2, Clock, XCircle, FileIcon, Image as ImageIcon, Film, Send, PauseCircle, Archive, Trash2, User } from 'lucide-react';

export const TicketsPage: React.FC = () => {
    const user = CondoService.getCurrentUser();
    const isAdmin = user?.role === 'admin' || user?.role === 'poweruser';

    const [tickets, setTickets] = useState<Ticket[]>([]);
    const [loading, setLoading] = useState(true);
    
    // View Filters
    const [viewMode, setViewMode] = useState<'active' | 'archived'>('active');
    
    const [showModal, setShowModal] = useState(false);
    const [viewTicket, setViewTicket] = useState<Ticket | null>(null);
    const [submitting, setSubmitting] = useState(false);

    // Comments State
    const [comments, setComments] = useState<TicketComment[]>([]);
    const [newComment, setNewComment] = useState('');
    const [loadingComments, setLoadingComments] = useState(false);

    // Form State
    const [formTitle, setFormTitle] = useState('');
    const [formDesc, setFormDesc] = useState('');
    const [formCategory, setFormCategory] = useState<TicketCategory>(TicketCategory.OTHER);
    const [formPriority, setFormPriority] = useState<TicketPriority>(TicketPriority.MEDIUM);
    const [attachments, setAttachments] = useState<{fileName: string, fileType: string, data: string}[]>([]);
    
    // File Reading helper
    const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files && e.target.files.length > 0) {
            const newAttachments = [];
            for (let i = 0; i < e.target.files.length; i++) {
                const file = e.target.files[i];
                // Check size (e.g. 5MB limit per file for demo safety)
                if (file.size > 5 * 1024 * 1024) {
                    alert(`Il file ${file.name} è troppo grande (max 5MB)`);
                    continue;
                }
                
                const base64 = await new Promise<string>((resolve, reject) => {
                    const reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = () => resolve(reader.result as string);
                    reader.onerror = error => reject(error);
                });
                
                newAttachments.push({
                    fileName: file.name,
                    fileType: file.type,
                    data: base64
                });
            }
            setAttachments([...attachments, ...newAttachments]);
        }
    };

    const removeAttachment = (index: number) => {
        const newAtt = [...attachments];
        newAtt.splice(index, 1);
        setAttachments(newAtt);
    };

    const loadTickets = async () => {
        setLoading(true);
        try {
            const list = await CondoService.getTickets();
            setTickets(list);
            
            // Mark tickets page as viewed to clear badges
            localStorage.setItem('lastViewedTickets', Date.now().toString());
            window.dispatchEvent(new Event('tickets-viewed'));

        } catch (e) {
            console.error(e);
        } finally {
            setLoading(false);
        }
    };

    const loadComments = async (ticketId: string) => {
        setLoadingComments(true);
        try {
            const data = await CondoService.getTicketComments(ticketId);
            setComments(data);
        } catch(e) { console.error(e); }
        finally { setLoadingComments(false); }
    };

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

    useEffect(() => {
        if (viewTicket) {
            loadComments(viewTicket.id);
        } else {
            setComments([]);
        }
    }, [viewTicket]);

    const handleCreateSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setSubmitting(true);
        try {
            await CondoService.createTicket({
                title: formTitle,
                description: formDesc,
                category: formCategory,
                priority: formPriority,
                attachments: attachments
            });
            setShowModal(false);
            // Reset form
            setFormTitle('');
            setFormDesc('');
            setAttachments([]);
            loadTickets();
        } catch (e) {
            alert("Errore creazione ticket");
            console.error(e);
        } finally {
            setSubmitting(false);
        }
    };

    const handleStatusUpdate = async (status: TicketStatus) => {
        if (!viewTicket) return;
        try {
            await CondoService.updateTicket(viewTicket.id, {
                status: status,
                priority: viewTicket.priority
            });
            // Update local state
            const updated = { ...viewTicket, status };
            setViewTicket(updated);
            setTickets(tickets.map(t => t.id === updated.id ? updated : t));
        } catch (e) { console.error(e); }
    };
    
    const handleDeleteTicket = async (id: string) => {
        if (!confirm("Eliminare definitivamente questa segnalazione?")) return;
        try {
            await CondoService.deleteTicket(id);
            setTickets(tickets.filter(t => t.id !== id));
            setViewTicket(null);
        } catch (e: any) { alert(e.message || "Impossibile eliminare."); }
    };

    const handleSendComment = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!viewTicket || !newComment.trim()) return;
        
        try {
            await CondoService.addTicketComment(viewTicket.id, newComment);
            setNewComment('');
            loadComments(viewTicket.id);
        } catch(e) { console.error(e); }
    };

    // Filter Logic
    const filteredTickets = tickets.filter(t => {
        const isArchived = t.status === TicketStatus.RESOLVED || t.status === TicketStatus.CLOSED;
        if (viewMode === 'active') return !isArchived;
        return isArchived;
    });

    // Helpers for Badge Colors
    const getStatusColor = (s: TicketStatus) => {
        switch(s) {
            case TicketStatus.OPEN: return 'bg-blue-100 text-blue-700';
            case TicketStatus.IN_PROGRESS: return 'bg-yellow-100 text-yellow-700';
            case TicketStatus.SUSPENDED: return 'bg-orange-100 text-orange-700';
            case TicketStatus.RESOLVED: return 'bg-green-100 text-green-700';
            case TicketStatus.CLOSED: return 'bg-slate-200 text-slate-600';
        }
    };
    
    const getPriorityColor = (p: TicketPriority) => {
        switch(p) {
            case TicketPriority.LOW: return 'bg-slate-100 text-slate-600';
            case TicketPriority.MEDIUM: return 'bg-blue-50 text-blue-600';
            case TicketPriority.HIGH: return 'bg-orange-100 text-orange-600';
            case TicketPriority.URGENT: return 'bg-red-100 text-red-600';
        }
    };

    const getCategoryLabel = (c: TicketCategory) => {
        switch(c) {
            case TicketCategory.MAINTENANCE: return 'Manutenzione';
            case TicketCategory.ADMINISTRATIVE: return 'Amministrazione';
            case TicketCategory.CLEANING: return 'Pulizie';
            case TicketCategory.NOISE: return 'Disturbo';
            default: return 'Altro';
        }
    };

    const openAttachment = async (ticketId: string, attId: string) => {
        try {
            const file = await CondoService.getTicketAttachment(ticketId, attId);
            const win = window.open();
            if (win) {
                if (file.fileType.startsWith('image/')) {
                    win.document.write(`<img src="${file.data}" style="max-width:100%"/>`);
                } else if (file.fileType === 'application/pdf') {
                    win.document.write(`<iframe src="${file.data}" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>`);
                } else {
                     win.document.write(`<a href="${file.data}" download="${file.fileName}">Clicca qui per scaricare ${file.fileName}</a>`);
                }
            }
        } catch (e) { alert("Errore apertura file"); }
    };

    return (
        <div className="space-y-6 pb-20">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h2 className="text-2xl font-bold text-slate-800">Segnalazioni</h2>
                    <p className="text-slate-500">Gestisci guasti e richieste</p>
                </div>
                <button 
                    onClick={() => setShowModal(true)} 
                    className="bg-blue-600 text-white px-4 py-2 rounded-lg font-medium flex items-center gap-2 hover:bg-blue-700 transition-colors"
                >
                    <Plus className="w-5 h-5"/> Nuova Segnalazione
                </button>
            </div>

            {/* Main Tabs */}
            <div className="border-b border-slate-200">
                <div className="flex gap-4">
                    <button
                        onClick={() => setViewMode('active')}
                        className={`pb-2 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${viewMode === 'active' ? 'border-blue-600 text-blue-600' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
                    >
                        <Clock className="w-4 h-4"/>
                        In Corso
                    </button>
                    <button
                        onClick={() => setViewMode('archived')}
                        className={`pb-2 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 ${viewMode === 'archived' ? 'border-blue-600 text-blue-600' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
                    >
                        <Archive className="w-4 h-4"/>
                        Archivio (Risolti/Chiusi)
                    </button>
                </div>
            </div>

            {/* List */}
            {loading ? (
                <div className="text-center p-12 text-slate-400">Caricamento...</div>
            ) : filteredTickets.length === 0 ? (
                <div className="text-center p-12 bg-white rounded-xl border border-dashed border-slate-300">
                    <MessageSquareWarning className="w-12 h-12 text-slate-300 mx-auto mb-3"/>
                    <p className="text-slate-500">Nessuna segnalazione in questa vista.</p>
                </div>
            ) : (
                <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
                    {filteredTickets.map(ticket => (
                        <div key={ticket.id} onClick={() => setViewTicket(ticket)} className="bg-white p-5 rounded-xl border border-slate-200 shadow-sm hover:shadow-md transition-shadow cursor-pointer relative group">
                            <div className="flex justify-between items-start mb-3">
                                <span className={`text-[10px] font-bold px-2 py-1 rounded uppercase ${getStatusColor(ticket.status)}`}>
                                    {ticket.status.replace('_', ' ')}
                                </span>
                                <span className={`text-[10px] font-bold px-2 py-1 rounded uppercase ${getPriorityColor(ticket.priority)}`}>
                                    {ticket.priority}
                                </span>
                            </div>
                            <h3 className="font-bold text-slate-800 mb-1 line-clamp-1">{ticket.title}</h3>
                            <p className="text-xs text-slate-400 mb-3">{new Date(ticket.createdAt).toLocaleDateString()} • {getCategoryLabel(ticket.category)}</p>
                            <p className="text-sm text-slate-600 line-clamp-3 mb-4">{ticket.description}</p>
                            
                            <div className="flex items-center justify-between border-t border-slate-100 pt-3">
                                <div className="flex items-center gap-2 text-xs text-slate-500">
                                    <div className="w-6 h-6 rounded-full bg-slate-200 flex items-center justify-center font-bold text-slate-600">
                                        {ticket.userName ? ticket.userName.charAt(0) : '?'}
                                    </div>
                                    <span className="truncate max-w-[100px]">{ticket.userName || 'Utente'}</span>
                                </div>
                                {ticket.attachments && ticket.attachments.length > 0 && (
                                    <div className="flex items-center gap-1 text-xs text-blue-600 font-medium">
                                        <Paperclip className="w-3 h-3"/> {ticket.attachments.length}
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {/* CREATE MODAL */}
            {showModal && (
                <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-lg p-6 animate-in fade-in zoom-in duration-200 max-h-[90vh] overflow-y-auto">
                        <div className="flex justify-between items-center mb-6">
                             <h3 className="font-bold text-lg text-slate-800">Nuova Segnalazione</h3>
                             <button onClick={() => setShowModal(false)}><X className="w-6 h-6 text-slate-400"/></button>
                        </div>
                        <form onSubmit={handleCreateSubmit} className="space-y-4">
                            <div>
                                <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Oggetto</label>
                                <input className="w-full border p-2.5 rounded-lg text-slate-700" value={formTitle} onChange={e => setFormTitle(e.target.value)} required placeholder="Es. Luce scale rotta" />
                            </div>
                            
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Categoria</label>
                                    <select className="w-full border p-2.5 rounded-lg text-slate-700 bg-white" value={formCategory} onChange={e => setFormCategory(e.target.value as any)}>
                                        <option value={TicketCategory.MAINTENANCE}>Manutenzione</option>
                                        <option value={TicketCategory.ADMINISTRATIVE}>Amministrazione</option>
                                        <option value={TicketCategory.CLEANING}>Pulizie</option>
                                        <option value={TicketCategory.NOISE}>Rumori</option>
                                        <option value={TicketCategory.OTHER}>Altro</option>
                                    </select>
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Priorità</label>
                                    <select className="w-full border p-2.5 rounded-lg text-slate-700 bg-white" value={formPriority} onChange={e => setFormPriority(e.target.value as any)}>
                                        <option value={TicketPriority.LOW}>Bassa</option>
                                        <option value={TicketPriority.MEDIUM}>Media</option>
                                        <option value={TicketPriority.HIGH}>Alta</option>
                                        <option value={TicketPriority.URGENT}>Urgente</option>
                                    </select>
                                </div>
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Descrizione</label>
                                <textarea className="w-full border p-2.5 rounded-lg text-slate-700 h-24" value={formDesc} onChange={e => setFormDesc(e.target.value)} required placeholder="Dettagli del problema..." />
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-slate-500 uppercase mb-1">Allegati (Foto, Video, PDF)</label>
                                <div className="border-2 border-dashed border-slate-300 rounded-lg p-4 text-center hover:bg-slate-50 transition-colors relative">
                                    <input type="file" multiple onChange={handleFileChange} className="absolute inset-0 opacity-0 cursor-pointer" accept="image/*,video/*,application/pdf" />
                                    <div className="flex flex-col items-center gap-1">
                                        <Paperclip className="w-6 h-6 text-slate-400"/>
                                        <span className="text-sm text-slate-500">Clicca o trascina file qui</span>
                                        <span className="text-[10px] text-slate-400">Max 5MB per file</span>
                                    </div>
                                </div>
                                {attachments.length > 0 && (
                                    <div className="mt-3 space-y-2">
                                        {attachments.map((att, idx) => (
                                            <div key={idx} className="flex items-center justify-between bg-slate-50 p-2 rounded border border-slate-200">
                                                <div className="flex items-center gap-2 truncate">
                                                    {att.fileType.includes('image') ? <ImageIcon className="w-4 h-4 text-blue-500"/> : att.fileType.includes('video') ? <Film className="w-4 h-4 text-purple-500"/> : <FileIcon className="w-4 h-4 text-slate-500"/>}
                                                    <span className="text-xs truncate max-w-[200px]">{att.fileName}</span>
                                                </div>
                                                <button type="button" onClick={() => removeAttachment(idx)} className="text-red-500 hover:bg-red-50 p-1 rounded"><X className="w-4 h-4"/></button>
                                            </div>
                                        ))}
                                    </div>
                                )}
                            </div>

                            <div className="pt-2">
                                <button type="submit" disabled={submitting} className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold hover:bg-blue-700 transition-colors flex justify-center items-center gap-2">
                                    {submitting ? 'Invio in corso...' : 'Invia Segnalazione'}
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}

            {/* VIEW DETAILS MODAL */}
            {viewTicket && (
                 <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4 backdrop-blur-sm">
                    <div className="bg-white rounded-xl shadow-xl w-full max-w-3xl flex flex-col md:flex-row max-h-[90vh] overflow-hidden animate-in fade-in zoom-in duration-200">
                        
                        {/* LEFT COLUMN: Info */}
                        <div className="flex-1 p-6 overflow-y-auto border-r border-slate-100">
                            <div className="flex justify-between items-start mb-4">
                                <div>
                                    <h3 className="font-bold text-xl text-slate-800">{viewTicket.title}</h3>
                                    <p className="text-sm text-slate-500">{new Date(viewTicket.createdAt).toLocaleString()} • {getCategoryLabel(viewTicket.category)}</p>
                                </div>
                                <button className="md:hidden" onClick={() => setViewTicket(null)}><X className="w-6 h-6 text-slate-400"/></button>
                            </div>

                            <div className="flex gap-2 mb-6">
                                <div className={`px-3 py-1 rounded-lg text-sm font-bold uppercase ${getStatusColor(viewTicket.status)}`}>
                                    {viewTicket.status.replace('_', ' ')}
                                </div>
                                <div className={`px-3 py-1 rounded-lg text-sm font-bold uppercase ${getPriorityColor(viewTicket.priority)}`}>
                                    {viewTicket.priority}
                                </div>
                            </div>

                            <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 mb-6 text-slate-700 whitespace-pre-wrap leading-relaxed">
                                {viewTicket.description}
                            </div>

                            {/* Attachments */}
                            {viewTicket.attachments && viewTicket.attachments.length > 0 && (
                                <div className="mb-6">
                                    <h4 className="font-bold text-sm text-slate-800 mb-2 flex items-center gap-2"><Paperclip className="w-4 h-4"/> Allegati</h4>
                                    <div className="grid grid-cols-2 gap-3">
                                        {viewTicket.attachments.map(att => (
                                            <button 
                                                key={att.id} 
                                                onClick={() => openAttachment(viewTicket.id, att.id)}
                                                className="flex flex-col items-center justify-center p-3 bg-white border border-slate-200 rounded-lg hover:border-blue-400 hover:shadow-sm transition-all text-center"
                                            >
                                                {att.fileType.includes('image') ? <ImageIcon className="w-6 h-6 text-blue-500 mb-1"/> : att.fileType.includes('video') ? <Film className="w-6 h-6 text-purple-500 mb-1"/> : <FileIcon className="w-6 h-6 text-slate-500 mb-1"/>}
                                                <span className="text-[10px] text-slate-600 truncate w-full">{att.fileName}</span>
                                            </button>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* Admin Actions */}
                            {isAdmin && (
                                <div className="border-t border-slate-100 pt-4">
                                    <h4 className="font-bold text-sm text-slate-500 uppercase mb-3">Gestione Admin</h4>
                                    <div className="flex flex-wrap gap-2">
                                        {(viewTicket.status === TicketStatus.OPEN || viewTicket.status === TicketStatus.SUSPENDED) && (
                                            <button onClick={() => handleStatusUpdate(TicketStatus.IN_PROGRESS)} className="px-3 py-2 bg-yellow-100 text-yellow-700 rounded-lg font-bold text-xs hover:bg-yellow-200 flex items-center gap-1">
                                                <Clock className="w-3 h-3"/> Prendi in Carico
                                            </button>
                                        )}
                                        {viewTicket.status === TicketStatus.IN_PROGRESS && (
                                            <button onClick={() => handleStatusUpdate(TicketStatus.SUSPENDED)} className="px-3 py-2 bg-orange-100 text-orange-700 rounded-lg font-bold text-xs hover:bg-orange-200 flex items-center gap-1">
                                                <PauseCircle className="w-3 h-3"/> Sospendi
                                            </button>
                                        )}
                                        {(viewTicket.status !== TicketStatus.RESOLVED && viewTicket.status !== TicketStatus.CLOSED) && (
                                            <button onClick={() => handleStatusUpdate(TicketStatus.RESOLVED)} className="px-3 py-2 bg-green-100 text-green-700 rounded-lg font-bold text-xs hover:bg-green-200 flex items-center gap-1">
                                                <CheckCircle2 className="w-3 h-3"/> Risolvi
                                            </button>
                                        )}
                                        {(viewTicket.status !== TicketStatus.RESOLVED && viewTicket.status !== TicketStatus.CLOSED) && (
                                            <button onClick={() => handleStatusUpdate(TicketStatus.CLOSED)} className="px-3 py-2 bg-slate-200 text-slate-700 rounded-lg font-bold text-xs hover:bg-slate-300 flex items-center gap-1">
                                                <XCircle className="w-3 h-3"/> Chiudi (Non Risolto)
                                            </button>
                                        )}
                                        
                                        {(viewTicket.status !== TicketStatus.RESOLVED && viewTicket.status !== TicketStatus.CLOSED) && (
                                            <button onClick={() => handleDeleteTicket(viewTicket.id)} className="ml-auto px-3 py-2 text-red-600 font-medium text-xs hover:bg-red-50 rounded-lg flex items-center gap-1">
                                                <Trash2 className="w-3 h-3"/> Elimina
                                            </button>
                                        )}
                                    </div>
                                </div>
                            )}
                             {!isAdmin && viewTicket.status === TicketStatus.OPEN && (
                                <div className="border-t border-slate-100 pt-4 flex justify-end">
                                     <button onClick={() => handleDeleteTicket(viewTicket.id)} className="px-4 py-2 text-red-600 font-medium text-sm hover:bg-red-50 rounded-lg">Elimina Segnalazione</button>
                                </div>
                             )}
                        </div>

                        {/* RIGHT COLUMN: Chat / History */}
                        <div className="w-full md:w-80 bg-slate-50 flex flex-col h-[500px] md:h-auto">
                            <div className="p-4 border-b border-slate-200 flex justify-between items-center bg-white">
                                <h4 className="font-bold text-slate-800">Discussione</h4>
                                <button className="hidden md:block" onClick={() => setViewTicket(null)}><X className="w-5 h-5 text-slate-400 hover:text-slate-600"/></button>
                            </div>
                            
                            <div className="flex-1 overflow-y-auto p-4 space-y-4">
                                {loadingComments ? (
                                    <p className="text-center text-slate-400 text-xs">Caricamento...</p>
                                ) : comments.length === 0 ? (
                                    <p className="text-center text-slate-400 text-xs italic">Nessun commento.</p>
                                ) : (
                                    comments.map(comment => {
                                        const isMe = comment.userId === user?.id;
                                        return (
                                            <div key={comment.id} className={`flex flex-col ${isMe ? 'items-end' : 'items-start'}`}>
                                                <div className={`max-w-[85%] rounded-2xl px-4 py-2 text-sm ${isMe ? 'bg-blue-600 text-white rounded-br-none' : 'bg-white border border-slate-200 text-slate-700 rounded-bl-none'}`}>
                                                    <p>{comment.text}</p>
                                                </div>
                                                <span className="text-[10px] text-slate-400 mt-1 px-1">
                                                    {isMe ? 'Tu' : comment.userName} • {new Date(comment.createdAt).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}
                                                </span>
                                            </div>
                                        );
                                    })
                                )}
                            </div>

                            {/* Input Area - Disabled if ticket closed/resolved */}
                            {(viewTicket.status !== TicketStatus.CLOSED && viewTicket.status !== TicketStatus.RESOLVED) ? (
                                <form onSubmit={handleSendComment} className="p-3 bg-white border-t border-slate-200">
                                    <div className="relative">
                                        <input 
                                            className="w-full border border-slate-300 rounded-full pl-4 pr-12 py-2 text-sm focus:outline-none focus:border-blue-500"
                                            placeholder="Scrivi una risposta..."
                                            value={newComment}
                                            onChange={e => setNewComment(e.target.value)}
                                        />
                                        <button type="submit" disabled={!newComment.trim()} className="absolute right-1 top-1 bottom-1 bg-blue-600 text-white w-8 h-8 rounded-full flex items-center justify-center hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed">
                                            <Send className="w-4 h-4 ml-0.5"/>
                                        </button>
                                    </div>
                                </form>
                            ) : (
                                <div className="p-4 bg-slate-100 text-center text-xs text-slate-500 border-t border-slate-200">
                                    Ticket archiviato. Non è possibile rispondere.
                                </div>
                            )}
                        </div>
                    </div>
                 </div>
            )}
        </div>
    );
};
