"use client";

import { useState, useTransition } from "react";
import { toggleLabelInFolder } from "@/lib/actions/folders";
import { NewFolderForm } from "@/components/labels/NewFolderForm";

interface FolderOption {
  id: string;
  name: string;
  isSaved: boolean;
}

function FolderCheckbox({
  labelId,
  folderId,
  name,
  initialSaved,
}: {
  labelId: string;
  folderId: string | null;
  name: string;
  initialSaved: boolean;
}) {
  const [saved, setSaved] = useState(initialSaved);
  const [, startTransition] = useTransition();

  return (
    <label className="flex items-center justify-between rounded border border-charcoal/10 px-3 py-2 text-sm">
      <span className="text-charcoal">{name}</span>
      <input
        type="checkbox"
        checked={saved}
        onChange={() => {
          setSaved((s) => !s);
          startTransition(() => {
            toggleLabelInFolder(labelId, folderId);
          });
        }}
        className="h-4 w-4 accent-terracotta"
      />
    </label>
  );
}

export function AddToFolderButton({
  labelId,
  isFavorited,
  folders,
  isLoggedIn,
}: {
  labelId: string;
  isFavorited: boolean;
  folders: FolderOption[];
  isLoggedIn: boolean;
}) {
  const [open, setOpen] = useState(false);
  const [refreshKey, setRefreshKey] = useState(0);

  if (!isLoggedIn) return null;

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className="rounded-full border border-charcoal/20 px-5 py-2 text-sm font-medium text-charcoal hover:bg-charcoal/5"
      >
        Add to Folder
      </button>

      {open && (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 px-6"
          onClick={() => setOpen(false)}
        >
          <div
            className="w-full max-w-sm rounded-lg bg-warm-white p-6 shadow-xl"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="font-heading text-xl font-semibold text-charcoal">
              Save to a folder
            </h2>
            <div className="mt-4 flex flex-col gap-2">
              <FolderCheckbox
                key={`favorites-${refreshKey}`}
                labelId={labelId}
                folderId={null}
                name="Favorites"
                initialSaved={isFavorited}
              />
              {folders.map((folder) => (
                <FolderCheckbox
                  key={`${folder.id}-${refreshKey}`}
                  labelId={labelId}
                  folderId={folder.id}
                  name={folder.name}
                  initialSaved={folder.isSaved}
                />
              ))}
            </div>

            <div className="mt-4 border-t border-charcoal/10 pt-4">
              <NewFolderForm onCreated={() => setRefreshKey((k) => k + 1)} />
            </div>

            <button
              type="button"
              onClick={() => setOpen(false)}
              className="mt-6 rounded-full border border-charcoal/20 px-5 py-2 text-sm font-medium text-charcoal hover:bg-charcoal/5"
            >
              Done
            </button>
          </div>
        </div>
      )}
    </>
  );
}
