import AdminLayout from '@/Layouts/AdminLayout';
import { Head, Link, router } from '@inertiajs/react';
import { Search, Trash2, CheckCircle, XCircle, Clock, Eye, X, Calendar, MapPin, Building2, TrendingUp, MessageSquare } from 'lucide-react';
import { useState, useEffect } from 'react';
import Modal from '@/Components/Modal';

interface Booking {
    id: number;
    name: string;
    email: string;
    company: string | null;
    location: string | null;
    revenue_band: string | null;
    challenge: string | null;
    scheduled_at: string;
    meeting_link: string | null;
    admin_notes: string | null;
    status: string;
}

interface PaginatedBookings {
    data: Booking[];
    current_page: number;
    last_page: number;
    total: number;
    per_page: number;
}

interface Props {
    bookings: PaginatedBookings;
    activeStatus: string;
}

const statusStyle = (s: string) => {
    if (s === 'Confirmed') return 'bg-emerald-50 text-emerald-700';
    if (s === 'Pending')   return 'bg-amber-50 text-amber-700';
    if (s === 'Completed') return 'bg-[#F0EDE8] text-[#8C92AC]';
    return 'bg-red-50 text-red-600';
};

export default function Index({ bookings, activeStatus }: Props) {
    const tabs = ['All', 'Confirmed', 'Pending', 'Completed', 'Cancelled'];
    const [search, setSearch] = useState('');
    const [selectedBooking, setSelectedBooking] = useState<Booking | null>(null);
    const [meetingLink, setMeetingLink] = useState('');
    const [adminNotes, setAdminNotes] = useState('');

    useEffect(() => {
        if (selectedBooking) {
            setMeetingLink(selectedBooking.meeting_link || '');
            setAdminNotes(selectedBooking.admin_notes || '');
        }
    }, [selectedBooking]);

    function switchTab(tab: string) {
        router.get('/admin/bookings', { status: tab === 'All' ? undefined : tab }, {
            preserveScroll: true,
            replace: true,
        });
    }

    function updateStatus(id: number, status: string) {
        router.patch(route('admin.bookings.update-status', id), { 
            status,
            meeting_link: meetingLink,
            admin_notes: adminNotes
        }, {
            preserveScroll: true,
            onSuccess: () => {
                if (selectedBooking && selectedBooking.id === id) {
                    setSelectedBooking(null);
                }
            }
        });
    }

    function deleteBooking(id: number) {
        if (confirm('Delete this booking? This cannot be undone.')) {
            router.delete(route('admin.bookings.destroy', id), { 
                preserveScroll: true,
                onSuccess: () => setSelectedBooking(null)
            });
        }
    }

    const displayed = search.trim()
        ? bookings.data.filter((b) =>
            b.name.toLowerCase().includes(search.toLowerCase()) ||
            b.email.toLowerCase().includes(search.toLowerCase()) ||
            (b.company ?? '').toLowerCase().includes(search.toLowerCase())
          )
        : bookings.data;

    return (
        <AdminLayout>
            <Head title="Bookings" />

            {/* Header */}
            <div className="mb-8">
                <h1 className="font-display text-[1.625rem] font-normal tracking-[-0.02em] text-ink leading-none">
                    Bookings
                </h1>
                <p className="mt-2.5 text-[0.9375rem] text-[#8C92AC]">
                    {bookings.total} growth audit {bookings.total === 1 ? 'call' : 'calls'} scheduled.
                </p>
            </div>

            {/* Toolbar */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                {/* Tabs */}
                <div className="flex items-center gap-0.5 bg-[#F0EDE8] p-1 rounded-lg overflow-x-auto">
                    {tabs.map((tab) => (
                        <button
                            key={tab}
                            onClick={() => switchTab(tab)}
                            className={`px-3.5 py-1.5 text-[11px] font-semibold rounded-md transition-all whitespace-nowrap ${
                                activeStatus === tab
                                    ? 'bg-white shadow-sm text-ink'
                                    : 'text-[#8C92AC] hover:text-ink'
                            }`}
                        >
                            {tab}
                        </button>
                    ))}
                </div>

                {/* Search */}
                <div className="relative w-full sm:w-64">
                    <div className="absolute inset-y-0 left-3.5 flex items-center pointer-events-none">
                        <Search className="h-4 w-4 text-[#8C92AC]" />
                    </div>
                    <input
                        type="text"
                        value={search}
                        onChange={(e) => setSearch(e.target.value)}
                        placeholder="Search name, company…"
                        className="pl-10 pr-4 py-2.5 bg-white border border-[#E8E6DF] rounded-xl text-[13px] text-ink placeholder:text-[#8C92AC] focus:outline-none focus:ring-2 focus:ring-primary/15 w-full"
                    />
                </div>
            </div>

            {/* Table (Desktop) */}
            <div className="hidden md:block bg-white rounded-xl border border-[#E8E6DF] overflow-hidden overflow-x-auto">
                <table className="w-full text-left min-w-[700px]">
                    <thead>
                        <tr className="border-b border-[#F0EDE8]">
                            {['ID', 'Client', 'Company', 'Location', 'Slot', 'Status', ''].map((h) => (
                                <th
                                    key={h}
                                    className="px-5 py-3.5 text-[10px] font-semibold tracking-[0.14em] uppercase text-[#8C92AC]"
                                >
                                    {h}
                                </th>
                            ))}
                        </tr>
                    </thead>
                    <tbody>
                        {displayed.length > 0 ? displayed.map((b) => (
                            <tr
                                key={b.id}
                                onClick={() => setSelectedBooking(b)}
                                className="border-b border-[#F0EDE8] last:border-0 hover:bg-[#FAFAF8] transition-colors group cursor-pointer"
                            >
                                <td className="px-5 py-4 text-[11px] text-[#8C92AC] font-medium">
                                    BK-{b.id}
                                </td>
                                <td className="px-5 py-4">
                                    <p className="text-[13px] font-semibold text-ink">{b.name}</p>
                                    <p className="text-[11px] text-[#8C92AC] mt-0.5">{b.email}</p>
                                </td>
                                <td className="px-5 py-4 text-[13px] text-ink">{b.company ?? '—'}</td>
                                <td className="px-5 py-4 text-[13px] text-[#8C92AC]">{b.location ?? '—'}</td>
                                <td className="px-5 py-4">
                                    <p className="text-[13px] font-semibold text-ink">
                                        {new Date(b.scheduled_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
                                    </p>
                                    <p className="text-[10px] text-[#8C92AC] mt-0.5 uppercase tracking-wide">
                                        {new Date(b.scheduled_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} WAT
                                    </p>
                                </td>
                                <td className="px-5 py-4">
                                    <span className={`inline-flex items-center px-2.5 py-1 rounded-full text-[10px] font-semibold uppercase tracking-wider ${statusStyle(b.status)}`}>
                                        {b.status}
                                    </span>
                                </td>
                                <td className="px-5 py-4">
                                    <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                        <button
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                setSelectedBooking(b);
                                            }}
                                            title="View details"
                                            className="p-1.5 text-[#8C92AC] hover:text-ink transition-colors"
                                        >
                                            <Eye className="h-4 w-4" />
                                        </button>
                                        {b.status === 'Pending' && (
                                            <button
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    updateStatus(b.id, 'Confirmed');
                                                }}
                                                title="Confirm"
                                                className="p-1.5 text-[#8C92AC] hover:text-emerald-600 transition-colors"
                                            >
                                                <CheckCircle className="h-4 w-4" />
                                            </button>
                                        )}
                                        {b.status !== 'Cancelled' && b.status !== 'Completed' && (
                                            <button
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    updateStatus(b.id, 'Cancelled');
                                                }}
                                                title="Cancel"
                                                className="p-1.5 text-[#8C92AC] hover:text-amber-600 transition-colors"
                                            >
                                                <XCircle className="h-4 w-4" />
                                            </button>
                                        )}
                                        {b.status === 'Confirmed' && (
                                            <button
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    updateStatus(b.id, 'Completed');
                                                }}
                                                title="Mark completed"
                                                className="p-1.5 text-[#8C92AC] hover:text-primary transition-colors"
                                            >
                                                <Clock className="h-4 w-4" />
                                            </button>
                                        )}
                                        <button
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                deleteBooking(b.id);
                                            }}
                                            title="Delete"
                                            className="p-1.5 text-[#8C92AC] hover:text-red-500 transition-colors"
                                        >
                                            <Trash2 className="h-3.5 w-3.5" />
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        )) : (
                            <tr>
                                <td colSpan={7} className="px-5 py-16 text-center text-[13px] text-[#8C92AC]">
                                    {search ? 'No bookings match your search.' : 'No bookings yet.'}
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            {/* Mobile List */}
            <div className="md:hidden space-y-3">
                {displayed.length > 0 ? displayed.map((b) => (
                    <div 
                        key={b.id}
                        onClick={() => setSelectedBooking(b)}
                        className="bg-white rounded-xl border border-[#E8E6DF] p-4 active:bg-[#FAFAF8] transition-colors"
                    >
                        <div className="flex items-center justify-between mb-2">
                            <h3 className="text-[14px] font-bold text-ink truncate mr-2">{b.name}</h3>
                            <span className={`inline-flex items-center px-2 py-0.5 rounded-full text-[8px] font-bold uppercase tracking-wider shrink-0 ${statusStyle(b.status)}`}>
                                {b.status}
                            </span>
                        </div>

                        <div className="flex items-center justify-between text-[11px] text-[#8C92AC] mb-3">
                            <span>BK-{b.id} · {b.company || 'Private Client'}</span>
                        </div>

                        <div className="flex items-center justify-between pt-3 border-t border-[#F0EDE8]">
                            <div className="flex items-center gap-3">
                                <span className="text-[12px] font-semibold text-ink">
                                    {new Date(b.scheduled_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
                                </span>
                                <span className="text-[12px] text-[#8C92AC]">
                                    {new Date(b.scheduled_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
                                </span>
                            </div>
                            
                            <div className="flex items-center gap-2">
                                {b.status === 'Pending' && (
                                    <button
                                        onClick={(e) => { e.stopPropagation(); updateStatus(b.id, 'Confirmed'); }}
                                        className="h-7 px-2.5 bg-emerald-50 text-emerald-700 text-[10px] font-bold rounded-lg border border-emerald-100"
                                    >
                                        Confirm
                                    </button>
                                )}
                                <button
                                    onClick={(e) => { e.stopPropagation(); setSelectedBooking(b); }}
                                    className="p-1.5 text-[#8C92AC]"
                                >
                                    <Eye className="h-4 w-4" />
                                </button>
                                <button
                                    onClick={(e) => { e.stopPropagation(); deleteBooking(b.id); }}
                                    className="p-1.5 text-[#8C92AC]"
                                >
                                    <Trash2 className="h-3.5 w-3.5" />
                                </button>
                            </div>
                        </div>
                    </div>
                )) : (
                    <div className="bg-white rounded-xl border border-[#E8E6DF] p-10 text-center text-[13px] text-[#8C92AC]">
                        {search ? 'No matches found.' : 'No bookings yet.'}
                    </div>
                )}
            </div>

            {/* Pagination */}
            {bookings.last_page > 1 && (
                <div className="flex items-center justify-between mt-5 text-[12px] text-[#8C92AC]">
                    <span>Page {bookings.current_page} of {bookings.last_page} · {bookings.total} total</span>
                    <div className="flex gap-2">
                        {bookings.current_page > 1 && (
                            <button
                                onClick={() => router.get('/admin/bookings', { page: bookings.current_page - 1, status: activeStatus !== 'All' ? activeStatus : undefined })}
                                className="px-3 py-1.5 bg-white border border-[#E8E6DF] rounded-lg hover:text-ink transition-colors"
                            >
                                Previous
                            </button>
                        )}
                        {bookings.current_page < bookings.last_page && (
                            <button
                                onClick={() => router.get('/admin/bookings', { page: bookings.current_page + 1, status: activeStatus !== 'All' ? activeStatus : undefined })}
                                className="px-3 py-1.5 bg-white border border-[#E8E6DF] rounded-lg hover:text-ink transition-colors"
                            >
                                Next
                            </button>
                        )}
                    </div>
                </div>
            )}

            {/* Details Modal */}
            <Modal show={!!selectedBooking} onClose={() => setSelectedBooking(null)} maxWidth="lg">
                {selectedBooking && (
                    <div className="p-0">
                        {/* Modal Header */}
                        <div className="px-6 py-4 border-b border-[#F0EDE8] flex items-center justify-between bg-[#FAFAF8]">
                            <div>
                                <h2 className="text-[14px] font-bold text-ink flex items-center gap-2">
                                    Booking Details
                                    <span className={`px-2 py-0.5 rounded-full text-[9px] font-bold uppercase tracking-widest ${statusStyle(selectedBooking.status)}`}>
                                        {selectedBooking.status}
                                    </span>
                                </h2>
                                <p className="text-[11px] text-[#8C92AC] mt-0.5">Reference: BK-{selectedBooking.id}</p>
                            </div>
                            <button 
                                onClick={() => setSelectedBooking(null)}
                                className="p-1.5 text-[#8C92AC] hover:text-ink transition-colors"
                            >
                                <X className="h-4 w-4" />
                            </button>
                        </div>

                        {/* Modal Body */}
                        <div className="p-6 space-y-8 max-h-[65vh] overflow-y-auto custom-scrollbar">
                            {/* Section: Client Info */}
                            <div className="grid grid-cols-2 gap-6">
                                <div>
                                    <label className="text-[10px] font-bold text-[#8C92AC] uppercase tracking-widest block mb-2">Client Name</label>
                                    <p className="text-[14px] font-semibold text-ink">{selectedBooking.name}</p>
                                    <p className="text-[12px] text-[#8C92AC]">{selectedBooking.email}</p>
                                </div>
                                <div>
                                    <label className="text-[10px] font-bold text-[#8C92AC] uppercase tracking-widest block mb-2">Scheduled Slot</label>
                                    <div className="flex items-center gap-2">
                                        <Calendar className="h-3.5 w-3.5 text-accent" />
                                        <p className="text-[13px] font-semibold text-ink">
                                            {new Date(selectedBooking.scheduled_at).toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}
                                        </p>
                                    </div>
                                    <p className="text-[11px] text-[#8C92AC] ml-5.5">
                                        {new Date(selectedBooking.scheduled_at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })} WAT
                                    </p>
                                </div>
                            </div>

                            {/* Section: Business Info */}
                            <div className="bg-[#FAFAF8] rounded-xl border border-[#F0EDE8] p-5 grid grid-cols-3 gap-4">
                                <div>
                                    <label className="text-[9px] font-bold text-[#8C92AC] uppercase tracking-widest flex items-center gap-1.5 mb-2">
                                        <Building2 className="h-3 w-3" /> Company
                                    </label>
                                    <p className="text-[13px] font-medium text-ink truncate">{selectedBooking.company || 'Not provided'}</p>
                                </div>
                                <div>
                                    <label className="text-[9px] font-bold text-[#8C92AC] uppercase tracking-widest flex items-center gap-1.5 mb-2">
                                        <MapPin className="h-3 w-3" /> Location
                                    </label>
                                    <p className="text-[13px] font-medium text-ink">{selectedBooking.location || '—'}</p>
                                </div>
                                <div>
                                    <label className="text-[9px] font-bold text-[#8C92AC] uppercase tracking-widest flex items-center gap-1.5 mb-2">
                                        <TrendingUp className="h-3 w-3" /> Revenue
                                    </label>
                                    <p className="text-[13px] font-medium text-ink">{selectedBooking.revenue_band || '—'}</p>
                                </div>
                            </div>

                            {/* Section: Fulfillment */}
                            {(selectedBooking.status === 'Pending' || selectedBooking.status === 'Confirmed') && (
                                <div className="bg-emerald-50/50 rounded-xl border border-emerald-100 p-5 space-y-4">
                                    <h3 className="text-[11px] font-bold text-emerald-800 uppercase tracking-widest flex items-center gap-2">
                                        <Clock className="h-3.5 w-3.5" /> Meeting & Fulfillment
                                    </h3>
                                    
                                    <div>
                                        <label className="text-[10px] font-bold text-emerald-700 uppercase tracking-widest block mb-2">Meeting Link (Google Meet / Zoom)</label>
                                        <input 
                                            type="url" 
                                            value={meetingLink}
                                            onChange={(e) => setMeetingLink(e.target.value)}
                                            placeholder="https://meet.google.com/..."
                                            className="w-full px-4 py-2.5 bg-white border border-emerald-200 rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-emerald-500/20 placeholder:text-emerald-300"
                                        />
                                        <p className="mt-1.5 text-[10px] text-emerald-600/80">This link will be emailed to the client when you confirm.</p>
                                    </div>

                                    <div>
                                        <label className="text-[10px] font-bold text-emerald-700 uppercase tracking-widest block mb-2">Admin Notes (Optional)</label>
                                        <textarea 
                                            value={adminNotes}
                                            onChange={(e) => setAdminNotes(e.target.value)}
                                            placeholder="Internal notes or prep info..."
                                            className="w-full px-4 py-2.5 bg-white border border-emerald-200 rounded-lg text-[13px] outline-none focus:ring-2 focus:ring-emerald-500/20 min-h-[80px]"
                                        />
                                    </div>
                                </div>
                            )}

                            {/* Section: Challenge */}
                            <div>
                                <label className="text-[10px] font-bold text-[#8C92AC] uppercase tracking-widest flex items-center gap-2 mb-3">
                                    <MessageSquare className="h-3.5 w-3.5 text-accent" />
                                    The Marketing Challenge
                                </label>
                                <div className="bg-white border border-[#F0EDE8] rounded-xl p-4 italic text-[13px] text-ink leading-relaxed">
                                    "{selectedBooking.challenge || 'No specific challenge provided.'}"
                                </div>
                            </div>
                        </div>

                        {/* Modal Footer */}
                        <div className="px-6 py-4 border-t border-[#F0EDE8] bg-[#FAFAF8] flex items-center justify-between">
                            <div className="flex items-center gap-2">
                                {selectedBooking.status === 'Pending' && (
                                    <button
                                        onClick={() => updateStatus(selectedBooking.id, 'Confirmed')}
                                        className="px-4 py-2 bg-emerald-600 text-white text-[12px] font-bold rounded-lg hover:bg-emerald-700 transition-colors flex items-center gap-2"
                                    >
                                        <CheckCircle className="h-3.5 w-3.5" /> Confirm Slot
                                    </button>
                                )}
                                {selectedBooking.status === 'Confirmed' && (
                                    <button
                                        onClick={() => updateStatus(selectedBooking.id, 'Completed')}
                                        className="px-4 py-2 bg-ink text-white text-[12px] font-bold rounded-lg hover:bg-primary transition-colors flex items-center gap-2"
                                    >
                                        <Clock className="h-3.5 w-3.5" /> Mark Completed
                                    </button>
                                )}
                                {(selectedBooking.status === 'Confirmed' || selectedBooking.status === 'Pending') && (
                                    <button
                                        onClick={() => updateStatus(selectedBooking.id, 'Cancelled')}
                                        className="px-4 py-2 border border-[#E8E6DF] bg-white text-[#8C92AC] text-[12px] font-bold rounded-lg hover:bg-red-50 hover:text-red-600 hover:border-red-100 transition-colors flex items-center gap-2"
                                    >
                                        <XCircle className="h-3.5 w-3.5" /> Cancel Booking
                                    </button>
                                )}
                            </div>
                            <div className="flex items-center gap-2">
                                <button
                                    onClick={() => deleteBooking(selectedBooking.id)}
                                    className="p-2 text-[#8C92AC] hover:text-red-600 transition-colors"
                                    title="Delete Permanent"
                                >
                                    <Trash2 className="h-4 w-4" />
                                </button>
                            </div>
                        </div>
                    </div>
                )}
            </Modal>
        </AdminLayout>
    );
}
