import { useState } from "react";
import { router } from "@inertiajs/react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { Input } from "@/components/ui/input";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
import { Search, GraduationCap, Clock, SendHorizonal, Loader2, CheckCircle2 } from "lucide-react";
import { useAuth } from "@/hooks/useAuth";
import { toast } from "sonner";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const CourseLookup = () => {
  const { user, companyId } = useAuth();
  const [search, setSearch] = useState("");
  const [selectedCourse, setSelectedCourse] = useState<any>(null);
  const [submitted, setSubmitted] = useState<Set<string>>(new Set());

  const { data: courses, isLoading } = useQuery({
    queryKey: ["delegate-course-lookup", search],
    queryFn: async () => {
      if (!search || search.length < 2) return [];
      const res = await fetch(`/api/delegate/courses/search?q=${encodeURIComponent(search)}`);
      if (!res.ok) return [];
      const data = await res.json();
      return data || [];
    },
    enabled: search.length >= 2,
  });

  const requestMutation = useMutation({
    mutationFn: async (course: any) => {
      if (!user || !companyId) throw new Error("Not authenticated");
      const fullName = user.full_name || user.email?.split("@")[0] || "Delegate";

      // Use today as a placeholder start date — manager will assign actual date
      const today = new Date().toISOString().split("T")[0];

      const res = await fetch('/api/delegate/booking-requests', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({
          delegate_user_id: user.id,
          delegate_email: user.email,
          delegate_name: fullName,
          company_id: companyId,
          course_id: course.id,
          start_date: today,
          manager_notes: "Requested via course lookup — date TBC",
        }),
      });
      if (!res.ok) throw new Error("Failed to submit request");
    },
    onSuccess: () => {
      setSubmitted((prev) => new Set(prev).add(selectedCourse.id));
      toast.success("Request sent to your manager");
    },
    onError: (e: Error) => toast.error(e.message),
  });

  return (
    <div className="space-y-3">
      <div className="relative">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
        <Input
          placeholder="Search courses by name…"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          className="pl-9"
        />
      </div>

      {search.length >= 2 && (
        <div className="space-y-2">
          {isLoading && <p className="text-xs text-muted-foreground py-2">Searching…</p>}
          {courses?.length === 0 && !isLoading && (
            <p className="text-xs text-muted-foreground py-2">No courses found for "{search}"</p>
          )}
          {courses?.map((c: any) => (
            <Card
              key={c.id}
              className="cursor-pointer hover:border-primary/40 transition-colors"
              onClick={() => {
                // Company-linked delegates raise a request their manager approves
                // and pays for. Individual delegates have no manager, so send them
                // to the course page to book (and pay) for it themselves.
                if (companyId) {
                  setSelectedCourse(c);
                } else {
                  router.visit(`/course/${c.slug}`);
                }
              }}
            >
              <CardContent className="py-3 flex items-center gap-3">
                <div className="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                  <GraduationCap className="w-4 h-4 text-primary" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-medium text-foreground truncate">{c.title}</p>
                  <div className="flex items-center gap-2 mt-0.5">
                    <Badge variant="outline" className="text-[10px]">{c.category}</Badge>
                    <span className="text-[11px] text-muted-foreground flex items-center gap-0.5">
                      <Clock className="w-3 h-3" /> {c.days} day{c.days !== 1 ? "s" : ""}
                    </span>
                  </div>
                </div>
                <div className="text-right shrink-0">
                  <p className="text-sm font-bold text-foreground">£{(c.price_cents / 100).toFixed(2)}</p>
                  <p className="text-[10px] text-muted-foreground">per delegate</p>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {!search && (
        <p className="text-xs text-muted-foreground text-center py-2">
          Type at least 2 characters to search available courses
        </p>
      )}

      <Dialog open={!!selectedCourse} onOpenChange={(o) => !o && setSelectedCourse(null)}>
        {selectedCourse && (
          <DialogContent className="sm:max-w-md">
            <DialogHeader>
              <DialogTitle>Request This Course</DialogTitle>
              <DialogDescription>
                Your manager will be notified and will assign a date and confirm the booking.
              </DialogDescription>
            </DialogHeader>

            {submitted.has(selectedCourse.id) ? (
              <div className="py-6 text-center">
                <CheckCircle2 className="w-12 h-12 mx-auto text-green-600 mb-3" />
                <p className="text-sm font-medium text-foreground">Request submitted!</p>
                <p className="text-xs text-muted-foreground mt-1">Your manager has been notified.</p>
              </div>
            ) : (
              <div className="space-y-4">
                <div className="bg-muted/50 rounded-lg p-4 space-y-2 text-sm">
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Course</span>
                    <span className="font-medium text-foreground">{selectedCourse.title}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Category</span>
                    <span className="font-medium text-foreground">{selectedCourse.category}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Duration</span>
                    <span className="font-medium text-foreground">{selectedCourse.days} day{selectedCourse.days !== 1 ? "s" : ""}</span>
                  </div>
                  <div className="flex justify-between">
                    <span className="text-muted-foreground">Price</span>
                    <span className="font-bold text-foreground">£{(selectedCourse.price_cents / 100).toFixed(2)}</span>
                  </div>
                </div>

                <div className="flex gap-2">
                  <Button variant="outline" className="flex-1" onClick={() => setSelectedCourse(null)}>
                    Cancel
                  </Button>
                  <Button
                    className="flex-1"
                    onClick={() => requestMutation.mutate(selectedCourse)}
                    disabled={requestMutation.isPending}
                  >
                    {requestMutation.isPending ? (
                      <><Loader2 className="w-4 h-4 mr-2 animate-spin" /> Sending…</>
                    ) : (
                      <><SendHorizonal className="w-4 h-4 mr-2" /> Send Request</>
                    )}
                  </Button>
                </div>
              </div>
            )}
          </DialogContent>
        )}
      </Dialog>
    </div>
  );
};

export default CourseLookup;
