"use client";

import { useRouter } from "next/navigation";
import { useState, useTransition } from "react";
import { Button } from "@/components/ui/Button";
import { Card } from "@/components/ui/Card";
import { createFromTemplate } from "@/lib/actions/elections";
import { formatDate } from "@/lib/utils/format";

interface TemplateOption {
  id: string;
  name: string;
  createdAt: Date | string;
}

export function ElectionTemplatePicker({
  templates,
}: {
  templates: TemplateOption[];
}) {
  const router = useRouter();
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  if (templates.length === 0) return null;

  return (
    <Card className="mb-5 p-4">
      <p className="text-[13px] font-bold">Start from a template</p>
      <p className="mt-1 text-[12px] text-muted">
        Creates a draft election with saved positions and security settings.
      </p>
      <ul className="mt-3 space-y-2">
        {templates.map((template) => (
          <li
            key={template.id}
            className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-border px-3 py-2"
          >
            <div>
              <p className="text-[13px] font-semibold">{template.name}</p>
              <p className="text-[11px] text-muted">
                Saved {formatDate(template.createdAt)}
              </p>
            </div>
            <Button
              type="button"
              size="sm"
              variant="outline"
              loading={isPending}
              onClick={() => {
                setError(null);
                startTransition(async () => {
                  const result = await createFromTemplate({
                    templateId: template.id,
                  });
                  if (!result.success || !result.data) {
                    setError(
                      result.success
                        ? "Could not create from template"
                        : result.error
                    );
                    return;
                  }
                  router.push(`/app/elections/${result.data.electionId}`);
                });
              }}
            >
              Use template
            </Button>
          </li>
        ))}
      </ul>
      {error && (
        <p className="mt-3 rounded-md bg-danger-bg px-3 py-2 text-[13px] text-danger">
          {error}
        </p>
      )}
    </Card>
  );
}
