import BoxDisplay from '@/components/BoxDisplay';
import { boxColumns } from '@/components/boxes/box-columns';
import CreateBoxAction from '@/components/boxes/create-box-dialog';
import SearchInput from '@/components/ui/search-input';
import { Skeleton } from '@/components/ui/skeleton';
import useDebounced from '@/hooks/use-debounced';
import { m } from '@/paraglide/messages';
import { boxQueries } from '@/service/queries';
import { PackageIcon } from '@phosphor-icons/react';
import { useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { Card, CardContent, CardHeader, CardTitle } from '@ui/card';
import { useState } from 'react';

export const Route = createFileRoute('/(app)/(auth)/kanri/boxes')({
  component: RouteComponent,
  staticData: { breadcrumb: () => m.nav_boxes() },
});

function RouteComponent() {
  const [page, setPage] = useState(1);
  const [pageLimit, setPageLimit] = useState(10);
  const [searchKeyword, setSearchKeyword] = useState('');
  const debouncedSearch = useDebounced(searchKeyword, 500);

  const { data, isLoading } = useQuery(
    boxQueries.list({
      page,
      limit: pageLimit,
      keyword: debouncedSearch,
    }),
  );

  const onSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setSearchKeyword(e.target.value);
    setPage(1);
  };

  if (isLoading) {
    return (
      <div className="@container/main flex flex-1 flex-col gap-2 p-4">
        <Skeleton className="h-130 w-full" />
      </div>
    );
  }

  return (
    <div className="@container/main flex flex-1 flex-col gap-2 p-4">
      <div className="*:data-[slot=card]:from-primary/5 *:data-[slot=card]:to-card dark:*:data-[slot=card]:bg-card *:data-[slot=card]:bg-linear-to-br *:data-[slot=card]:shadow-xs">
        <Card>
          <CardHeader>
            <CardTitle className="text-xl flex items-center gap-2">
              <PackageIcon size={24} />
              {m.boxes_page_ui_title()}
            </CardTitle>
          </CardHeader>
          <CardContent className="flex flex-col gap-4">
            <div className="flex items-center justify-between gap-2">
              <SearchInput
                keywords={searchKeyword}
                setKeyword={setSearchKeyword}
                onChange={onSearchChange}
                placeholder={m.common_search_placeholder_for_box()}
              />
              <CreateBoxAction />
            </div>
            {data && (
              <BoxDisplay
                data={data.result || []}
                columns={boxColumns}
                page={page}
                setPage={setPage}
                limit={pageLimit}
                setLimit={setPageLimit}
                pagination={data.pagination}
              />
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
