<script lang="ts">
  import type { Todo, ExtractPayload } from "@<@var(context.project.name)>/rpc";
  import { getTodoCollection } from "$lib/todocollectionscontext";
	import * as Card from "../ui/card/index";
	import * as Field from "../ui/field/index";
	import Input from "../ui/input/input.svelte";
	import Checkbox from "../ui/checkbox/checkbox.svelte";
	import Button from "../ui/button/button.svelte";
	import { DeleteIcon } from "@lucide/svelte"
  let { todo } : { todo:ExtractPayload<Todo> } = $props();
  let todoState = $state(todo)
  const todoCollection = getTodoCollection();
  const update = () => {
    todoCollection.update(todoState.id,(draft) => {
      draft.done = todoState.done;
      draft.task = todoState.task;
    })
  }
  const del = () => {
    if (todoState.id) {
      todoCollection.delete(todoState.id)
    }
  }
</script>

<Card.Card class="p-5" onkeydown={()=>update()}>
  <Card.CardContent>
    <Field.FieldSet>
      <Field.Field>
        <Field.Label>
          task
        </Field.Label>
        <Field.FieldContent>
          <Input bind:value={todoState.task}/>
        </Field.FieldContent>
      </Field.Field>
      <Field.Field>
        <Field.Label>
          done
        </Field.Label>
        <Field.FieldContent onclick={()=>update()}>
          <Checkbox bind:checked={todoState.done}/>
        </Field.FieldContent>
      </Field.Field>
      <div class="flex flex-row">
      <Field.Field>
        <Field.Label>
          Created
        </Field.Label>
        <Field.FieldContent>
          {(new Date(todoState.createdAt||"now")).toLocaleString()}
        </Field.FieldContent>
      </Field.Field>
      <Field.Field>
        <Field.Label>
          Updated
        </Field.Label>
        <Field.FieldContent>
          {(new Date(todoState.updatesAt||"now")).toLocaleString()}
        </Field.FieldContent>
      </Field.Field>
      <Button variant='destructive' onclick={del}>
        <DeleteIcon/>
      </Button>
      </div>
    </Field.FieldSet>
  </Card.CardContent>
</Card.Card>

