import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { useAuth } from "@/hooks/use-auth";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { toast } from "sonner";
import { ArrowLeft } from "lucide-react";
import { z } from "zod";

export const Route = createFileRoute("/_authenticated/bookings/new")({
  head: () => ({ meta: [{ title: "New booking · SkillKonnect" }] }),
  validateSearch: (search: Record<string, unknown>) => ({
    trainer: typeof search.trainer === "string" ? search.trainer : undefined,
    trade: typeof search.trade === "string" ? search.trade : undefined,
  }),
  component: NewBookingPage,
});

const TRADES = ["Carpentry", "Tailoring", "Welding", "Catering", "Coding", "Electrical", "Plumbing", "Hairdressing"];

const schema = z.object({
  trainer_id: z.string().uuid("Pick a trainer"),
  trade: z.string().min(2).max(60),
  scheduled_at: z.string().min(1, "Pick a date and time"),
  duration_minutes: z.number().int().min(15).max(600),
  location: z.string().max(200).optional(),
  notes: z.string().max(1000).optional(),
  hourly_rate: z.number().min(0).max(1000000).optional(),
});

type TrainerOption = { id: string; full_name: string | null; organization: string | null };

function NewBookingPage() {
  const { user, hasRole, loading } = useAuth();
  const navigate = useNavigate();
  const { trainer: prefillTrainer, trade: prefillTrade } = Route.useSearch();
  const [trainers, setTrainers] = useState<TrainerOption[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [form, setForm] = useState({
    trainer_id: prefillTrainer ?? "",
    trade: prefillTrade && TRADES.includes(prefillTrade) ? prefillTrade : TRADES[0],
    scheduled_at: "",
    duration_minutes: 60,
    location: "",
    notes: "",
    hourly_rate: "",
  });

  useEffect(() => {
    (async () => {
      const { data: roleRows } = await supabase
        .from("user_roles")
        .select("user_id")
        .eq("role", "trainer");
      const ids = (roleRows ?? []).map((r) => r.user_id);
      if (ids.length === 0) return;
      const { data: profs } = await supabase
        .from("profiles")
        .select("id, full_name, organization")
        .in("id", ids);
      setTrainers((profs as TrainerOption[]) ?? []);
    })();
  }, []);

  if (!loading && !hasRole("school")) {
    return (
      <div className="container-prose py-16 text-center">
        <p className="text-muted-foreground">Only school accounts can create bookings.</p>
        <Button asChild variant="link"><Link to="/dashboard">Back to dashboard</Link></Button>
      </div>
    );
  }

  async function onSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!user) return;
    const parsed = schema.safeParse({
      ...form,
      duration_minutes: Number(form.duration_minutes),
      hourly_rate: form.hourly_rate ? Number(form.hourly_rate) : undefined,
      location: form.location || undefined,
      notes: form.notes || undefined,
    });
    if (!parsed.success) {
      toast.error(parsed.error.issues[0]?.message ?? "Invalid input");
      return;
    }
    setSubmitting(true);
    const { error } = await supabase.from("bookings").insert({
      school_id: user.id,
      trainer_id: parsed.data.trainer_id,
      trade: parsed.data.trade,
      scheduled_at: new Date(parsed.data.scheduled_at).toISOString(),
      duration_minutes: parsed.data.duration_minutes,
      location: parsed.data.location ?? null,
      notes: parsed.data.notes ?? null,
      hourly_rate: parsed.data.hourly_rate ?? null,
    });
    setSubmitting(false);
    if (error) toast.error(error.message);
    else {
      toast.success("Booking request sent");
      navigate({ to: "/bookings" });
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-30 backdrop-blur bg-background/80 border-b border-border/60">
        <div className="container-prose flex h-16 items-center">
          <Button variant="ghost" size="sm" asChild className="gap-1.5">
            <Link to="/bookings"><ArrowLeft className="h-4 w-4" /> Bookings</Link>
          </Button>
        </div>
      </header>

      <main className="container-prose py-8 max-w-2xl">
        <Card className="border-border/60">
          <CardHeader>
            <CardTitle>Request a trainer</CardTitle>
            <CardDescription>The trainer will be notified and can accept or decline.</CardDescription>
          </CardHeader>
          <CardContent>
            <form onSubmit={onSubmit} className="space-y-4">
              <div className="space-y-1.5">
                <Label>Trainer</Label>
                <Select value={form.trainer_id} onValueChange={(v) => setForm({ ...form, trainer_id: v })}>
                  <SelectTrigger><SelectValue placeholder={trainers.length ? "Select a trainer" : "No trainers available yet"} /></SelectTrigger>
                  <SelectContent>
                    {trainers.map((t) => (
                      <SelectItem key={t.id} value={t.id}>
                        {t.full_name || "Unnamed trainer"}{t.organization ? ` · ${t.organization}` : ""}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-1.5">
                <Label>Trade / skill</Label>
                <Select value={form.trade} onValueChange={(v) => setForm({ ...form, trade: v })}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent>
                    {TRADES.map((t) => <SelectItem key={t} value={t}>{t}</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>

              <div className="grid sm:grid-cols-2 gap-4">
                <div className="space-y-1.5">
                  <Label htmlFor="scheduled_at">Date & time</Label>
                  <Input id="scheduled_at" type="datetime-local" required
                    value={form.scheduled_at}
                    onChange={(e) => setForm({ ...form, scheduled_at: e.target.value })} />
                </div>
                <div className="space-y-1.5">
                  <Label htmlFor="duration">Duration (minutes)</Label>
                  <Input id="duration" type="number" min={15} max={600} step={15} required
                    value={form.duration_minutes}
                    onChange={(e) => setForm({ ...form, duration_minutes: Number(e.target.value) })} />
                </div>
              </div>

              <div className="space-y-1.5">
                <Label htmlFor="location">School venue</Label>
                <Input id="location" placeholder="School address, campus or classroom" maxLength={200}
                  value={form.location}
                  onChange={(e) => setForm({ ...form, location: e.target.value })} />
              </div>

              <div className="space-y-1.5">
                <Label htmlFor="rate">Proposed rate (₦ / hour)</Label>
                <Input id="rate" type="number" min={0} step="0.01"
                  value={form.hourly_rate}
                  onChange={(e) => setForm({ ...form, hourly_rate: e.target.value })} />
              </div>

              <div className="space-y-1.5">
                <Label htmlFor="notes">Notes for the trainer</Label>
                <Textarea id="notes" rows={4} maxLength={1000}
                  placeholder="Class size, level, materials, learning goals…"
                  value={form.notes}
                  onChange={(e) => setForm({ ...form, notes: e.target.value })} />
              </div>

              <Button type="submit" disabled={submitting || !form.trainer_id} className="w-full">
                {submitting ? "Sending request…" : "Send booking request"}
              </Button>
            </form>
          </CardContent>
        </Card>
      </main>
    </div>
  );
}
