import { Head, router } from '@inertiajs/react';
import { ChevronDown, MapPin, Maximize2, Minimize2, Search, User, X } from 'lucide-react';
import type { ReactNode } from 'react';
import { useState } from 'react';
import { EmptyState } from '@/components/layout/empty-state';
import { FormDrawer } from '@/components/layout/form-drawer';
import { PageHeader } from '@/components/layout/page-header';
import { StatusBadge } from '@/components/status-badge';
import { Button } from '@/components/ui/button';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import { Input } from '@/components/ui/input';
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { BOOKING_LIST_EXPANDED_KEYS, useBookingListGlobalExpanded } from '@/hooks/use-booking-list-global-expanded';
import { useBookingDateTimeFormatters } from '@/hooks/use-booking-timezone';
import AppLayout from '@/layouts/app-layout';
import { serviceStatusBorderClass } from '@/lib/service-status-border';
import { cn } from '@/lib/utils';
import { live as technicianJobsLive } from '@/routes/technician/jobs';

type ActiveBooking = {
    id: number;
    uuid: string;
    service_status: string;
    scheduled_at: string | null;
    total: number;
    customer: {
        id: number;
        name: string;
        email: string;
        phone: string | null;
    } | null;
    vehicle: {
        label: string;
        color: string | null;
        size: string;
    } | null;
    package_name: string | null;
    addons: Array<{ id: number; name: string; pivot: { price: number } }>;
    technician_name: string | null;
    location_label: string | null;
};

type Props = {
    active_bookings: ActiveBooking[];
    locations: string[];
};

type Customer = NonNullable<ActiveBooking['customer']>;

const ALL_SERVICE_STATUSES: { value: string; label: string }[] = [
    { value: 'scheduled', label: 'Scheduled' },
    { value: 'arrived', label: 'Arrived' },
    { value: 'in_progress', label: 'In progress' },
    { value: 'completed', label: 'Completed' },
    { value: 'cancelled', label: 'Cancelled' },
    { value: 'no_show', label: 'No show' },
];

