'use client';
import Image from 'next/image';
import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'convex/react';
import { api } from '~/convex/_generated/api';
import type { Id } from '~/convex/_generated/dataModel';
import { formatDate, formatTime } from '@/lib/utils';
import {
  DrawerClose,
  DrawerContent,
  DrawerFooter,
  DrawerHeader,
  DrawerTitle,
  Pagination,
  PaginationContent,
  PaginationNext,
  PaginationPrevious,
  ScrollArea,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
  Button,
  BasedAvatar,
} from '@/components/ui';

type StatusHistoryProps = {
  user?: (typeof api.statuses.getCurrentForAll._returnType)[0]['user'];
};

const PAGE_SIZE = 25;

export const StatusHistory = ({ user }: StatusHistoryProps) => {
  const [pageIndex, setPageIndex] = useState(0);
  // cursor for page N is the continueCursor returned from page N-1
  const [cursors, setCursors] = useState<(string | null)[]>([null]);

  const args = useMemo(() => {
    return {
      userId: user?.id,
      paginationOpts: {
        numItems: PAGE_SIZE,
        cursor: cursors[pageIndex] ?? null,
      },
    };
  }, [user?.id, cursors, pageIndex]);

  const data = useQuery(api.statuses.listHistory, args);

  // Track loading
  const isLoading = data === undefined;

  // When a page loads, cache its "next" cursor if we don't have it yet
  useEffect(() => {
    if (!data) return;
    const nextIndex = pageIndex + 1;
    setCursors((prev) => {
      const copy = [...prev];
      if (copy[nextIndex] === undefined) copy[nextIndex] = data.continueCursor;
      return copy;
    });
  }, [data, pageIndex]);

  const canPrev = pageIndex > 0;
  const canNext = !!data && data.continueCursor !== null;

  const handlePrev = () => {
    if (!canPrev) return;
    setPageIndex((p) => Math.max(0, p - 1));
  };

  const handleNext = () => {
    if (!canNext) return;
    setPageIndex((p) => p + 1);
  };

  const rows = data?.page ?? [];

  return (
    <DrawerContent className='max-w-4xl mx-auto'>
      <DrawerHeader>
        <DrawerTitle>
          <div className='flex flex-row items-center justify-center py-4'>
            {user ? (
              <BasedAvatar
                src={user?.imageUrl}
                fullName={user?.name}
                className='w-8 h-8 md:w-12 md:h-12'
              />
            ) : (
              <Image
                src='/favicon.png'
                alt='Tech Tracker Logo'
                width={32}
                height={32}
                className='w-8 h-8 md:w-12 md:h-12'
              />
            )}
            <h1 className='text-lg md:text-2xl lg:text-4xl font-bold pl-2 md:pl-4'>
              {user ? `${user.name ?? 'Technician'}'s History` : 'All History'}
            </h1>
          </div>
        </DrawerTitle>
      </DrawerHeader>

      <div className='px-4'>
        <ScrollArea className='h-96 w-full px-6'>
          {isLoading ? (
            <div className='flex justify-center items-center h-32'>
              <div className='animate-spin rounded-full h-8 w-8 border-b-2 border-primary' />
            </div>
          ) : rows.length === 0 ? (
            <div className='flex justify-center items-center h-32'>
              <p className='text-muted-foreground'>No history found</p>
            </div>
          ) : (
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className='font-semibold'>Name</TableHead>
                  <TableHead className='font-semibold'>Status</TableHead>
                  <TableHead className='font-semibold'>Updated By</TableHead>
                  <TableHead className='font-semibold text-right'>
                    Date &amp; Time
                  </TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rows.map((r, idx) => (
                  <TableRow key={`${r.status?.id ?? 'no-status'}-${idx}`}>
                    <TableCell className='font-medium'>
                      {r.user.name ?? 'Technician'}
                    </TableCell>
                    <TableCell className='max-w-xs'>
                      <div className='truncate' title={r.status?.message ?? ''}>
                        {r.status?.message ?? 'No status'}
                      </div>
                    </TableCell>
                    <TableCell className='text-sm text-muted-foreground'>
                      {r.status?.updatedBy?.name ?? ''}
                    </TableCell>
                    <TableCell className='text-right text-sm'>
                      {r.status
                        ? `${formatTime(r.status.updatedAt)} · ${formatDate(
                            r.status.updatedAt,
                          )}`
                        : '--:-- · --/--'}
                    </TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          )}
        </ScrollArea>
      </div>

      <DrawerFooter>
        <Pagination>
          <PaginationContent>
            <PaginationPrevious
              href='#'
              onClick={(e) => {
                e.preventDefault();
                handlePrev();
              }}
              aria-disabled={!canPrev}
              className={!canPrev ? 'pointer-events-none opacity-50' : ''}
            />
            <div className='flex items-center gap-2 text-sm text-muted-foreground'>
              <span>Page</span>
              <span className='font-bold text-foreground'>{pageIndex + 1}</span>
            </div>
            <PaginationNext
              href='#'
              onClick={(e) => {
                e.preventDefault();
                handleNext();
              }}
              aria-disabled={!canNext}
              className={!canNext ? 'pointer-events-none opacity-50' : ''}
            />
          </PaginationContent>
        </Pagination>

        <DrawerClose asChild>
          <Button variant='outline' className='mt-4'>
            Close
          </Button>
        </DrawerClose>
      </DrawerFooter>
    </DrawerContent>
  );
};
