"use client";

import { Textarea } from "../../ui/textarea";
import { Button } from "../../ui/button";
import { useState } from "react";
import { useToast } from "../../ui/use-toast";
import { CaseDocument } from "@/lib/db";
import { CaseCard } from "@/components/cards/CaseCard";
import { closeCase, reopenCase, updateCaseNotes } from "@/lib/actions";

export function CaseActions({ Case }: { Case: CaseDocument }) {
  const { toast } = useToast();
  const [caseDraft, setDraft] = useState(Case);

  return (
    <>
      <CaseCard entry={Case} />

      <Textarea
        rows={8}
        placeholder="Enter notes here... (save on unfocus)"
        className="!min-h-0 !h-[76px]"
        defaultValue={Case.notes}
        onBlur={async (e) => {
          const notes = e.currentTarget.value;
          if (notes === caseDraft.notes ?? "") return;

          try {
            await updateCaseNotes(Case._id, notes);
            setDraft((c) => ({ ...c, notes }));
            toast({
              title: "Updated report notes",
            });
          } catch (err) {
            toast({
              title: "Failed to update report notes",
              description: String(err),
              variant: "destructive",
            });
          }
        }}
      />

      <div className="flex gap-2">
        {caseDraft.status === "Open" ? (
          <>
            <Button
              className="flex-1 bg-green-400 hover:bg-green-300"
              onClick={async () => {
                try {
                  const $set = await closeCase(Case._id);
                  setDraft((c) => ({ ...c, ...$set }));
                  toast({
                    title: "Closed case",
                  });
                } catch (err) {
                  toast({
                    title: "Failed to close case",
                    description: String(err),
                    variant: "destructive",
                  });
                }
              }}
            >
              Close Case
            </Button>
          </>
        ) : (
          <>
            <Button
              className="flex-1"
              onClick={async () => {
                try {
                  const $set = await reopenCase(Case._id);
                  setDraft((c) => ({ ...c, ...$set }));
                  toast({
                    title: "Opened case again",
                  });
                } catch (err) {
                  toast({
                    title: "Failed to re-open case",
                    description: String(err),
                    variant: "destructive",
                  });
                }
              }}
            >
              Re-open Case
            </Button>
          </>
        )}
      </div>
    </>
  );
}
