"use client";

import React, { useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch, resolveToApiOrigin } from "@/lib/api";
import { Button } from "@/components/shared/Button";

export function EventForm({ onCreated }: { onCreated?: () => void }) {
  const { token } = useAuth();
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [startDate, setStartDate] = useState("");
  const [endDate, setEndDate] = useState("");
  const [price, setPrice] = useState<number>(0);
  const [picture, setPicture] = useState("");
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [uploadingImage, setUploadingImage] = useState(false);
  const [isHidden, setIsHidden] = useState(false);
  const [requiresAuth, setRequiresAuth] = useState(true);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleImageFile(file: File) {
    setUploadingImage(true);
    setError(null);
    try {
      const fd = new FormData();
      fd.append("image", file);
      const data = await apiFetch<{ url: string }>("/api/uploads/event-image", {
        method: "POST",
        authToken: token,
        body: fd,
      });
      setPicture(data.url);
      setImagePreview(URL.createObjectURL(file));
    } catch (e: any) {
      setError(e?.message || "Image upload failed");
    } finally {
      setUploadingImage(false);
    }
  }

  function clearImage() {
    setImagePreview(null);
    setPicture("");
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!token) { setError("Please login"); return; }
    setLoading(true);
    setError(null);
    try {
      await apiFetch("/api/events", {
        method: "POST",
        authToken: token,
        body: { title, description, startDate, endDate, price, picture, isHidden, requiresAuth },
      });
      onCreated?.();
      setTitle(""); setDescription(""); setStartDate(""); setEndDate(""); setPrice(0); setPicture(""); setImagePreview(null); setIsHidden(false); setRequiresAuth(true);
    } catch (e: any) {
      setError(e?.message || "Failed to create event");
    } finally {
      setLoading(false);
    }
  }

  const previewSrc = imagePreview || (picture ? resolveToApiOrigin(picture) : null);

  return (
    <form onSubmit={submit} className="space-y-3">
      <div>
        <label className="block text-sm font-medium">Title</label>
        <input className="w-full border rounded px-3 py-2" value={title} onChange={(e) => setTitle(e.target.value)} required />
      </div>
      <div>
        <label className="block text-sm font-medium">Description</label>
        <textarea className="w-full border rounded px-3 py-2" value={description} onChange={(e) => setDescription(e.target.value)} />
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
        <div>
          <label className="block text-sm font-medium">Start</label>
          <input type="datetime-local" className="w-full border rounded px-3 py-2" value={startDate} onChange={(e) => setStartDate(e.target.value)} required />
        </div>
        <div>
          <label className="block text-sm font-medium">End</label>
          <input type="datetime-local" className="w-full border rounded px-3 py-2" value={endDate} onChange={(e) => setEndDate(e.target.value)} required />
        </div>
      </div>
      <div>
        <label className="block text-sm font-medium">Price (R)</label>
        <input type="number" step="0.01" className="w-full border rounded px-3 py-2" value={price} onChange={(e) => setPrice(parseFloat(e.target.value))} />
      </div>
      <div>
        <label className="block text-sm font-medium mb-1">Event image</label>
        {previewSrc && (
          <div className="relative inline-block mb-2">
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={previewSrc} alt="Preview" className="h-32 object-cover rounded border" />
            <button
              type="button"
              onClick={clearImage}
              className="absolute top-1 right-1 bg-white text-red-500 hover:text-red-700 rounded px-1 text-xs shadow"
            >✕</button>
          </div>
        )}
        <div className="flex gap-2 items-center">
          <label className={`cursor-pointer px-3 py-2 text-sm rounded border bg-gray-50 hover:bg-gray-100 ${uploadingImage ? "opacity-50 pointer-events-none" : ""}`}>
            <input
              type="file"
              accept="image/*"
              className="hidden"
              disabled={uploadingImage}
              onChange={e => {
                const file = e.target.files?.[0];
                if (file) handleImageFile(file);
                e.target.value = "";
              }}
            />
            {uploadingImage ? "Uploading…" : "Upload image"}
          </label>
          <span className="text-xs text-gray-400">or</span>
          <input
            className="flex-1 border rounded px-3 py-2 text-sm"
            placeholder="https://…"
            value={picture}
            onChange={e => { setPicture(e.target.value); setImagePreview(null); }}
          />
        </div>
      </div>
      <div className="border rounded-lg p-3 bg-gray-50 space-y-2">
        <div className="text-xs font-semibold text-gray-500 uppercase tracking-wide mb-1">Visibility &amp; Access</div>
        <label className="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" checked={isHidden} onChange={e => setIsHidden(e.target.checked)} />
          <span className="text-sm text-gray-700">
            <span className="font-medium">Hidden event</span> — not shown in the public listing; accessible by direct link only
          </span>
        </label>
        <label className="flex items-center gap-2 cursor-pointer">
          <input type="checkbox" checked={!requiresAuth} onChange={e => setRequiresAuth(!e.target.checked)} />
          <span className="text-sm text-gray-700">
            <span className="font-medium">Allow unauthenticated registration</span> — guests can register without creating an account
          </span>
        </label>
      </div>
      {error && <p className="text-sm text-red-600">{error}</p>}
      <Button type="submit" loading={loading}>Create Event</Button>
    </form>
  );
}