function ActiveBookingCard({
    booking,
    defaultOpen,
    onUpdateStatus,
    onViewCustomer,
}: {
    booking: ActiveBooking;
    defaultOpen: boolean;
    onUpdateStatus: (id: number, status: string) => void;
    onViewCustomer: (customer: Customer) => void;
}) {
    const { formatDate, formatTime } = useBookingDateTimeFormatters();
    const [isOpen, setIsOpen] = useState(defaultOpen);
    const scheduledDate = booking.scheduled_at
        ? formatDate(booking.scheduled_at)
        : 'Date TBD';

    const scheduledTime = booking.scheduled_at
        ? formatTime(booking.scheduled_at)
        : 'Time TBD';

    const addonTotal = booking.addons.reduce((sum, a) => sum + a.pivot.price, 0);
    const packagePrice = booking.total - addonTotal;

    return (
        <div
            className={cn(
                'overflow-hidden rounded-2xl border border-l-[3px] bg-card shadow-sm',
                serviceStatusBorderClass(booking.service_status),
            )}
        >
            <button
                type="button"
                onClick={() => setIsOpen((v) => !v)}
                className="w-full bg-muted/40 px-4 py-3 text-sm transition-colors hover:bg-muted/60"
            >
                <div className="flex items-start justify-between gap-2">
                    <div className="flex flex-col items-start gap-1">
                        <div className="flex items-center gap-1.5">
                            <span className="relative flex size-2.5 shrink-0">
                                <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-orange-400 opacity-75" />
                                <span className={`relative inline-flex size-2.5 rounded-full ${booking.service_status === 'in_progress' ? 'bg-orange-500' : 'bg-teal-500'}`} />
                            </span>
                            <StatusBadge status={booking.service_status} />
                        </div>
                        <p className="font-mono text-xs text-muted-foreground">
                            #{booking.uuid.slice(0, 8).toUpperCase()}
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <p className="font-bold text-primary">
                            ${(booking.total / 100).toFixed(2)}
                        </p>
                        <ChevronDown
                            className={cn(
                                'size-4 shrink-0 text-muted-foreground transition-transform duration-200',
                                isOpen && 'rotate-180',
                            )}
                        />
                    </div>
                </div>

                <div className="mt-3 grid grid-cols-2 gap-2 text-left">
                    <div>
                        <p className="text-xs text-muted-foreground">Customer</p>
                        <p className="truncate text-sm font-medium">
                            {booking.customer?.name ?? '—'}
                        </p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Vehicle</p>
                        {booking.vehicle ? (
                            <>
                                <p className="text-sm font-medium capitalize">{booking.vehicle.size}</p>
                                <p className="truncate text-xs text-muted-foreground">{booking.vehicle.label}</p>
                            </>
                        ) : (
                            <p className="text-sm font-medium text-muted-foreground">—</p>
                        )}
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Date</p>
                        <p className="text-sm font-medium">{scheduledDate}</p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Time</p>
                        <p className="text-sm font-medium">{scheduledTime}</p>
                    </div>
                </div>
            </button>

            {isOpen ? (
                <div className="border-t px-4 py-3">
                    {/* Package + addons price breakdown */}
                    <div className="space-y-1">
                        <div className="flex items-start justify-between gap-2">
                            <div>
                                <p className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Package</p>
                                <p className="font-semibold">{booking.package_name ?? 'Car Wash'}</p>
                            </div>
                            <p className="shrink-0 font-medium">${(packagePrice / 100).toFixed(2)}</p>
                        </div>
                        {booking.addons.map((addon) => (
                            <div key={addon.id} className="flex items-center justify-between gap-2">
                                <p className="text-sm text-muted-foreground">+ {addon.name}</p>
                                <p className="shrink-0 text-sm text-muted-foreground">${(addon.pivot.price / 100).toFixed(2)}</p>
                            </div>
                        ))}
                    </div>

                    {/* Status select */}
                    <div className="mt-3 border-t pt-3">
                        <p className="mb-1.5 text-xs text-muted-foreground">Update status</p>
                        <NativeSelect
                            className="w-full"
                            value={booking.service_status}
                            onChange={(e) => {
                                if (e.target.value && e.target.value !== booking.service_status) {
                                    onUpdateStatus(booking.id, e.target.value);
                                }
                            }}
                        >
                            {ALL_SERVICE_STATUSES.map(({ value, label }) => (
                                <NativeSelectOption key={value} value={value}>
                                    {label}
                                </NativeSelectOption>
                            ))}
                        </NativeSelect>
                    </div>

                    {/* Tech + location */}
                    {booking.technician_name || booking.location_label ? (
                        <div className="mt-3 flex flex-wrap gap-3 border-t pt-3 text-sm text-muted-foreground">
                            {booking.technician_name ? (
                                <span>Tech: <span className="font-medium text-foreground">{booking.technician_name}</span></span>
                            ) : null}
                            {booking.location_label ? (
                                <span className="flex items-center gap-1">
                                    <MapPin className="size-3" />
                                    {booking.location_label}
                                </span>
                            ) : null}
                        </div>
                    ) : null}

                    {/* View customer */}
                    {booking.customer ? (
                        <button
                            type="button"
                            onClick={() => onViewCustomer(booking.customer!)}
                            className="mt-3 w-full rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors hover:bg-muted"
                        >
                            View customer
                        </button>
                    ) : null}
                </div>
            ) : null}
        </div>
    );
}

function BookingGrid({
    bookings,
    allExpanded,
    expandRevision,
    onUpdateStatus,
    onViewCustomer,
}: {
    bookings: ActiveBooking[];
    allExpanded: boolean;
    expandRevision: number;
    onUpdateStatus: (id: number, status: string) => void;
    onViewCustomer: (customer: Customer) => void;
}) {
    if (bookings.length === 0) {
        return (
            <EmptyState
                title="Nothing here"
                description="No bookings with this status right now."
            />
        );
    }

    return (
        <div className="grid grid-cols-1 items-start gap-4 md:grid-cols-2 xl:grid-cols-4">
            {bookings.map((b) => (
                <ActiveBookingCard
                    key={`${b.id}-${expandRevision}`}
                    booking={b}
                    defaultOpen={allExpanded}
                    onUpdateStatus={onUpdateStatus}
                    onViewCustomer={onViewCustomer}
                />
            ))}
        </div>
    );
}

