import Popover from "@/components/Popover";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { ConvertJSONToFormData, ServerRequest } from "@/lib/actions";
import { LocaleDate } from "@/lib/utils";
import { fetchLastOpenNote } from "@/services/notes/fetchNotes";
import {
  faArrowsRotate,
  faNoteSticky,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
import { toast } from "sonner";

type CellProps = {
  row: ProjectData;
};

function LastNoteSkeleton() {
  return (
    <>
      <div className="space-y-1">
        <div>
          <Skeleton className="h-7 w-full rounded" />
        </div>
        <div>
          <Skeleton className="h-4 w-full rounded" />
        </div>
      </div>
      <div>
        <Skeleton className="h-5 w-full rounded" />
      </div>
      <div>
        <div>
          <p className="flex items-center gap-2">
            <FontAwesomeIcon icon={faArrowsRotate} className="animate-spin" />
            Loading last note...
          </p>
        </div>
      </div>
    </>
  );
}

function LastNote({ row }: CellProps) {
  const params: { lang: string } = useParams();

  const [lastNote, setLastNote] = useState<DomainNote | "error">();

  const handleFetchlastNote = async () => {
    const formData = ConvertJSONToFormData({
      id: row.id,
    });
    const result = await ServerRequest(fetchLastOpenNote(formData));

    if (!result.operation) {
      toast.error(result.message);
      return setLastNote("error");
    }

    setLastNote(result.data);
  };

  useEffect(() => {
    handleFetchlastNote();
  }, [row.id]);

  return (
    <div className="m-2 w-[300px] space-y-4 rounded bg-white p-4 shadow">
      {!lastNote ? (
        <LastNoteSkeleton />
      ) : lastNote === "error" ? (
        <p>
          An error has occurred while fetching the last note, please try again
          later.
        </p>
      ) : (
        <>
          <div>
            <h2 className="animate-[fade-in_0.5s_ease-in-out] text-lg font-bold">
              {lastNote.title}
            </h2>
            <p className="animate-[fade-in_0.5s_ease-in-out] text-xs text-neutral-500">
              {LocaleDate(lastNote.updatedAt, params.lang).long()}
            </p>
          </div>
          <p className="animate-[fade-in_0.5s_ease-in-out]">{lastNote.note}</p>
          <div>
            <Link
              className="animate-[fade-in_0.5s_ease-in-out] text-primary-600"
              href={`/projects/${row.name}/files?notes=show`}
            >
              <p>View all notes...</p>
            </Link>
          </div>
        </>
      )}
    </div>
  );
}

export default function Notes({ row }: CellProps) {
  return (
    row.notes && (
      <div className="relative mx-auto w-fit self-center">
        <Popover className="z-10" content={<LastNote row={row} />}>
          <Button
            variant="soft"
            color="primary"
            size="sm"
            isIcon
            rounded
            decorator={faNoteSticky}
          />
        </Popover>
        <span className="absolute right-0 top-0 -m-0.5 flex h-6 w-6 origin-top-right scale-50 items-center justify-center rounded-full bg-red-500 text-white">
          {row.notes > 9 ? "+" : row.notes}
        </span>
      </div>
    )
  );
}
