<script lang="ts">
  import {
    Table,
    TableBody,
    TableBodyCell,
    TableBodyRow,
    TableHead,
    TableHeadCell,
  } from 'flowbite-svelte';

  import type { SolutionTableProps } from '$features/workbooks/types/workbook';

  import TitleTableHeadCell from '$features/workbooks/components/list/TitleTableHeadCell.svelte';
  import TitleTableBodyCell from '$features/workbooks/components/list/TitleTableBodyCell.svelte';
  import WorkbookProgressCell from '$features/workbooks/components/list/WorkbookProgressCell.svelte';
  import WorkbookCompletionCell from '$features/workbooks/components/list/WorkbookCompletionCell.svelte';
  import WorkbookAuthorActionsCell from '$features/workbooks/components/list/WorkbookAuthorActionsCell.svelte';
  import EmptyWorkbookList from '$features/workbooks/components/list/EmptyWorkbookList.svelte';

  import { canRead } from '$lib/utils/authorship';
  import { getTaskResult } from '$features/workbooks/utils/workbooks';

  let { workbooks, userId, role, taskResults }: SolutionTableProps = $props();

  let visibleWorkbooks = $derived(
    workbooks.filter((workbook) => canRead(workbook.isPublished, userId, workbook.authorId)),
  );
</script>

{#if visibleWorkbooks.length >= 1}
  <div class="overflow-auto rounded-md border border-gray-200 dark:border-gray-100">
    <Table shadow class="text-md">
      <TableHead class="text-sm bg-gray-100">
        <TableHeadCell>作者</TableHeadCell>
        <TitleTableHeadCell />
        <TableHeadCell class="text-left min-w-[240px] max-w-[1440px] px-0">回答状況</TableHeadCell>
        <TableHeadCell></TableHeadCell>
        <TableHeadCell class="text-center px-0">修了</TableHeadCell>
        <TableHeadCell></TableHeadCell>
      </TableHead>

      <TableBody class="divide-y divide-gray-200 dark:divide-gray-700">
        {#each visibleWorkbooks as workbook (workbook.id)}
          <TableBodyRow>
            <TableBodyCell>
              <div class="truncate min-w-[96px] max-w-[120px]">
                {workbook.authorName}
              </div>
            </TableBodyCell>

            <TitleTableBodyCell {workbook} />

            <WorkbookProgressCell
              workBookTasks={workbook.workBookTasks}
              taskResults={getTaskResult(workbook.id, taskResults)}
            />

            <WorkbookCompletionCell
              workBookTasks={workbook.workBookTasks}
              taskResults={getTaskResult(workbook.id, taskResults)}
            />

            <WorkbookAuthorActionsCell {workbook} {userId} {role} />
          </TableBodyRow>
        {/each}
      </TableBody>
    </Table>
  </div>
{:else}
  <EmptyWorkbookList />
{/if}