export default function TechnicianJobsLive({ active_bookings, locations = [] }: Props) {
    const [search, setSearch] = useState('');
    const [locationFilter, setLocationFilter] = useState<string | null>(null);
    const [viewingCustomer, setViewingCustomer] = useState<Customer | null>(null);
    const { allExpanded, expandRevision, toggleAllExpanded } = useBookingListGlobalExpanded(
        BOOKING_LIST_EXPANDED_KEYS.technicianLive,
    );

    const locationOptions = locations.length > 0
        ? locations
        : Array.from(new Set(active_bookings.map((b) => b.location_label).filter(Boolean))) as string[];

    const searchedBookings = (() => {
        const q = search.trim().toLowerCase();

        if (q.length === 0) {
            return active_bookings;
        }

        return active_bookings.filter((b) => {
            const code = b.uuid.slice(0, 8).toLowerCase();
            const haystack = [
                b.uuid,
                b.customer?.name ?? '',
                b.customer?.phone ?? '',
                b.package_name ?? '',
                b.vehicle?.label ?? '',
                b.vehicle?.size ?? '',
                b.location_label ?? '',
                b.service_status,
            ].join(' ').toLowerCase();

            return haystack.includes(q) || code.includes(q.replace(/^#/, ''));
        });
    })();

    const filteredBookings = locationFilter
        ? searchedBookings.filter((b) => b.location_label === locationFilter)
        : searchedBookings;

    const inProgress = filteredBookings.filter((b) => b.service_status === 'in_progress');
    const arrived = filteredBookings.filter((b) => b.service_status === 'arrived');

    const updateStatus = (bookingId: number, status: string) => {
        router.post(`/technician/jobs/${bookingId}/status`, { status }, {
            preserveScroll: true,
            preserveState: true,
        });
    };

    return (
        <>
            <Head title="Live jobs" />
            <div className="flex h-full flex-1 flex-col gap-6">
                <div className="flex items-center gap-3">
                    <PageHeader title="Live" />
                    {active_bookings.length > 0 ? (
                        <span className="relative flex size-2.5">
                            <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-orange-400 opacity-75" />
                            <span className="relative inline-flex size-2.5 rounded-full bg-orange-500" />
                        </span>
                    ) : null}
                </div>

                {active_bookings.length > 0 ? (
                    <div className="relative">
                        <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
                        <Input
                            value={search}
                            onChange={(e) => setSearch(e.target.value)}
                            placeholder="Customer, booking #, status, or vehicle"
                            className="pl-9 pr-9"
                        />
                        {search.length > 0 ? (
                            <button
                                type="button"
                                className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
                                onClick={() => setSearch('')}
                            >
                                <X className="size-4" />
                            </button>
                        ) : null}
                    </div>
                ) : null}

                {active_bookings.length === 0 ? (
                    <EmptyState
                        title="Nothing active right now"
                        description="Bookings with arrived or in-progress status will appear here."
                    />
                ) : (
                    <Tabs defaultValue="all">
                        <div className="flex flex-wrap items-center justify-between gap-3">
                            <TabsList>
                                <TabsTrigger value="all" className="gap-2">
                                    All
                                    <span className="rounded-full bg-muted px-1.5 py-0.5 text-xs font-medium">
                                        {filteredBookings.length}
                                    </span>
                                </TabsTrigger>
                                <TabsTrigger value="in_progress" className="gap-2">
                                    In Progress
                                    {inProgress.length > 0 ? (
                                        <span className="rounded-full bg-orange-100 px-1.5 py-0.5 text-xs font-medium text-orange-700 dark:bg-orange-900/30 dark:text-orange-400">
                                            {inProgress.length}
                                        </span>
                                    ) : null}
                                </TabsTrigger>
                                <TabsTrigger value="arrived" className="gap-2">
                                    Arrived
                                    {arrived.length > 0 ? (
                                        <span className="rounded-full bg-teal-100 px-1.5 py-0.5 text-xs font-medium text-teal-700 dark:bg-teal-900/30 dark:text-teal-400">
                                            {arrived.length}
                                        </span>
                                    ) : null}
                                </TabsTrigger>
                            </TabsList>

                            <div className="flex items-center gap-2">
                                {filteredBookings.length > 0 ? (
                                    <Button
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        onClick={toggleAllExpanded}
                                    >
                                        {allExpanded ? (
                                            <>
                                                <Minimize2 className="size-4" />
                                                Collapse all
                                            </>
                                        ) : (
                                            <>
                                                <Maximize2 className="size-4" />
                                                Expand all
                                            </>
                                        )}
                                    </Button>
                                ) : null}
                                {locationOptions.length > 0 ? (
                                <Combobox
                                    items={locationOptions}
                                    itemToStringLabel={(loc: string) => loc}
                                    itemToStringValue={(loc: string) => loc}
                                    isItemEqualToValue={(a: string, b: string) => a === b}
                                    value={locationFilter}
                                    onValueChange={(val) => setLocationFilter(val as string | null)}
                                >
                                    <ComboboxInput
                                        placeholder="Filter by location…"
                                        showClear={locationFilter !== null}
                                        className="w-52"
                                    />
                                    <ComboboxContent>
                                        <ComboboxEmpty>No locations found.</ComboboxEmpty>
                                        <ComboboxList>
                                            {(loc: string) => (
                                                <ComboboxItem key={loc} value={loc}>
                                                    <MapPin className="size-3.5 text-muted-foreground" />
                                                    {loc}
                                                </ComboboxItem>
                                            )}
                                        </ComboboxList>
                                    </ComboboxContent>
                                </Combobox>
                                ) : null}
                            </div>
                        </div>

                        <TabsContent value="all" className="mt-4">
                            <BookingGrid
                                bookings={filteredBookings}
                                allExpanded={allExpanded}
                                expandRevision={expandRevision}
                                onUpdateStatus={updateStatus}
                                onViewCustomer={setViewingCustomer}
                            />
                        </TabsContent>
                        <TabsContent value="in_progress" className="mt-4">
                            <BookingGrid
                                bookings={inProgress}
                                allExpanded={allExpanded}
                                expandRevision={expandRevision}
                                onUpdateStatus={updateStatus}
                                onViewCustomer={setViewingCustomer}
                            />
                        </TabsContent>
                        <TabsContent value="arrived" className="mt-4">
                            <BookingGrid
                                bookings={arrived}
                                allExpanded={allExpanded}
                                expandRevision={expandRevision}
                                onUpdateStatus={updateStatus}
                                onViewCustomer={setViewingCustomer}
                            />
                        </TabsContent>
                    </Tabs>
                )}
            </div>

            {/* Customer detail drawer */}
            <FormDrawer
                open={viewingCustomer !== null}
                onOpenChange={(open) => {
                    if (!open) {
                        setViewingCustomer(null);
                    }
                }}
                title={viewingCustomer?.name ?? 'Customer'}
                description={viewingCustomer?.email ?? undefined}
                direction="right"
                className="w-full max-w-sm"
            >
                {viewingCustomer ? (
                    <div className="space-y-4 p-4">
                        <div className="flex items-center gap-3">
                            <div className="flex size-12 shrink-0 items-center justify-center rounded-full bg-muted">
                                <User className="size-5 text-muted-foreground" />
                            </div>
                            <div className="min-w-0">
                                <p className="truncate font-semibold">{viewingCustomer.name}</p>
                                <p className="truncate text-sm text-muted-foreground">{viewingCustomer.email}</p>
                            </div>
                        </div>
                        {viewingCustomer.phone ? (
                            <div className="rounded-lg border p-3">
                                <p className="text-xs text-muted-foreground">Phone</p>
                                <p className="mt-0.5 font-medium">{viewingCustomer.phone}</p>
                            </div>
                        ) : null}
                        <div className="rounded-lg border p-3">
                            <p className="text-xs text-muted-foreground">Email</p>
                            <p className="mt-0.5 font-medium">{viewingCustomer.email}</p>
                        </div>
                    </div>
                ) : null}
            </FormDrawer>
        </>
    );
}

TechnicianJobsLive.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            { title: 'Technician jobs', href: '/technician/jobs' },
            { title: 'Live', href: technicianJobsLive.url() },
        ]}
    >
        {page}
    </AppLayout>
);
