'use client';
import { useEffect, useMemo, useState } from 'react';
import { useQuery } from 'convex/react';
import { api } from '~/convex/_generated/api';
import { formatDate, formatTime } from '@/lib/utils';
import {
  Pagination,
  PaginationContent,
  PaginationNext,
  PaginationPrevious,
  ScrollArea,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui';

const PAGE_SIZE = 25;

export const HistoryTable = () => {
  const [pageIndex, setPageIndex] = useState(0);
  const [cursors, setCursors] = useState<(string | null)[]>([null]);

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

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

  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 (
    <div className='w-full px-4 sm:px-6'>
      {/* Mobile: card list */}
      <div className='md:hidden'>
        <ScrollArea className='max-h-[70vh] w-full'>
          {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>
          ) : (
            <div className='space-y-2 pb-2'>
              {rows.map((r, idx) => {
                const key = `${r.status?.id ?? 'no-status'}-${idx}`;
                const name = r.user.name ?? 'Technician';
                const msg = r.status?.message ?? 'No status';
                const updatedBy = r.status?.updatedBy?.name ?? null;
                const stamp = r.status
                  ? `${formatTime(r.status.updatedAt)} · ${formatDate(
                      r.status.updatedAt,
                    )}`
                  : '--:-- · --/--';

                return (
                  <div key={key} className='rounded-lg border p-3'>
                    <div className='flex items-start justify-between'>
                      <div className='min-w-0'>
                        <div className='font-medium truncate'>{name}</div>
                        <div
                          className='text-sm text-muted-foreground
                            mt-0.5 line-clamp-2 break-words'
                          title={msg}
                        >
                          {msg}
                        </div>
                      </div>
                      {updatedBy && (
                        <span
                          className='ml-3 shrink-0 rounded
                            bg-muted px-2 py-0.5 text-xs
                            text-foreground'
                          title={`Updated by ${updatedBy}`}
                        >
                          {updatedBy}
                        </span>
                      )}
                    </div>

                    <div
                      className='mt-2 flex items-center gap-2
                        text-xs text-muted-foreground'
                    >
                      <span>{stamp}</span>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </ScrollArea>
      </div>

      {/* Desktop: original table */}
      <div className='hidden md:block'>
        <ScrollArea className='h-[600px] w-full px-4'>
          {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>

      {/* Pagination */}
      <div className='mt-3 sm:mt-4'>
        <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>
      </div>
    </div>
  );
};
