import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { AppShell } from "@/components/AppShell";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/hooks/useAuth";
import { fetchCategories, fetchCities } from "@/lib/hotspots";
import { cn } from "@/lib/utils";

export const Route = createFileRoute("/_authenticated/submit")({
  head: () => ({
    meta: [
      { title: "Submit an event — HOTSPOTS" },
      { name: "description", content: "Add your event to HOTSPOTS for review and publication." },
      { property: "og:title", content: "Submit an event — HOTSPOTS" },
      { property: "og:description", content: "Share your event with people near you." },
    ],
  }),
  component: SubmitPage,
});

function SubmitPage() {
  const { userId } = useAuth();
  const navigate = useNavigate();
  const [busy, setBusy] = useState(false);
  const [form, setForm] = useState({
    title: "",
    description: "",
    venue: "",
    address: "",
    starts_at: "",
    ticket_url: "",
    image_url: "",
    price_min: "",
    is_free: true,
  });
  const [cityName, setCityName] = useState("");
  const [uploading, setUploading] = useState(false);
  const [categoryId, setCategoryId] = useState("");

  const { data: cities = [] } = useQuery({ queryKey: ["cities"], queryFn: fetchCities });
  const { data: categories = [] } = useQuery({ queryKey: ["categories"], queryFn: fetchCategories });

  async function uploadCover(file: File) {
    if (!userId) return;
    if (file.size > 5 * 1024 * 1024) {
      toast.error("Image must be under 5MB");
      return;
    }
    setUploading(true);
    const ext = file.name.split(".").pop() || "jpg";
    const path = `${userId}/${Date.now().toString(36)}.${ext}`;
    const up = await supabase.storage.from("event-covers").upload(path, file, {
      contentType: file.type,
    });
    if (up.error) {
      setUploading(false);
      toast.error(up.error.message);
      return;
    }
    const signed = await supabase.storage
      .from("event-covers")
      .createSignedUrl(path, 60 * 60 * 24 * 365 * 10);
    setUploading(false);
    if (signed.error) {
      toast.error(signed.error.message);
      return;
    }
    setForm((f) => ({ ...f, image_url: signed.data.signedUrl }));
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    if (!cityName.trim() || !categoryId) {
      toast.error("Enter a city and pick a category");
      return;
    }
    setBusy(true);
    const cityRes = await supabase.rpc("add_city", { _name: cityName.trim() });
    if (cityRes.error || !cityRes.data) {
      setBusy(false);
      toast.error(cityRes.error?.message ?? "Could not save city");
      return;
    }
    const cityId = cityRes.data as string;
    const existing = cities.find((c) => c.id === cityId);
    const { data: cityRow } = existing
      ? { data: existing }
      : await supabase.from("cities").select("id, timezone, country_id").eq("id", cityId).single();
    const city = cityRow ?? { id: cityId, timezone: "Africa/Accra", country_id: null };
    const { error } = await supabase.from("events").insert({
      title: form.title,
      slug: `${form.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 60)}-${Date.now().toString(36)}`,
      description: form.description || null,
      venue: form.venue || null,
      address: form.address || null,
      starts_at: new Date(form.starts_at).toISOString(),
      timezone: city.timezone,
      city_id: city.id,
      country_id: city.country_id,
      category_id: categoryId,
      is_free: form.is_free,
      price_min: form.is_free || !form.price_min ? null : Number(form.price_min),
      ticket_url: form.ticket_url || null,
      image_url: form.image_url || null,
      submitted_by: userId,
      status: "pending",
      verification: "needs_review",
      confidence: 40,
    });
    setBusy(false);
    if (error) {
      toast.error(error.message);
      return;
    }
    toast.success("Submitted — our team will review it shortly");
    navigate({ to: "/my-events" });
  }

  return (
    <AppShell>
      <form className="max-w-2xl space-y-5" onSubmit={submit}>
        <div>
          <h1 className="font-display text-2xl font-extrabold">Submit an event</h1>
          <p className="text-sm text-muted-foreground">
            Your event goes through verification before it appears publicly.
          </p>
        </div>

        <div className="surface-card space-y-4 p-5">
          <div className="space-y-1.5">
            <Label htmlFor="title">Event name</Label>
            <Input
              id="title"
              required
              value={form.title}
              onChange={(e) => setForm({ ...form, title: e.target.value })}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="desc">Description</Label>
            <Textarea
              id="desc"
              value={form.description}
              onChange={(e) => setForm({ ...form, description: e.target.value })}
            />
          </div>
          <div className="grid gap-4 sm:grid-cols-2">
            <div className="space-y-1.5">
              <Label htmlFor="starts">Date & time</Label>
              <Input
                id="starts"
                type="datetime-local"
                required
                value={form.starts_at}
                onChange={(e) => setForm({ ...form, starts_at: e.target.value })}
              />
            </div>
            <div className="space-y-1.5">
              <Label htmlFor="venue">Venue</Label>
              <Input
                id="venue"
                value={form.venue}
                onChange={(e) => setForm({ ...form, venue: e.target.value })}
              />
            </div>
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="address">Address</Label>
            <Input
              id="address"
              value={form.address}
              onChange={(e) => setForm({ ...form, address: e.target.value })}
            />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="city">City</Label>
            <Input
              id="city"
              required
              list="city-options"
              placeholder="Type any African city, e.g. Kigali"
              value={cityName}
              onChange={(e) => setCityName(e.target.value)}
            />
            <datalist id="city-options">
              {cities.map((c) => (
                <option key={c.id} value={c.name} />
              ))}
            </datalist>
          </div>
          <div className="space-y-1.5">
            <Label>Category</Label>
            <div className="flex flex-wrap gap-2">
              {categories.map((c) => (
                <button
                  type="button"
                  key={c.id}
                  onClick={() => setCategoryId(c.id)}
                  className={cn(
                    "rounded-full border px-3 py-1.5 text-xs",
                    categoryId === c.id ? "border-primary text-primary" : "border-border",
                  )}
                >
                  {c.emoji} {c.name}
                </button>
              ))}
            </div>
          </div>
          <div className="flex items-center justify-between">
            <Label htmlFor="free" className="text-sm font-normal">
              This event is free
            </Label>
            <Switch
              id="free"
              checked={form.is_free}
              onCheckedChange={(v) => setForm({ ...form, is_free: v })}
            />
          </div>
          {!form.is_free && (
            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-1.5">
                <Label htmlFor="price">Ticket price</Label>
                <Input
                  id="price"
                  type="number"
                  min="0"
                  value={form.price_min}
                  onChange={(e) => setForm({ ...form, price_min: e.target.value })}
                />
              </div>
              <div className="space-y-1.5">
                <Label htmlFor="ticket">Ticket link</Label>
                <Input
                  id="ticket"
                  type="url"
                  value={form.ticket_url}
                  onChange={(e) => setForm({ ...form, ticket_url: e.target.value })}
                />
              </div>
            </div>
          )}
          <div className="space-y-1.5">
            <Label htmlFor="image">Cover image</Label>
            <Input
              id="image"
              type="file"
              accept="image/*"
              disabled={uploading}
              onChange={(e) => {
                const f = e.target.files?.[0];
                if (f) void uploadCover(f);
              }}
            />
            {uploading && <p className="text-xs text-muted-foreground">Uploading…</p>}
            {form.image_url && (
              <img
                src={form.image_url}
                alt="Cover preview"
                className="mt-2 aspect-[16/10] w-full max-w-sm rounded-xl object-cover"
              />
            )}
          </div>
        </div>

        <Button type="submit" className="rounded-full px-6" disabled={busy}>
          {busy ? "Submitting…" : "Submit for review"}
        </Button>
      </form>
    </AppShell>
  );
}
