import React, { useState } from 'react';
import { Head, router } from '@inertiajs/react';
import AdminLayout from '@/Layouts/AdminLayout';
import { 
    Scale, 
    MessageSquare, 
    Download, 
    BadgeDollarSign, 
    AlertCircle, 
    CheckCircle, 
    FileText, 
    ArrowRight,
    ArrowUpRight,
    User,
    ShieldCheck,
    Send,
    Search,
    ChevronDown,
    MoreVertical,
    Clock,
    Eye,
    Plus,
    X,
    Folder,
    AlertTriangle,
    Hourglass
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';

export default function DisputesHub({ tickets }) {
    const [selectedTicket, setSelectedTicket] = useState(null);
    const [isWorkspaceOpen, setIsWorkspaceOpen] = useState(false);
    
    // Notes / Resolution states
    const [internalNote, setInternalNote] = useState('');
    const [resolutionAction, setResolutionAction] = useState('refund_employer');
    const [resolutionSummary, setResolutionSummary] = useState('');

    // Filters
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState('All Status');
    const [priorityFilter, setPriorityFilter] = useState('All Priority');
    const [typeFilter, setTypeFilter] = useState('All Types');
    const [sortBy, setSortBy] = useState('Newest First');

    const handleAddNote = (e) => {
        e.preventDefault();
        if (!internalNote.trim() || !selectedTicket) return;

        router.post(`/admin/disputes/${selectedTicket.id}/add-note`, { note: internalNote }, {
            onSuccess: () => {
                selectedTicket.admin_notes += "\n• " + internalNote;
                setInternalNote('');
            }
        });
    };

    const handleResolve = (e) => {
        if (e) e.preventDefault();
        if (!selectedTicket) return;
        
        router.post(`/admin/disputes/${selectedTicket.id}/resolve`, {
            resolution: internalNote || 'Resolved by mediator',
            action_taken: 'close_ticket'
        }, {
            onSuccess: () => {
                selectedTicket.status = 'Resolved';
                setIsWorkspaceOpen(false);
                setSelectedTicket(null);
                setInternalNote('');
            }
        });
    };

    // Filter tickets
    const filteredTickets = (tickets || []).filter(ticket => {
        // Status filter
        if (statusFilter !== 'All Status' && ticket.status !== statusFilter) return false;

        // Priority filter
        if (priorityFilter !== 'All Priority' && ticket.priority !== priorityFilter) return false;

        // Type filter
        if (typeFilter !== 'All Types' && ticket.type !== typeFilter) return false;

        // Search query
        if (searchQuery.trim() !== '') {
            const query = searchQuery.toLowerCase();
            return (
                ticket.id.toLowerCase().includes(query) ||
                ticket.party_one_name.toLowerCase().includes(query) ||
                ticket.party_two_name.toLowerCase().includes(query) ||
                ticket.reason.toLowerCase().includes(query)
            );
        }

        return true;
    });

    return (
        <AdminLayout title="Help & Support">
            <Head title="Help & Support" />

            <div className="font-sans max-w-[1600px] mx-auto space-y-6">
                
                {/* Header Row */}
                <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                    <div>
                        <h1 className="text-2xl font-bold text-slate-900 tracking-tight">Help & Support</h1>
                        <p className="text-sm text-slate-500 mt-1">Handle complaints and resolve disputes between workers and employers.</p>
                    </div>
                    
                    <button className="inline-flex items-center gap-1.5 px-4 py-2.5 bg-[#0F6E56] hover:bg-[#085041] text-white rounded-xl text-xs font-bold transition-all shadow-md self-end md:self-auto uppercase tracking-wider">
                        <Plus className="w-4 h-4" />
                        <span>New Dispute</span>
                    </button>
                </div>

                {/* Upper Row Metric Cards */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    
                    {/* Card 1: Total Disputes */}
                    <div className="bg-white p-5 border border-slate-200 rounded-2xl shadow-sm flex items-center justify-between">
                        <div className="space-y-1">
                            <span className="text-xs text-slate-500 font-semibold block">Total Disputes</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">36</span>
                            <span className="inline-flex items-center gap-0.5 px-2 py-0.5 bg-emerald-50 text-emerald-700 rounded-full text-[10px] font-bold">
                                ↑ 8% <span className="font-normal text-slate-400 ml-1">from last 30 days</span>
                            </span>
                        </div>
                        <div className="p-3 bg-[#0F6E56]/10 text-[#0F6E56] rounded-2xl">
                            <Scale className="w-6 h-6" />
                        </div>
                    </div>

                    {/* Card 2: Open */}
                    <div className="bg-white p-5 border border-slate-200 rounded-2xl shadow-sm flex items-center justify-between">
                        <div className="space-y-1">
                            <span className="text-xs text-slate-500 font-semibold block">Open</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">12</span>
                            <span className="text-[11px] text-amber-600 font-bold block">Needs attention</span>
                        </div>
                        <div className="p-3 bg-amber-50 text-amber-600 rounded-2xl">
                            <Folder className="w-6 h-6" />
                        </div>
                    </div>

                    {/* Card 3: Under Review */}
                    <div className="bg-white p-5 border border-slate-200 rounded-2xl shadow-sm flex items-center justify-between">
                        <div className="space-y-1">
                            <span className="text-xs text-slate-500 font-semibold block">Under Review</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">10</span>
                            <span className="text-[11px] text-blue-600 font-bold block">In progress</span>
                        </div>
                        <div className="p-3 bg-blue-50 text-blue-600 rounded-2xl">
                            <Eye className="w-6 h-6" />
                        </div>
                    </div>

                    {/* Card 4: Resolved */}
                    <div className="bg-white p-5 border border-slate-200 rounded-2xl shadow-sm flex items-center justify-between">
                        <div className="space-y-1">
                            <span className="text-xs text-slate-500 font-semibold block">Resolved</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">8</span>
                            <span className="text-[11px] text-emerald-600 font-bold block">This period</span>
                        </div>
                        <div className="p-3 bg-emerald-50 text-emerald-600 rounded-2xl">
                            <CheckCircle className="w-6 h-6" />
                        </div>
                    </div>
                </div>

                {/* Table / Filters Section */}
                <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
                    
                    {/* Filters Header */}
                    <div className="p-4 border-b border-slate-100 flex flex-col lg:flex-row lg:items-center justify-between gap-4 bg-slate-50/20">
                        {/* Left search */}
                        <div className="relative w-full lg:w-80">
                            <Search className="w-4 h-4 text-slate-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
                            <input
                                type="text"
                                placeholder="Search disputes..."
                                value={searchQuery}
                                onChange={e => setSearchQuery(e.target.value)}
                                className="bg-white border border-slate-200 pl-10 pr-4 py-2 rounded-xl text-xs font-semibold focus:outline-none focus:ring-2 focus:ring-[#0F6E56]/20 w-full shadow-sm"
                            />
                        </div>

                        {/* Right filters */}
                        <div className="flex flex-wrap items-center gap-3">
                            <select
                                value={statusFilter}
                                onChange={e => setStatusFilter(e.target.value)}
                                className="bg-white border border-slate-200 text-slate-700 text-xs font-bold px-3 py-2 rounded-xl outline-none cursor-pointer hover:bg-slate-50 transition-colors shadow-sm"
                            >
                                <option value="All Status">All Status</option>
                                <option value="Open">Open</option>
                                <option value="Under Review">Under Review</option>
                                <option value="Waiting Response">Waiting Response</option>
                                <option value="Resolved">Resolved</option>
                            </select>



                            <select
                                value={typeFilter}
                                onChange={e => setTypeFilter(e.target.value)}
                                className="bg-white border border-slate-200 text-slate-700 text-xs font-bold px-3 py-2 rounded-xl outline-none cursor-pointer hover:bg-slate-50 transition-colors shadow-sm"
                            >
                                <option value="All Types">All Types</option>
                                <option value="Payment Issue">Payment Issue</option>
                                <option value="Behavior Issue">Behavior Issue</option>
                                <option value="Working Conditions">Working Conditions</option>
                                <option value="Abuse/Harassment">Abuse/Harassment</option>
                            </select>

                            <select
                                value={sortBy}
                                onChange={e => setSortBy(e.target.value)}
                                className="bg-white border border-slate-200 text-slate-700 text-xs font-bold px-3 py-2 rounded-xl outline-none cursor-pointer hover:bg-slate-50 transition-colors shadow-sm"
                            >
                                <option value="Newest First">Sort: Newest First</option>
                                <option value="Oldest First">Sort: Oldest First</option>
                            </select>
                        </div>
                    </div>

                    {/* Table Row Content */}
                    <div className="overflow-x-auto">
                        <table className="w-full text-left border-collapse text-xs font-semibold text-slate-600">
                            <thead>
                                <tr className="border-b border-slate-100 bg-slate-50/50 text-slate-400 font-bold uppercase tracking-wider text-[10px]">
                                    <th className="px-5 py-4">Dispute ID</th>
                                    <th className="px-5 py-4">Raised By</th>
                                    <th className="px-5 py-4">Type</th>
                                    <th className="px-5 py-4">Reason</th>
                                    <th className="px-5 py-4">Status</th>
                                    <th className="px-5 py-4">Created At</th>
                                    <th className="px-5 py-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {filteredTickets.map((ticket) => (
                                    <tr key={ticket.id} className="hover:bg-slate-50/40 transition-colors">
                                        <td className="px-5 py-4 font-mono font-bold text-[#0F6E56] hover:underline cursor-pointer">
                                            {ticket.id}
                                        </td>
                                        <td className="px-5 py-4">
                                            <div className="flex items-center gap-3">
                                                <img 
                                                    src={ticket.party_one_avatar || 'https://images.unsplash.com/photo-1494790108377-be9c29b29330?auto=format&fit=crop&q=80&w=100'} 
                                                    alt={ticket.party_one_name}
                                                    className="w-7 h-7 rounded-full object-cover border border-slate-200 shadow-sm"
                                                />
                                                <div>
                                                    <span className="font-extrabold text-slate-800 block">
                                                        {ticket.party_one_name}
                                                    </span>
                                                    <span className="text-[10px] text-slate-400 font-bold block uppercase tracking-wider">
                                                        {ticket.party_one_role}
                                                    </span>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-5 py-4">
                                            <span className={`px-2.5 py-1 rounded-full text-[10px] font-black uppercase ${
                                                ticket.type === 'Payment Issue' ? 'bg-blue-100 text-blue-700' :
                                                ticket.type === 'Behavior Issue' ? 'bg-purple-100 text-purple-700' :
                                                ticket.type === 'Working Conditions' ? 'bg-emerald-100 text-emerald-700' : 'bg-red-100 text-red-700'
                                            }`}>
                                                {ticket.type}
                                            </span>
                                        </td>
                                        <td className="px-5 py-4 font-semibold text-slate-800">
                                            {ticket.reason}
                                        </td>
                                        <td className="px-5 py-4">
                                            <span className={`px-2 py-0.5 rounded-full text-[10px] font-black uppercase ${
                                                ticket.status === 'Open' ? 'bg-orange-50 text-orange-700' :
                                                ticket.status === 'Under Review' ? 'bg-blue-50 text-blue-700' :
                                                ticket.status === 'Waiting Response' ? 'bg-purple-50 text-purple-700' : 'bg-emerald-50 text-emerald-700'
                                            }`}>
                                                {ticket.status}
                                            </span>
                                        </td>
                                        <td className="px-5 py-4 text-slate-400 font-semibold">
                                            {ticket.created_at}
                                        </td>
                                        <td className="px-5 py-4 text-right">
                                            <div className="flex items-center justify-end gap-2">
                                                <button 
                                                    onClick={() => { setSelectedTicket(ticket); setIsWorkspaceOpen(true); }}
                                                    className="px-3.5 py-1.5 bg-[#0F6E56] hover:bg-[#085041] text-white rounded-lg transition-colors font-black uppercase tracking-wider text-[10px]"
                                                >
                                                    Manage
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}

                                {filteredTickets.length === 0 && (
                                    <tr>
                                        <td colSpan="9" className="p-10 text-center font-bold text-slate-400 uppercase">
                                            No active disputes found matching your criteria.
                                        </td>
                                    </tr>
                                )}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            {/* Premium Full Detailed Investigation Workspace Sidebar Drawer */}
            {isWorkspaceOpen && selectedTicket && (
                <div className="fixed inset-0 bg-slate-900/50 backdrop-blur-sm z-50 flex justify-end transition-opacity">
                    <div className="w-full max-w-5xl bg-slate-50 h-full shadow-2xl flex flex-col justify-between overflow-hidden animate-slide-in-right">
                        
                        {/* Drawer Header */}
                        <div className="bg-white p-5 border-b border-slate-200 flex items-center justify-between">
                            <div className="flex items-center gap-3">
                                <Scale className="w-6 h-6 text-[#0F6E56]" />
                                <div>
                                    <h2 className="text-base font-black text-slate-800 uppercase tracking-wide flex items-center gap-1.5">
                                        <span>Dispute Resolution Case:</span>
                                        <span className="font-mono text-[#0F6E56]">{selectedTicket.id}</span>
                                    </h2>
                                    <p className="text-xs text-slate-400 font-semibold mt-0.5">Assigned Mediator: {selectedTicket.assigned_to}</p>
                                </div>
                            </div>
                            <button 
                                onClick={() => { setIsWorkspaceOpen(false); setSelectedTicket(null); }}
                                className="p-2 text-slate-400 hover:text-slate-600 hover:bg-slate-100 rounded-full transition-colors"
                            >
                                <X className="w-5 h-5" />
                            </button>
                        </div>

                        {/* Drawer Body Scroll Container */}
                        <div className="flex-1 overflow-y-auto p-6 space-y-6">
                            
                            {/* Case Header Details Banner */}
                            <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm grid grid-cols-1 md:grid-cols-4 gap-4">
                                <div className="space-y-1">
                                    <span className="text-[10px] text-slate-400 font-bold uppercase block">Parties</span>
                                    <span className="font-extrabold text-slate-800 text-sm block">
                                        {selectedTicket.party_one_name} <span className="font-normal text-slate-400">({selectedTicket.party_one_role})</span>
                                    </span>
                                    <span className="font-semibold text-slate-500 text-xs block">
                                        vs {selectedTicket.party_two_name} <span className="font-normal text-slate-400">({selectedTicket.party_two_role})</span>
                                    </span>
                                </div>

                                <div className="space-y-1">
                                    <span className="text-[10px] text-slate-400 font-bold uppercase block">Dispute Type</span>
                                    <span className="font-extrabold text-slate-800 block text-xs uppercase tracking-wide">{selectedTicket.type}</span>
                                    <span className="text-[11px] text-slate-500 font-medium block leading-relaxed">{selectedTicket.reason}</span>
                                </div>

                                <div className="space-y-1">
                                    <span className="text-[10px] text-slate-400 font-bold uppercase block">Case Status</span>
                                    <span className={`block px-2.5 py-0.5 rounded-full text-[10px] font-black uppercase w-fit ${
                                        selectedTicket.status === 'Resolved' ? 'bg-emerald-50 text-emerald-700' : 'bg-orange-50 text-orange-700'
                                    }`}>
                                        Status: {selectedTicket.status}
                                    </span>
                                </div>

                                <div className="space-y-1">
                                    <span className="text-[10px] text-slate-400 font-bold uppercase block">Created Date</span>
                                    <span className="font-extrabold text-slate-800 block">{selectedTicket.created_at}</span>
                                    <span className="text-[10px] text-slate-400 font-semibold block">Case active since last update</span>
                                </div>
                            </div>

                            {/* Dual Panel Workspace */}
                            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                                
                                {/* Chat Log Transcript */}
                                <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm flex flex-col h-[480px]">
                                    <div className="border-b pb-3">
                                        <h3 className="text-xs font-black text-slate-800 uppercase tracking-widest flex items-center gap-1.5">
                                            <MessageSquare className="w-4.5 h-4.5 text-[#0F6E56]" />
                                            <span>Direct Chat logs Transcript</span>
                                        </h3>
                                        <p className="text-[10px] text-slate-400 font-semibold mt-1">Official authenticated conversation history audits</p>
                                    </div>

                                    {/* Scroll thread */}
                                    <div className="flex-1 overflow-y-auto space-y-4 my-4 pr-1 scrollbar-thin">
                                        {selectedTicket.chat_logs.map((log, i) => {
                                            const isMediator = log.sender === 'Mediator (Admin)';
                                            const isPartyTwo = log.sender === selectedTicket.party_two_name;
                                            return (
                                                <div 
                                                    key={i} 
                                                    className={`max-w-[90%] p-3 rounded-2xl text-[11px] font-bold shadow-sm ${
                                                        isMediator
                                                            ? 'bg-emerald-50 text-emerald-950 border border-emerald-250 mx-auto'
                                                            : isPartyTwo 
                                                                ? 'bg-blue-50 text-blue-900 mr-auto border border-blue-100' 
                                                                : 'bg-indigo-50 text-indigo-900 ml-auto border border-indigo-100'
                                                    }`}
                                                >
                                                    <span className="text-[8px] font-black uppercase text-slate-400 block mb-1">{log.sender} • {log.time}</span>
                                                    <p className="font-semibold leading-relaxed">{log.message}</p>
                                                </div>
                                            );
                                        })}
                                    </div>

                                    <div className="text-[10px] bg-slate-50 p-2.5 rounded-xl border border-slate-100 text-slate-400 font-bold text-center uppercase tracking-wider">
                                        Logs Digitally Secured by UAE Verification Compliance
                                    </div>
                                </div>

                                {/* Tools panel */}
                                <div className="space-y-6">
                                    
                                    {/* Evidence Files */}
                                    <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm space-y-3">
                                        <h3 className="text-xs font-black text-slate-800 uppercase tracking-widest flex items-center gap-1.5">
                                            <FileText className="w-4.5 h-4.5 text-[#0F6E56]" />
                                            <span>Case Evidence Files</span>
                                        </h3>
                                        <div className="space-y-2">
                                            {selectedTicket.evidence?.map((file, i) => (
                                                <div key={i} className="flex items-center justify-between p-2.5 bg-slate-50 rounded-xl border border-slate-150 text-xs font-bold text-slate-700 shadow-sm hover:bg-slate-100 transition-colors">
                                                    <div className="flex items-center gap-2">
                                                        <FileText className="w-4 h-4 text-slate-400" />
                                                        <span>{file.name} ({file.type})</span>
                                                    </div>
                                                    <a href={file.url} className="text-[#0F6E56] hover:underline flex items-center gap-0.5">
                                                        <span>View</span>
                                                        <ArrowUpRight className="w-3.5 h-3.5" />
                                                    </a>
                                                </div>
                                            ))}
                                        </div>
                                    </div>

                                    {/* Simplified Action Panel */}
                                    <div className="bg-white border border-slate-200 rounded-2xl p-5 shadow-sm space-y-4">
                                        <div>
                                            <h3 className="text-xs font-black text-slate-800 uppercase tracking-widest flex items-center gap-2">
                                                <MessageSquare className="w-4 h-4 text-[#0F6E56]" />
                                                <span>Mediator Reply & Actions</span>
                                            </h3>
                                            <p className="text-[10px] text-slate-400 font-semibold mt-1">Send a message to both parties or resolve the dispute.</p>
                                        </div>

                                        <form onSubmit={handleAddNote} className="space-y-3">
                                            <textarea 
                                                rows="3"
                                                className="w-full bg-white border border-slate-200 rounded-xl p-3 text-xs font-semibold focus:ring-2 focus:ring-[#0F6E56]/10 outline-none"
                                                placeholder="Write your response or internal compliance update..."
                                                value={internalNote}
                                                onChange={e => setInternalNote(e.target.value)}
                                            />
                                            <div className="flex gap-2">
                                                <button 
                                                    type="submit" 
                                                    className="flex-1 py-2.5 bg-[#0F6E56] hover:bg-[#085041] text-white rounded-xl text-[10px] font-black uppercase tracking-wider transition-colors shadow-sm"
                                                >
                                                    Send Reply
                                                </button>
                                                
                                                {selectedTicket.status !== 'Resolved' && (
                                                    <button 
                                                        type="button"
                                                        onClick={handleResolve}
                                                        className="px-4 py-2.5 bg-red-600 hover:bg-red-700 text-white rounded-xl text-[10px] font-black uppercase tracking-wider transition-colors shadow-sm"
                                                    >
                                                        Close Ticket
                                                    </button>
                                                )}
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </AdminLayout>
    );
}
