import React, { useState } from 'react';
import { Head, router } from '@inertiajs/react';
import AdminLayout from '@/Layouts/AdminLayout';
import { 
    ShieldAlert, 
    AlertTriangle, 
    CheckCircle, 
    XCircle, 
    Filter, 
    Flag, 
    Eye, 
    Plus,
    UserX,
    Settings,
    FileText,
    MessageSquare,
    Search,
    ChevronDown,
    MoreVertical,
    Clock,
    Shield
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';

export default function SafetyHub({ reports, rules, moderation_queue }) {
    const [selectedReport, setSelectedReport] = useState(null);
    const [isDialogOpen, setIsDialogOpen] = useState(false);
    const [resolutionAction, setResolutionAction] = useState('warn');
    const [adminNotes, setAdminNotes] = useState('');
    
    // Tab and filter states
    const [activeTab, setActiveTab] = useState('All Reports');
    const [searchQuery, setSearchQuery] = useState('');
    const [statusFilter, setStatusFilter] = useState('All Status');
    const [typeFilter, setTypeFilter] = useState('All Types');

    const handleResolve = (e) => {
        e.preventDefault();
        if (!selectedReport) return;
        
        router.post(`/admin/safety/reports/${selectedReport.id}/resolve`, {
            action: resolutionAction,
            admin_notes: adminNotes
        }, {
            onSuccess: () => {
                setIsDialogOpen(false);
                setSelectedReport(null);
                setAdminNotes('');
            }
        });
    };

    // Filter reports based on active tab, search query, type, and status
    const filteredReports = (reports || []).filter(report => {
        // Tab filter
        if (activeTab !== 'All Reports') {
            if (activeTab === 'Chats' && report.type !== 'Chat') return false;
            if (activeTab === 'Reviews' && report.type !== 'Review') return false;
        }

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

        // Status filter dropdown
        if (statusFilter !== 'All Status' && report.status !== statusFilter) return false;

        // Search query
        if (searchQuery.trim() !== '') {
            const query = searchQuery.toLowerCase();
            return (
                report.id.toLowerCase().includes(query) ||
                report.reason.toLowerCase().includes(query) ||
                report.reported_user_name.toLowerCase().includes(query) ||
                report.reported_by_name.toLowerCase().includes(query)
            );
        }

        return true;
    });

    return (
        <AdminLayout title="Safety & Moderation">
            <Head title="Safety & Moderation" />

            <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">Safety & Moderation</h1>
                        <p className="text-sm text-slate-500 mt-1">Review and take action on reported content, users and reviews.</p>
                    </div>
                </div>

                {/* Upper Row Metric Cards */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    
                    {/* Card 1: Total Reports */}
                    <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 Reports</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">{reports ? reports.length : 0}</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">
                                Live <span className="font-normal text-slate-400 ml-1">database count</span>
                            </span>
                        </div>
                        <div className="p-3 bg-[#0F6E56]/10 text-[#0F6E56] rounded-2xl">
                            <Flag className="w-6 h-6" />
                        </div>
                    </div>

                    {/* Card 2: Pending 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">Pending Review</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">{reports ? reports.filter(r => r.status === 'Pending').length : 0}</span>
                            <span className="text-[11px] text-amber-600 font-bold block">Requires attention</span>
                        </div>
                        <div className="p-3 bg-amber-50 text-amber-600 rounded-2xl">
                            <Clock 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">{reports ? reports.filter(r => r.status === 'Resolved').length : 0}</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>

                    {/* Card 5: Actions Taken */}
                    <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">Actions Taken</span>
                            <span className="text-2xl font-extrabold text-slate-900 block">{reports ? reports.filter(r => r.status === 'Resolved').length : 0}</span>
                            <span className="text-[11px] text-blue-600 font-bold block">Warnings/Suspensions</span>
                        </div>
                        <div className="p-3 bg-blue-50 text-blue-600 rounded-2xl">
                            <Shield className="w-6 h-6" />
                        </div>
                    </div>
                </div>

                {/* Tabs & Controls Section */}
                <div className="bg-white border border-slate-200 rounded-2xl shadow-sm overflow-hidden">
                    <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">
                        {/* Tabs list */}
                        <div className="flex items-center overflow-x-auto gap-2 -mb-4 lg:mb-0 pb-2 lg:pb-0 scrollbar-none">
                            {['All Reports', 'Chats', 'Reviews'].map((tab) => (
                                <button
                                    key={tab}
                                    onClick={() => setActiveTab(tab)}
                                    className={`px-4 py-2 text-xs font-bold whitespace-nowrap transition-all rounded-lg ${
                                        activeTab === tab 
                                            ? 'bg-[#0F6E56]/10 text-[#0F6E56] font-black shadow-sm' 
                                            : 'text-slate-500 hover:text-slate-800'
                                    }`}
                                >
                                    {tab}
                                </button>
                            ))}
                        </div>

                        {/* Search & Select Controls */}
                        <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3">
                            {/* Type filter */}
                            <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="Chat">Chat</option>
                                <option value="Review">Review</option>
                            </select>

                            {/* Status filter */}
                            <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="Pending">Pending</option>
                                <option value="In Review">In Review</option>
                                <option value="Resolved">Resolved</option>
                            </select>

                            {/* Search Box */}
                            <div className="relative">
                                <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 reports..."
                                    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 sm:w-60 shadow-sm"
                                />
                            </div>
                        </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 w-10">
                                        <input type="checkbox" className="rounded border-slate-300 text-[#0F6E56] focus:ring-[#0F6E56] cursor-pointer" />
                                    </th>
                                    <th className="px-5 py-4">Report ID</th>
                                    <th className="px-5 py-4">Type</th>
                                    <th className="px-5 py-4">Reported User</th>
                                    <th className="px-5 py-4">Reported By</th>
                                    <th className="px-5 py-4">Reason</th>
                                    <th className="px-5 py-4">Status</th>
                                    <th className="px-5 py-4">Reported At</th>
                                    <th className="px-5 py-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-slate-100">
                                {filteredReports.map((report) => (
                                    <tr key={report.id} className="hover:bg-slate-50/40 transition-colors">
                                        <td className="px-5 py-4">
                                            <input type="checkbox" className="rounded border-slate-300 text-[#0F6E56] focus:ring-[#0F6E56] cursor-pointer" />
                                        </td>
                                        <td className="px-5 py-4 font-mono font-bold text-[#0F6E56] hover:underline cursor-pointer">
                                            {report.id}
                                        </td>
                                        <td className="px-5 py-4">
                                            <span className={`px-2.5 py-1 rounded-full text-[10px] font-black uppercase ${
                                                report.type === 'Chat' ? 'bg-cyan-100 text-cyan-700' : 'bg-emerald-100 text-emerald-700'
                                            }`}>
                                                {report.type}
                                            </span>
                                        </td>
                                        <td className="px-5 py-4">
                                            <div className="flex items-center gap-2.5">
                                                <img 
                                                    src={report.reported_user_avatar || 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?auto=format&fit=crop&q=80&w=100'} 
                                                    alt={report.reported_user_name}
                                                    className="w-7 h-7 rounded-full object-cover shadow-sm border border-slate-100"
                                                />
                                                <div>
                                                    <span className="font-extrabold text-slate-800 block">{report.reported_user_name}</span>
                                                    <span className="text-[10px] text-slate-400 font-semibold block">{report.reported_user_role}</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-5 py-4">
                                            <div className="flex items-center gap-2.5">
                                                <img 
                                                    src={report.reported_by_avatar || 'https://images.unsplash.com/photo-1544005313-94ddf0286df2?auto=format&fit=crop&q=80&w=100'} 
                                                    alt={report.reported_by_name}
                                                    className="w-7 h-7 rounded-full object-cover shadow-sm border border-slate-100"
                                                />
                                                <div>
                                                    <span className="font-extrabold text-slate-800 block">{report.reported_by_name}</span>
                                                    <span className="text-[10px] text-slate-400 font-semibold block">{report.reported_by_role}</span>
                                                </div>
                                            </div>
                                        </td>
                                        <td className="px-5 py-4 font-semibold text-slate-800">
                                            {report.reason}
                                        </td>
                                        <td className="px-5 py-4">
                                            <span className={`px-2 py-0.5 rounded-full text-[10px] font-black uppercase ${
                                                report.status === 'Pending' ? 'bg-orange-50 text-orange-700' :
                                                report.status === 'In Review' ? 'bg-blue-50 text-blue-700' : 'bg-emerald-50 text-emerald-700'
                                            }`}>
                                                {report.status}
                                            </span>
                                        </td>
                                        <td className="px-5 py-4 text-slate-400 font-semibold">
                                            {report.reported_at}
                                        </td>
                                        <td className="px-5 py-4 text-right">
                                            <div className="flex items-center justify-end gap-2">
                                                <button 
                                                    onClick={() => { setSelectedReport(report); setIsDialogOpen(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]"
                                                >
                                                    Take Action
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                ))}

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

            </div>

            {/* Investigation & Action Dialog Modal */}
            <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
                <DialogContent className="max-w-xl bg-white p-6 rounded-[24px] border-none shadow-2xl font-sans">
                    <DialogHeader className="mb-4">
                        <DialogTitle className="text-lg font-black text-slate-800 flex items-center gap-2">
                            <ShieldAlert className="w-5 h-5 text-red-600" />
                            <span>Incident Investigation: <span className="font-mono text-slate-400">{selectedReport?.id}</span></span>
                        </DialogTitle>
                    </DialogHeader>

                    <form onSubmit={handleResolve} className="space-y-4 text-xs font-bold text-slate-700">
                        <div className="space-y-1">
                            <label className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Reason / Incident Subject</label>
                            <div className="p-3 bg-slate-50 border border-slate-200 rounded-xl font-black text-slate-800">{selectedReport?.reason}</div>
                        </div>

                        <div className="space-y-1">
                            <label className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Report Description</label>
                            <p className="p-3 bg-slate-50 border border-slate-200 rounded-xl font-medium text-slate-600 leading-relaxed">
                                {selectedReport?.description || 'No description details provided.'}
                            </p>
                        </div>

                        <div className="space-y-1">
                            <label className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Select Resolution Action</label>
                            <select 
                                className="w-full bg-slate-50 border border-slate-200 rounded-xl px-3 py-2.5 font-bold outline-none cursor-pointer focus:bg-white transition-colors"
                                value={resolutionAction}
                                onChange={e => setResolutionAction(e.target.value)}
                            >
                                <option value="warn">Issue Official Warning Notice</option>
                                <option value="suspend">Suspend Reported Account temporarily</option>
                                <option value="ban">Permanently Ban reported user profile</option>
                                <option value="dismiss">Dismiss Report as False / Unverified</option>
                            </select>
                        </div>

                        <div className="space-y-1">
                            <label className="text-[9px] font-black text-slate-400 uppercase tracking-widest">Internal Compliance Action Notes</label>
                            <textarea 
                                rows="3"
                                placeholder="State findings of direct message logs audits or phone outreach validation..."
                                className="w-full bg-white border border-slate-200 rounded-xl p-3 font-semibold focus:ring-2 focus:ring-[#0F6E56]/10 outline-none"
                                value={adminNotes}
                                onChange={e => setAdminNotes(e.target.value)}
                            />
                        </div>

                        <div className="flex gap-2 pt-2 justify-end">
                            <button 
                                type="submit"
                                className="px-5 py-2.5 bg-[#0F6E56] hover:bg-[#085041] text-white rounded-xl text-[10px] font-black uppercase tracking-widest transition-colors shadow-md"
                            >
                                Submit Findings
                            </button>
                            <button 
                                type="button" 
                                onClick={() => setIsDialogOpen(false)}
                                className="px-4 py-2.5 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded-xl text-[10px] font-black uppercase tracking-widest transition-colors"
                            >
                                Close
                            </button>
                        </div>
                    </form>
                </DialogContent>
            </Dialog>
        </AdminLayout>
    );
}
