import DataTable from '@/components/DataTable';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import SearchInput from '@/components/ui/search-input';
import { Skeleton } from '@/components/ui/skeleton';
import AddNewUserButton from '@/components/user/add-new-user-dialog';
import { userColumns } from '@/components/user/user-column';
import useDebounced from '@hooks/use-debounced';
import { m } from '@paraglide/messages';
import { UsersIcon } from '@phosphor-icons/react';
import { usersQueries } from '@service/queries';
import { useQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import { useState } from 'react';

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

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(
    usersQueries.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 className="border-b">
            <CardTitle className="text-xl flex items-center gap-2">
              <UsersIcon size={24} />
              {m.users_page_ui_title()}
            </CardTitle>
          </CardHeader>
          <CardContent className="flex flex-col gap-4">
            <div className="flex items-center justify-between">
              <SearchInput
                keywords={searchKeyword}
                setKeyword={setSearchKeyword}
                onChange={onSearchChange}
              />
              <AddNewUserButton />
            </div>
            {data && (
              <DataTable
                data={data.result || []}
                columns={userColumns}
                page={page}
                setPage={setPage}
                limit={pageLimit}
                setLimit={setPageLimit}
                pagination={data.pagination}
              />
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
