"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { toast } from "@/components/admin/Toast";
import { FetchError, apiPost } from "@/lib/client-api";

export function UseTemplateButton({
  templateId,
  templateName,
  requireEventDate,
  requireLocation,
  className,
}: {
  templateId: string;
  templateName: string;
  requireEventDate: boolean;
  requireLocation: boolean;
  className?: string;
}) {
  const router = useRouter();
  const [open, setOpen] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const [title, setTitle] = useState(templateName);
  const [eventDate, setEventDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [location, setLocation] = useState("");

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      setSubmitting(true);
      const created = await apiPost<{ id: string }>(
        `/api/templates/${templateId}/use`,
        {
          title,
          description: "",
          eventDate: eventDate ? new Date(eventDate).toISOString() : null,
          endDate: endDate ? new Date(endDate).toISOString() : null,
          location: location || null,
        },
      );
      toast("Event created from template.", "success");
      setOpen(false);
      router.push(`/events/${created.id}`);
      router.refresh();
    } catch (err) {
      toast(
        err instanceof FetchError ? err.message : "Failed to use template.",
        "error",
      );
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <>
      <Button
        size="sm"
        className={className ?? "w-full"}
        onClick={() => setOpen(true)}
      >
        Use template
      </Button>
      {open ? (
        <div className="fixed inset-0 z-50 grid place-items-center bg-black/40 p-4">
          <form
            onSubmit={onSubmit}
            className="w-full max-w-md rounded-2xl border border-border bg-surface p-6 shadow-lg"
          >
            <div className="flex items-center justify-between">
              <div>
                <p className="text-xs text-muted">Use template</p>
                <h3 className="text-lg font-semibold">{templateName}</h3>
              </div>
              <button
                type="button"
                onClick={() => setOpen(false)}
                className="rounded-md p-1 text-muted hover:bg-surface-muted"
                aria-label="Close"
              >
                ✕
              </button>
            </div>
            <div className="mt-4 space-y-3">
              <div>
                <label className="mb-1 block text-xs font-medium text-muted">
                  Event title
                </label>
                <input
                  required
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  className="input"
                />
              </div>
              {requireEventDate ? (
                <div>
                  <label className="mb-1 block text-xs font-medium text-muted">
                    Start date
                  </label>
                  <input
                    type="datetime-local"
                    value={eventDate}
                    onChange={(e) => setEventDate(e.target.value)}
                    className="input"
                  />
                </div>
              ) : null}
              <div>
                <label className="mb-1 block text-xs font-medium text-muted">
                  End date (optional)
                </label>
                <input
                  type="datetime-local"
                  value={endDate}
                  onChange={(e) => setEndDate(e.target.value)}
                  className="input"
                />
              </div>
              {requireLocation ? (
                <div>
                  <label className="mb-1 block text-xs font-medium text-muted">
                    Location
                  </label>
                  <input
                    value={location}
                    onChange={(e) => setLocation(e.target.value)}
                    className="input"
                  />
                </div>
              ) : null}
            </div>
            <div className="mt-6 flex justify-end gap-2">
              <Button
                type="button"
                variant="secondary"
                size="sm"
                onClick={() => setOpen(false)}
                disabled={submitting}
              >
                Cancel
              </Button>
              <Button type="submit" size="sm" isLoading={submitting}>
                Create event
              </Button>
            </div>
            <style jsx>{`
              :global(.input) {
                width: 100%;
                border-radius: 0.5rem;
                border: 1px solid var(--border);
                background: var(--surface);
                padding: 0.5rem 0.75rem;
                font-size: 0.875rem;
                color: var(--foreground);
              }
              :global(.input:focus) {
                outline: none;
                border-color: var(--primary);
              }
            `}</style>
          </form>
        </div>
      ) : null}
    </>
  );
}
