import { Head, router } from '@inertiajs/react';
import { format } from 'date-fns';
import { CalendarDays, Camera, ChevronDown, Maximize2, Minimize2, QrCode, Search, X } from 'lucide-react';
import {
    useCallback,
    useEffect,
    useMemo,
    useRef,
    useState,
} from 'react';
import type { ReactNode } from 'react';
import type { DateRange } from 'react-day-picker';
import { toast } from 'sonner';
import {
    BookingDetailPanel

} from '@/components/booking/booking-detail-panel';
import type {BookingDetail} from '@/components/booking/booking-detail-panel';
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 { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import {
    Combobox,
    ComboboxContent,
    ComboboxEmpty,
    ComboboxInput,
    ComboboxItem,
    ComboboxList,
} from '@/components/ui/combobox';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import AppLayout from '@/layouts/app-layout';
import { useBookingListGlobalExpanded, BOOKING_LIST_EXPANDED_KEYS } from '@/hooks/use-booking-list-global-expanded';
import { useBookingDateTimeFormatters } from '@/hooks/use-booking-timezone';
import { serviceStatusBorderClass } from '@/lib/service-status-border';
import { cn } from '@/lib/utils';

type Job = {
    id: number;
    uuid: string;
    scheduled_at: string | null;
    created_at?: string | null;
    service_type?: 'mobile' | 'fixed' | null;
    service_address: string | null;
    service_city: string | null;
    service_state: string | null;
    service_zip: string | null;
    service_status: string;
    payment_status: string;
    payment_method?: string;
    notes?: string | null;
    internal_notes?: string | null;
    total: number;
    allowed_next_statuses: string[];
    customer: {
        id?: number | null;
        name: string | null;
        email?: string | null;
        phone: string | null;
    };
    technician?: {
        id?: number | null;
        name: string | null;
    } | null;
    vehicle: {
        make: string | null;
        model: string | null;
        year?: number | null;
        color: string | null;
        size: string | null;
    };
    package: {
        id?: number | null;
        name: string | null;
    };
    location?: {
        name: string | null;
        address: string | null;
        city: string | null;
        state: string | null;
        zip: string | null;
    } | null;
    addons?: Array<{ id: number; name: string; pivot: { price: number } }>;
};

type Props = {
    jobs: Job[];
    locations: string[];
};

type JobCardProps = {
    job: Job;
    highlight: boolean;
    defaultOpen: boolean;
    onUpdateStatus: (jobId: number, status: string) => void;
    onViewDetails: (jobId: number) => void;
};

type DetectedBarcode = {
    rawValue?: string;
};

type BarcodeDetectorInstance = {
    detect: (source: ImageBitmapSource) => Promise<DetectedBarcode[]>;
};

type BarcodeDetectorConstructor = new (options?: {
    formats?: string[];
}) => BarcodeDetectorInstance;

type DatePreset = 'all' | 'today' | 'this_week' | 'this_month' | 'last_30_days' | 'custom';

const DATE_PRESETS: { value: DatePreset; label: string }[] = [
    { value: 'all', label: 'All dates' },
    { value: 'today', label: 'Today' },
    { value: 'this_week', label: 'This week' },
    { value: 'this_month', label: 'This month' },
    { value: 'last_30_days', label: 'Last 30 days' },
    { value: 'custom', label: 'Custom range' },
];

const UUID_REGEX =
    /[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i;
const COMPLETED_STATUSES = new Set(['completed', 'cancelled', 'no_show']);
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 FilterField({ label, children }: { label: string; children: ReactNode }) {
    return (
        <div className="flex min-w-0 flex-col gap-1.5">
            <Label className="text-xs font-medium text-muted-foreground">{label}</Label>
            {children}
        </div>
    );
}

function extractBookingUuid(value: string): string | null {
    const trimmed = value.trim();

    if (trimmed.length === 0) {
        return null;
    }

    if (UUID_REGEX.test(trimmed)) {
        return trimmed.match(UUID_REGEX)?.[0] ?? null;
    }

    try {
        const parsed = new URL(trimmed);

        return parsed.pathname.match(UUID_REGEX)?.[0] ?? null;
    } catch {
        return trimmed.match(UUID_REGEX)?.[0] ?? null;
    }
}

function TechnicianJobCard({
    job,
    highlight,
    defaultOpen,
    onUpdateStatus,
    onViewDetails,
}: JobCardProps) {
    const { formatDate, formatTime } = useBookingDateTimeFormatters();
    const [open, setOpen] = useState(defaultOpen);

    return (
        <div
            className={cn(
                'overflow-hidden rounded-2xl border border-border border-l-[3px] bg-card shadow-sm',
                serviceStatusBorderClass(job.service_status),
            )}
        >
            <button
                type="button"
                onClick={() => setOpen((value) => !value)}
                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">
                        <StatusBadge status={job.service_status} />
                        <p className="font-mono text-xs text-muted-foreground">
                            #{job.uuid.slice(0, 8).toUpperCase()}
                        </p>
                    </div>
                    <div className="flex items-center gap-2">
                        <p className={cn('font-bold', highlight ? 'text-primary' : 'text-foreground')}>
                            ${(job.total / 100).toFixed(2)}
                        </p>
                        <ChevronDown
                            className={cn(
                                'size-4 shrink-0 text-muted-foreground transition-transform duration-200',
                                open && '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">{job.customer.name ?? '—'}</p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Vehicle</p>
                        <p className="text-sm font-medium capitalize">{job.vehicle.size ?? job.vehicle.make ?? '—'}</p>
                        <p className="truncate text-xs text-muted-foreground">{job.vehicle.make} {job.vehicle.model}</p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Date</p>
                        <p className="text-sm font-medium">
                            {job.scheduled_at
                                ? formatDate(job.scheduled_at)
                                : 'Date TBD'}
                        </p>
                    </div>
                    <div>
                        <p className="text-xs text-muted-foreground">Time</p>
                        <p className="text-sm font-medium">
                            {job.scheduled_at
                                ? formatTime(job.scheduled_at)
                                : 'Time TBD'}
                        </p>
                    </div>
                </div>
            </button>

            {open ? (
                <div className="px-4 py-3 border-t">
                    {(() => {
                        const addonTotal = (job.addons ?? []).reduce((sum, a) => sum + a.pivot.price, 0);
                        const packagePrice = job.total - addonTotal;

                        return (
                            <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">{job.package.name ?? 'Car Wash'}</p>
                                    </div>
                                    <p className="shrink-0 font-medium">${(packagePrice / 100).toFixed(2)}</p>
                                </div>
                                {(job.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>
                        );
                    })()}
                    <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={job.service_status}
                            onChange={(e) => {
                                if (e.target.value && e.target.value !== job.service_status) {
                                    onUpdateStatus(job.id, e.target.value);
                                }
                            }}
                        >
                            {ALL_SERVICE_STATUSES.map(({ value, label }) => (
                                <NativeSelectOption key={value} value={value}>
                                    {label}
                                </NativeSelectOption>
                            ))}
                        </NativeSelect>
                    </div>
                    <button
                        type="button"
                        onClick={() => onViewDetails(job.id)}
                        className="mt-3 w-full rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors hover:bg-muted"
                    >
                        View details
                    </button>
                </div>
            ) : null}
        </div>
    );
}

export default function TechnicianJobsIndex({ jobs, locations = [] }: Props) {
    const { formatDateTime } = useBookingDateTimeFormatters();
    const [activeTab, setActiveTab] = useState<'active' | 'checked_in' | 'completed' | 'cancelled'>('active');
    const [viewingJobId, setViewingJobId] = useState<number | null>(null);
    const [search, setSearch] = useState('');
    const [locationFilter, setLocationFilter] = useState<string | null>(null);
    const [statusFilter, setStatusFilter] = useState('all');
    const { allExpanded, expandRevision, toggleAllExpanded } = useBookingListGlobalExpanded(
        BOOKING_LIST_EXPANDED_KEYS.technicianJobs,
    );
    const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');
    const [datePreset, setDatePreset] = useState<DatePreset>('all');
    const [customDateRange, setCustomDateRange] = useState<{ from: Date | undefined; to: Date | undefined }>({ from: undefined, to: undefined });
    const [datePickerOpen, setDatePickerOpen] = useState(false);
    const [draftDateRange, setDraftDateRange] = useState<DateRange>({ from: undefined, to: undefined });
    const [scanDialogOpen, setScanDialogOpen] = useState(false);
    const [scanValue, setScanValue] = useState('');
    const [scanError, setScanError] = useState<string | null>(null);
    const [cameraStatus, setCameraStatus] = useState<
        'idle' | 'starting' | 'ready' | 'unsupported' | 'blocked'
    >('idle');
    const videoRef = useRef<HTMLVideoElement | null>(null);
    const streamRef = useRef<MediaStream | null>(null);
    const detectorIntervalRef = useRef<number | null>(null);
    const lastScannedRef = useRef<string | null>(null);

    const updateStatus = (
        jobId: number,
        status: string,
        options?: { onSuccess?: () => void; onError?: () => void },
    ) => {
        router.post(`/technician/jobs/${jobId}/status`, {
            status,
        }, {
            preserveScroll: true,
            preserveState: true,
            onSuccess: options?.onSuccess,
            onError: options?.onError,
        });
    };


    const locationOptions = locations.length > 0
        ? locations
        : Array.from(new Set(jobs.map((j) => j.location?.name).filter(Boolean))) as string[];

    const locationFilteredJobs = locationFilter
        ? jobs.filter((j) => j.location?.name === locationFilter)
        : jobs;

    const activeDateRange = useMemo<{ from: Date; to: Date } | null>(() => {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        const endOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999);

        switch (datePreset) {
            case 'today':

                return { from: today, to: endOfDay(today) };

            case 'this_week': {
                const from = new Date(today);
                from.setDate(today.getDate() - today.getDay());
                const to = new Date(from);
                to.setDate(from.getDate() + 6);

                return { from, to: endOfDay(to) };
            }

            case 'this_month': {
                const from = new Date(today.getFullYear(), today.getMonth(), 1);
                const to = new Date(today.getFullYear(), today.getMonth() + 1, 0);

                return { from, to: endOfDay(to) };
            }

            case 'last_30_days': {
                const from = new Date(today);
                from.setDate(today.getDate() - 30);

                return { from, to: endOfDay(today) };
            }

            case 'custom':
                if (customDateRange.from && customDateRange.to) {
                    return { from: customDateRange.from, to: endOfDay(customDateRange.to) };
                }

                return null;

            default:

                return null;
        }
    }, [datePreset, customDateRange]);

    const dateFilteredJobs = useMemo(() => {
        if (!activeDateRange) {
            return locationFilteredJobs;
        }

        return locationFilteredJobs.filter((job) => {
            if (!job.scheduled_at) {
                return true;
            }

            const d = new Date(job.scheduled_at);

            return d >= activeDateRange.from && d <= activeDateRange.to;
        });
    }, [locationFilteredJobs, activeDateRange]);

    const customRangeLabel = customDateRange.from
        ? customDateRange.to
            ? `${format(customDateRange.from, 'MMM d, yyyy')} – ${format(customDateRange.to, 'MMM d, yyyy')}`
            : format(customDateRange.from, 'MMM d, yyyy')
        : 'Select range';

    const searchableJobs = useMemo(() => {
        const query = search.trim().toLowerCase();
        const normalizedBookingQuery = query.replace(/^#/, '');

        if (query.length === 0) {
            return dateFilteredJobs;
        }

        return dateFilteredJobs.filter((job) => {
            const bookingCode = job.uuid.slice(0, 8).toLowerCase();
            const scheduledAt = job.scheduled_at
                ? formatDateTime(job.scheduled_at).toLowerCase()
                : '';
            const searchable = [
                job.uuid,
                job.customer.name ?? '',
                job.customer.phone ?? '',
                job.package.name ?? '',
                job.vehicle.make ?? '',
                job.vehicle.model ?? '',
                job.vehicle.color ?? '',
                job.vehicle.size ?? '',
                job.service_status,
                job.payment_status,
                job.service_address ?? '',
                job.service_city ?? '',
                job.service_state ?? '',
                job.service_zip ?? '',
                scheduledAt,
            ]
                .join(' ')
                .toLowerCase();

            return searchable.includes(query) || bookingCode.includes(normalizedBookingQuery);
        });
    }, [dateFilteredJobs, search, formatDateTime]);

    const jobsByUuid = useMemo(
        () => new Map(jobs.map((job) => [job.uuid.toLowerCase(), job])),
        [jobs],
    );
    const statusOptions = useMemo(() => {
        const options = new Set<string>();

        jobs.forEach((job) => {
            options.add(job.service_status);
        });

        return ['all', ...Array.from(options)];
    }, [jobs]);
    const statusFilteredJobs = useMemo(() => {
        if (statusFilter === 'all') {
            return searchableJobs;
        }

        return searchableJobs.filter((job) => job.service_status === statusFilter);
    }, [searchableJobs, statusFilter]);
    const selectedJob = useMemo(
        () => jobs.find((job) => Number(job.id) === Number(viewingJobId)) ?? null,
        [jobs, viewingJobId],
    );
    const selectedBookingDetail = useMemo<BookingDetail | null>(() => {
        if (!selectedJob) {
            return null;
        }

        return {
            id: selectedJob.id,
            uuid: selectedJob.uuid,
            payment_status: selectedJob.payment_status,
            payment_method: selectedJob.payment_method,
            service_status: selectedJob.service_status,
            service_type: selectedJob.service_type ?? null,
            scheduled_at: selectedJob.scheduled_at ?? new Date().toISOString(),
            total: selectedJob.total,
            notes: selectedJob.notes ?? null,
            internal_notes: selectedJob.internal_notes ?? null,
            vehicle: {
                make: selectedJob.vehicle.make ?? '',
                model: selectedJob.vehicle.model ?? '',
                year: selectedJob.vehicle.year ?? new Date().getFullYear(),
                size: selectedJob.vehicle.size ?? undefined,
                color: selectedJob.vehicle.color ?? null,
            },
            package: selectedJob.package.name
                ? {
                    id: selectedJob.package.id ?? selectedJob.id,
                    name: selectedJob.package.name,
                }
                : null,
            location: selectedJob.location?.name
                ? {
                    name: selectedJob.location.name,
                    address: selectedJob.location.address,
                    city: selectedJob.location.city,
                    state: selectedJob.location.state,
                    zip: selectedJob.location.zip,
                }
                : null,
            service_address: selectedJob.service_address ?? null,
            service_city: selectedJob.service_city ?? null,
            service_state: selectedJob.service_state ?? null,
            service_zip: selectedJob.service_zip ?? null,
            customer: selectedJob.customer.name
                ? {
                    id: selectedJob.customer.id ?? selectedJob.id,
                    name: selectedJob.customer.name,
                    email: selectedJob.customer.email ?? '',
                }
                : null,
            technician: selectedJob.technician?.name
                ? {
                    id: selectedJob.technician.id ?? selectedJob.id,
                    name: selectedJob.technician.name,
                }
                : null,
            addons: selectedJob.addons ?? [],
        };
    }, [selectedJob]);
    const sortedJobs = useMemo(() => {
        return [...statusFilteredJobs].sort((a, b) => {
            const aTime = a.scheduled_at ? new Date(a.scheduled_at).getTime() : 0;
            const bTime = b.scheduled_at ? new Date(b.scheduled_at).getTime() : 0;

            return sortOrder === 'asc' ? aTime - bTime : bTime - aTime;
        });
    }, [statusFilteredJobs, sortOrder]);

    const checkedInJobs = sortedJobs.filter(
        (job) => job.service_status === 'arrived',
    );
    const activeJobs = sortedJobs.filter(
        (job) => !COMPLETED_STATUSES.has(job.service_status) && job.service_status !== 'arrived',
    );
    const completedJobs = sortedJobs.filter(
        (job) => job.service_status === 'completed',
    );
    const cancelledJobs = sortedJobs.filter(
        (job) => job.service_status === 'cancelled' || job.service_status === 'no_show',
    );

    const hasActiveFilters =
        search.trim().length > 0
        || locationFilter !== null
        || statusFilter !== 'all'
        || datePreset !== 'all';

    const clearFilters = () => {
        setSearch('');
        setLocationFilter(null);
        setStatusFilter('all');
        setDatePreset('all');
        setCustomDateRange({ from: undefined, to: undefined });
    };

    const currentTabJobs =
        activeTab === 'active' ? activeJobs
        : activeTab === 'checked_in' ? checkedInJobs
        : activeTab === 'cancelled' ? cancelledJobs
        : completedJobs;

    const stopScanner = useCallback(() => {
        if (detectorIntervalRef.current !== null) {
            window.clearInterval(detectorIntervalRef.current);
            detectorIntervalRef.current = null;
        }

        if (streamRef.current) {
            streamRef.current.getTracks().forEach((track) => track.stop());
            streamRef.current = null;
        }
    }, []);

    const submitScan = useCallback((payload: string) => {
        if (lastScannedRef.current === payload) {
            return;
        }

        lastScannedRef.current = payload;

        const bookingUuid = extractBookingUuid(payload);

        if (!bookingUuid) {
            setScanError('Scan did not include a valid booking QR code.');

            return;
        }

        const matchedJob = jobsByUuid.get(bookingUuid.toLowerCase());

        if (!matchedJob) {
            stopScanner();
            setScanError('This booking is not in your current jobs list.');
            setSearch(bookingUuid.slice(0, 8));
            toast.error('Booking not found in your assigned jobs.');

            return;
        }

        setSearch(matchedJob.uuid.slice(0, 8).toUpperCase());
        setActiveTab(
            matchedJob.service_status === 'completed' ? 'completed'
            : matchedJob.service_status === 'cancelled' || matchedJob.service_status === 'no_show' ? 'cancelled'
            : matchedJob.service_status === 'arrived' ? 'checked_in'
            : 'active',
        );

        if (!matchedJob.allowed_next_statuses.includes('arrived')) {
            setScanDialogOpen(false);
            setScanError(null);
            setScanValue('');

            if (matchedJob.service_status === 'arrived') {
                toast.info('Customer is already checked in.');
            } else {
                toast.error(`Cannot check in — current status: ${matchedJob.service_status.replaceAll('_', ' ')}.`);
            }

            return;
        }

        setScanDialogOpen(false);
        setScanError(null);
        setScanValue('');
        updateStatus(matchedJob.id, 'arrived', {
            onSuccess: () => {
                toast.success('Customer checked in — status updated to Arrived.');
            },
            onError: () => {
                toast.error('Check-in failed. Try scanning again.');
            },
        });
    }, [jobsByUuid, stopScanner]);

    useEffect(() => {
        if (!scanDialogOpen) {
            stopScanner();

            return;
        }

        const startScanner = async () => {
            setScanError(null);
            setCameraStatus('starting');

            const supportsCamera = navigator.mediaDevices?.getUserMedia;

            if (!supportsCamera) {
                setCameraStatus('unsupported');

                return;
            }

            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: { ideal: 'environment' } },
                    audio: false,
                });

                streamRef.current = stream;

                if (videoRef.current) {
                    videoRef.current.srcObject = stream;
                    await videoRef.current.play();
                }

                const BarcodeDetectorApi = (
                    window as Window & { BarcodeDetector?: BarcodeDetectorConstructor }
                ).BarcodeDetector;

                if (!BarcodeDetectorApi) {
                    setCameraStatus('unsupported');

                    return;
                }

                const detector = new BarcodeDetectorApi({
                    formats: ['qr_code'],
                });

                detectorIntervalRef.current = window.setInterval(async () => {
                    if (!videoRef.current) {
                        return;
                    }

                    const results = await detector.detect(videoRef.current);
                    const value = results[0]?.rawValue;

                    if (!value) {
                        return;
                    }

                    submitScan(value);
                }, 500);

                setCameraStatus('ready');
            } catch {
                stopScanner();
                setCameraStatus('blocked');
            }
        };

        startScanner();

        return () => stopScanner();
    }, [scanDialogOpen, stopScanner, submitScan]);

    const tabCountBadge = (
        count: number,
        variant: 'blue' | 'green' | 'sky' | 'purple' | 'red',
    ) => (
        <Badge
            variant={variant}
            className="pointer-events-none flex size-6 min-w-6 shrink-0 items-center justify-center rounded-full p-0 text-[11px] font-bold leading-none tabular-nums shadow-sm"
        >
            {count}
        </Badge>
    );

    const renderJobGrid = (items: Job[], highlight: boolean) => (
        <div className="grid grid-cols-1 items-start gap-6 md:grid-cols-2 xl:grid-cols-4">
            {items.map((job) => (
                <TechnicianJobCard
                    key={`${job.id}-${expandRevision}`}
                    job={job}
                    highlight={highlight}
                    defaultOpen={allExpanded}
                    onUpdateStatus={updateStatus}
                    onViewDetails={setViewingJobId}
                />
            ))}
        </div>
    );

    return (
        <>
            <Head title="Today's jobs" />
            <div className="layout flex h-full flex-1 flex-col gap-8">
                <PageHeader
                    title="Today's jobs"
                    description="Active jobs are scheduled for today. Completed shows your finished jobs from the last 30 days."
                />

                {jobs.length > 0 ? (
                    <div className="rounded-2xl border bg-card p-5">
                        <div className="flex flex-col gap-4">
                            {/* Search + Scan check-in */}
                            <div className="flex items-end gap-2">
                                <div className="min-w-0 flex-1">
                                    <FilterField label="Search">
                                        <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={(event) => setSearch(event.target.value)}
                                                placeholder="Customer, booking #, status, address, 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>
                                    </FilterField>
                                </div>
                                <Button
                                    type="button"
                                    variant="outline"
                                    onClick={() => setScanDialogOpen(true)}
                                    className="shrink-0"
                                >
                                    <QrCode className="size-4" />
                                    Scan check-in
                                </Button>
                            </div>

                            {/* Location + Status + Sort + Clear */}
                            <div className="flex flex-col gap-3 xl:flex-row xl:items-end">
                                <div className="grid flex-1 grid-cols-1 gap-3 sm:grid-cols-3">
                                    <FilterField label="Location">
                                        {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-full"
                                                />
                                                <ComboboxContent>
                                                    <ComboboxEmpty>No locations found.</ComboboxEmpty>
                                                    <ComboboxList>
                                                        {(loc: string) => (
                                                            <ComboboxItem key={loc} value={loc}>
                                                                {loc}
                                                            </ComboboxItem>
                                                        )}
                                                    </ComboboxList>
                                                </ComboboxContent>
                                            </Combobox>
                                        ) : (
                                            <p className="text-sm text-muted-foreground">No locations</p>
                                        )}
                                    </FilterField>
                                    <FilterField label="Status">
                                        <NativeSelect
                                            className="w-full"
                                            value={statusFilter}
                                            onChange={(event) => setStatusFilter(event.target.value)}
                                        >
                                            {statusOptions.map((status) => (
                                                <option key={status} value={status}>
                                                    {status === 'all'
                                                        ? 'All statuses'
                                                        : status.replaceAll('_', ' ')}
                                                </option>
                                            ))}
                                        </NativeSelect>
                                    </FilterField>
                                    <FilterField label="Sort by">
                                        <Select value={sortOrder} onValueChange={(v) => setSortOrder(v as 'asc' | 'desc')}>
                                            <SelectTrigger className="w-full">
                                                <SelectValue />
                                            </SelectTrigger>
                                            <SelectContent>
                                                <SelectItem value="asc">Upcoming first</SelectItem>
                                                <SelectItem value="desc">Latest first</SelectItem>
                                            </SelectContent>
                                        </Select>
                                    </FilterField>
                                </div>
                                {hasActiveFilters ? (
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="sm"
                                        className="xl:self-end"
                                        onClick={clearFilters}
                                    >
                                        Clear filters
                                    </Button>
                                ) : null}
                            </div>
                        </div>
                    </div>
                ) : null}

                {jobs.length === 0 ? (
                    <EmptyState
                        title="No jobs scheduled"
                        description="No jobs are assigned for today."
                    />
                ) : null}

                {jobs.length > 0 ? (
                    <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'active' | 'checked_in' | 'completed' | 'cancelled')}>
                        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                            <TabsList className="w-full sm:w-auto">
                                <TabsTrigger value="active" className="gap-2">
                                    Active
                                    {tabCountBadge(activeJobs.length, 'blue')}
                                </TabsTrigger>
                                <TabsTrigger value="checked_in" className="gap-2">
                                    Checked-In
                                    {tabCountBadge(checkedInJobs.length, 'sky')}
                                </TabsTrigger>
                                <TabsTrigger value="completed" className="gap-2">
                                    Completed
                                    {tabCountBadge(completedJobs.length, 'green')}
                                </TabsTrigger>
                                <TabsTrigger value="cancelled" className="gap-2">
                                    Cancelled
                                    {tabCountBadge(cancelledJobs.length, 'red')}
                                </TabsTrigger>
                            </TabsList>
                            <div className="flex shrink-0 items-center gap-2">
                                <Select value={datePreset} onValueChange={(v) => setDatePreset(v as DatePreset)}>
                                    <SelectTrigger size="sm" className="w-36">
                                        <SelectValue />
                                    </SelectTrigger>
                                    <SelectContent>
                                        {DATE_PRESETS.map((p) => (
                                            <SelectItem key={p.value} value={p.value}>
                                                {p.label}
                                            </SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                                {datePreset === 'custom' ? (
                                    <Popover
                                        open={datePickerOpen}
                                        onOpenChange={(open) => {
                                            if (open) {
                                                setDraftDateRange({ from: customDateRange.from, to: customDateRange.to });
                                            }

                                            setDatePickerOpen(open);
                                        }}
                                    >
                                        <PopoverTrigger asChild>
                                            <Button variant="outline" size="sm" className="w-[240px] justify-start font-normal">
                                                <CalendarDays className="size-4" />
                                                {customRangeLabel}
                                            </Button>
                                        </PopoverTrigger>
                                        <PopoverContent align="end" className="w-auto p-0">
                                            <Calendar
                                                mode="range"
                                                numberOfMonths={2}
                                                selected={draftDateRange.from ? draftDateRange : undefined}
                                                onSelect={(range) => setDraftDateRange(range ?? { from: undefined, to: undefined })}
                                                defaultMonth={draftDateRange.from ?? new Date()}
                                            />
                                            <div className="flex items-center justify-end gap-2 border-t p-3">
                                                <Button
                                                    variant="ghost"
                                                    size="sm"
                                                    onClick={() => setDraftDateRange({ from: undefined, to: undefined })}
                                                >
                                                    Clear
                                                </Button>
                                                <Button
                                                    size="sm"
                                                    disabled={!draftDateRange.from || !draftDateRange.to}
                                                    onClick={() => {
                                                        if (!draftDateRange.from || !draftDateRange.to) {
                                                            return;
                                                        }

                                                        setCustomDateRange({ from: draftDateRange.from, to: draftDateRange.to });
                                                        setDatePickerOpen(false);
                                                    }}
                                                >
                                                    Apply
                                                </Button>
                                            </div>
                                        </PopoverContent>
                                    </Popover>
                                ) : null}
                                {currentTabJobs.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}
                            </div>
                        </div>
                        <TabsContent value="active">
                            {activeJobs.length > 0 ? (
                                renderJobGrid(activeJobs, true)
                            ) : (
                                <EmptyState
                                    title="No active jobs"
                                    description="All assigned jobs are completed for today."
                                />
                            )}
                        </TabsContent>
                        <TabsContent value="checked_in">
                            {checkedInJobs.length > 0 ? (
                                renderJobGrid(checkedInJobs, true)
                            ) : (
                                <EmptyState
                                    title="No checked-in customers"
                                    description="Customers who have arrived will appear here."
                                />
                            )}
                        </TabsContent>
                        <TabsContent value="completed">
                            {completedJobs.length > 0 ? (
                                renderJobGrid(completedJobs, false)
                            ) : (
                                <EmptyState
                                    title="No completed jobs"
                                    description="Completed jobs will appear here."
                                />
                            )}
                        </TabsContent>
                        <TabsContent value="cancelled">
                            {cancelledJobs.length > 0 ? (
                                renderJobGrid(cancelledJobs, false)
                            ) : (
                                <EmptyState
                                    title="No cancelled jobs"
                                    description="Cancelled and no-show bookings will appear here."
                                />
                            )}
                        </TabsContent>
                    </Tabs>
                ) : null}
            </div>

            <Dialog
                open={scanDialogOpen}
                onOpenChange={(open) => {
                    setScanDialogOpen(open);

                    if (!open) {
                        setCameraStatus('idle');
                        setScanError(null);
                        setScanValue('');
                        lastScannedRef.current = null;
                    }
                }}
            >
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Scan customer check-in QR</DialogTitle>
                        <DialogDescription>
                            Scan the customer QR code to auto mark a booking as arrived.
                        </DialogDescription>
                    </DialogHeader>
                    <div className="space-y-4">
                        <div className="overflow-hidden rounded-lg border bg-black/90">
                            <video
                                ref={videoRef}
                                className="h-56 w-full object-cover"
                                muted
                                playsInline
                            />
                        </div>
                        {cameraStatus === 'starting' ? (
                            <p className="text-muted-foreground text-xs">
                                Starting camera scanner...
                            </p>
                        ) : null}
                        {cameraStatus === 'ready' ? (
                            <p className="text-muted-foreground text-xs">
                                Point camera at a booking QR code.
                            </p>
                        ) : null}
                        {cameraStatus === 'unsupported' ? (
                            <p className="text-muted-foreground text-xs">
                                Camera QR scan is not supported in this browser. Use manual scan input below.
                            </p>
                        ) : null}
                        {cameraStatus === 'blocked' ? (
                            <p className="text-destructive text-xs">
                                Camera access is blocked. Allow camera access, or use manual scan input below.
                            </p>
                        ) : null}
                        <form
                            className="space-y-2"
                            onSubmit={(event) => {
                                event.preventDefault();
                                submitScan(scanValue);
                            }}
                        >
                            <Label htmlFor="scan-value">
                                QR content (works with external scanner paste/input)
                            </Label>
                            <div className="flex gap-2">
                                <Input
                                    id="scan-value"
                                    value={scanValue}
                                    onChange={(event) => setScanValue(event.target.value)}
                                    placeholder="Paste scanned URL or booking UUID"
                                    autoComplete="off"
                                />
                                <Button type="submit">
                                    <Camera className="mr-1.5 size-4" />
                                    Check in
                                </Button>
                            </div>
                        </form>
                        {scanError ? (
                            <p className="text-destructive text-xs">{scanError}</p>
                        ) : null}
                    </div>
                </DialogContent>
            </Dialog>

            <FormDrawer
                open={viewingJobId !== null}
                onOpenChange={(open) => {
                    if (!open) {
                        setViewingJobId(null);
                    }
                }}
                title={
                    selectedJob
                        ? `Booking #${selectedJob.uuid.slice(0, 8).toUpperCase()}`
                        : 'Booking details'
                }
                description={selectedJob?.customer.name ?? undefined}
                direction="right"
                className="w-full max-w-3xl"
            >
                {selectedBookingDetail ? (
                    <BookingDetailPanel booking={selectedBookingDetail} showTracking={false} />
                ) : null}
            </FormDrawer>
        </>
    );
}

TechnicianJobsIndex.layout = (page: ReactNode) => (
    <AppLayout
        breadcrumbs={[
            {
                title: "Today's jobs",
                href: '/technician/jobs',
            },
        ]}
    >
        {page}
    </AppLayout>
);
